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/master
|
<repo_name>lochsh/c-lexer-exercise<file_sep>/README.md
Skeleton code for implementing a C lexer in Python, to be completed as an
exercise.
Note that the lack of sum types (aka tagged unions) and pattern matching (and
arguably the dynamic typing generally) makes Python a less appropriate
choice for this than a language like Rust, Swift, Haskell or OCaml.
But those languages are a lot less well known, and I wanted to create a simple
exercise for anyone who wants to have a go themselves at creating a lexer, to
tie in with a talk I'm going to be giving on lexing at work.
<file_sep>/lexer/lex.py
import tokens
class Lexer:
"""
C lexer
Attributes:
accum (str): string accumulating the text for the current token
tokens (list): list of tokens lexed so far
"""
def __init__(self):
self.accum = ""
self.tokens = []
def step(self, state, char):
"""
Step the lexer state machine, processing the next character
Args:
state (callable that takes a string): state function to run
char (str): character to interpret
"""
assert len(char) == 1
return state(char)
def done_accumulating(self):
"""Clear the accumulator, returning what it contained"""
token_str = self.accum
self.accum = ""
return token_str
def new_token(self, char):
"""
Entry state: we are starting to lex a new token
Args:
char (str): character to interpret. Its value will decide which
type of token we attempt to lex.
Returns:
next state to run
Raises:
RuntimeError if an unexpected character is received
"""
if char.isspace():
return self.new_token
self.accum += char
if char.isalpha():
return self.accumulate_keyword_or_id
elif char.isdigit():
return self.accumulate_constant
elif char == "'":
return self.accumulate_string
else:
raise RuntimeError("State transition not implemented")
def accumulate_keyword_or_id(self, char):
"""
State for accumulating a keyword or identifier token
Args:
char (str): character to interpret. Its value will decide whether
we continue or finish accumulating our token.
Returns:
next state to run
"""
if char.isalnum():
self.accum += char
return self.accumulate_keyword_or_id
token_str = self.done_accumulating()
if token_str in tokens.keywords:
self.tokens.append(tokens.Keyword(token_str))
else:
self.tokens.append(tokens.Identifier(token_str))
return self.new_token(char)
def accumulate_punctuator(self, char):
"""
State for accumulating a punctuator token
Args:
char (str): character to interpret. Its value will decide whether
we continue or finish accumulating our token.
Returns:
next state to run
"""
raise RuntimeError("Not implemented")
def accumulate_string(self, char):
"""
State for accumulating a string literal token
Args:
char (str): character to interpret. Its value will decide whether
we continue or finish accumulating our token.
Returns:
next state to run
"""
raise RuntimeError("Not implemented")
def accumulate_constant(self, char):
"""
State for accumulating a constant token
Args:
char (str): character to interpret. Its value will decide whether
we continue or finish accumulating our token.
Returns:
next state to run
"""
raise RuntimeError("Not implemented")
<file_sep>/lexer/tokens.py
keywords = [
# Storage class specifiers
"auto", "extern", "register", "static",
# Type qualifiers
"const", "restrict", "volatile",
# Control
"break", "case", "continue", "default", "do", "else", "for",
"goto", "if", "return", "switch", "while",
# Type specifiers
"char", "double", "float", "int", "long",
"short", "signed", "unsigned", "void",
# Struct, union, enumeration
"enum", "struct", "union",
# Function specifiers
"inline",
# others
"sizeof", "typedef",
]
punctuators = [
"[", "]", "(", ")", "{", "}",
".", "->", "++", "--", "&",
"*", "+", "-", "~", "!",
"/", "%", "<<", ">>", "<", ">", "<=", ">=",
"==", "!=", "^", "|", "&&", "||", "?",
":", ";", "...", "=", "*=", "/=", "%=", "+=",
"-=", "<<=", ">>=", "&=", "^=", "|=", ",", "#", "##",
# Digraphs,
"<:", ":>", "<%", "%>", "%:", "%:%:",
# Trigraphs,
"??=", "??/", "??'", "??(", "??)", "??!", "??<", "??>", "??-",
]
complete_punctuator_chars = ["[", "]", "(", ")", "{", "}", ";", ","]
possibly_incomplete_punctuator_chars = [
".", "|", ":", "!", "-", "+",
"=", "*", "/", "!", "?", "<",
">", "#", "&", "|", "^", "%",
]
punctuator_chars = [
*complete_punctuator_chars,
*possibly_incomplete_punctuator_chars
]
class Keyword:
def __init__(self, keyword_string):
if keyword_string not in keywords:
raise RuntimeError(f"{keyword_string} is not a keyword")
self.value = keyword_string
class Identifier:
def __init__(self, token_string):
self.value = token_string
class StringLiteral:
def __init__(self, literal_value):
self.value = literal_value
class Constant:
def __init__(self, constant_value):
self.value = constant_value
class Punctuator:
def __init__(self, punctuator_string):
if punctuator_string not in punctuators:
raise RuntimeError(f"{punctuator_string} is not a punctuator")
self.value = punctuator_string
|
3afb2c4c77035c977c1acf7c71557fadf2def94b
|
[
"Markdown",
"Python"
] | 3
|
Markdown
|
lochsh/c-lexer-exercise
|
bcde7207c6ec31f45685bda824cc58e0bf6d4da2
|
09a3a85f414899dac4b1cb281be661e47972a9b1
|
refs/heads/master
|
<repo_name>wangzhi0417/android-calculatorpp<file_sep>/android-app/src/main/java/org/solovyev/android/calculator/wizard/AppWizardFlow.java
/*
* Copyright 2013 serso aka se.solovyev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Contact details
*
* Email: <EMAIL>
* Site: http://se.solovyev.org
*/
package org.solovyev.android.calculator.wizard;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import static org.solovyev.android.calculator.wizard.WizardStep.last;
import static org.solovyev.android.calculator.wizard.Wizards.DEFAULT_WIZARD_FLOW;
import static org.solovyev.android.calculator.wizard.Wizards.FIRST_TIME_WIZARD;
import static org.solovyev.android.calculator.wizard.WizardStep.welcome;
/**
* User: serso
* Date: 6/16/13
* Time: 9:25 PM
*/
final class AppWizardFlow implements WizardFlow {
@Nonnull
private final ListWizardFlow listWizardFlow;
private AppWizardFlow(@Nonnull String name, @Nonnull List<WizardStep> wizardSteps) {
this.listWizardFlow = new ListWizardFlow(name, wizardSteps);
}
@Nonnull
static AppWizardFlow newDefaultWizardFlow() {
final List<WizardStep> wizardSteps = new ArrayList<WizardStep>();
for (WizardStep wizardStep : WizardStep.values()) {
if (wizardStep != welcome && wizardStep != last && wizardStep.isVisible()) {
wizardSteps.add(wizardStep);
}
}
return new AppWizardFlow(DEFAULT_WIZARD_FLOW, wizardSteps);
}
@Nonnull
static AppWizardFlow newFirstTimeWizardFlow() {
final List<WizardStep> wizardSteps = new ArrayList<WizardStep>();
for (WizardStep wizardStep : WizardStep.values()) {
if (wizardStep.isVisible()) {
wizardSteps.add(wizardStep);
}
}
return new AppWizardFlow(FIRST_TIME_WIZARD, wizardSteps);
}
@Nonnull
@Override
public String getName() {
return listWizardFlow.getName();
}
@Nullable
@Override
public WizardStep getStep(@Nonnull String name) {
return listWizardFlow.getStep(name);
}
@Nullable
@Override
public WizardStep getNextStep(@Nonnull WizardStep step) {
return listWizardFlow.getNextStep(step);
}
@Nullable
@Override
public WizardStep getPrevStep(@Nonnull WizardStep step) {
return listWizardFlow.getPrevStep(step);
}
@Nonnull
@Override
public WizardStep getFirstStep() {
return listWizardFlow.getFirstStep();
}
}
<file_sep>/core/src/main/resources/org/solovyev/android/calculator/messages.properties
msg_1=Arithmetic error occurred: {0}
msg_2=Expression is too complex
msg_3=Execution time is too long - check the expression
msg_4=Evaluation was cancelled
msg_5=No parameters are specified for function: {0}
msg_6=Infinite loop is detected in expression
msg_7=Some user data could not be loaded. Please contact developers.\n\nUnable to load:\n{0}
syntax_error=Error
result_copied=Result has been copied to the clipboard!
text_copied=Text has been copied to the clipboard!
ans_description=Last calculated value
|
21ca6532ab74d3e65e736d08a02323a3a4b69c07
|
[
"Java",
"INI"
] | 2
|
Java
|
wangzhi0417/android-calculatorpp
|
1abaed2bab9ee6fdcf03d029159139caad00ba65
|
061579734a79b40f59b34a0cca131f5565e0ece6
|
refs/heads/master
|
<file_sep>#!~/anaconda2/bin python
# -*- coding: UTF-8 -*-
# File: resnet-msc-coco.py
# Author: <NAME> (<EMAIL>)
import argparse
import os
import sys
import os
from tensorpack import logger, QueueInput
from tensorpack.models import *
from tensorpack.callbacks import *
from tensorpack.train import (TrainConfig, SyncMultiGPUTrainerParameterServer, launch_train_with_config)
from tensorpack.dataflow import FakeData
from tensorpack.tfutils import argscope, get_model_loader
from tensorpack.utils.gpu import get_nr_gpu
from coco_utils import (
fbresnet_augmentor, get_voc_dataflow, MSC_Model,
eval_on_ILSVRC12)
from resnet_model_voc_aspp import (
preresnet_group, preresnet_basicblock, preresnet_bottleneck,
resnet_group, resnet_group_dilation,resnet_basicblock, resnet_bottleneck, resnet_bottleneck_dilation, se_resnet_bottleneck,
resnet_backbone)
# Fintune
# TOTAL_BATCH_SIZE = 32
#Joint Train
TOTAL_BATCH_SIZE = 8
class Model(MSC_Model):
def __init__(self, depth, data_format='NCHW', mode='resnet'):
super(Model, self).__init__(data_format)
if mode == 'se':
assert depth >= 50
self.mode = mode
basicblock = preresnet_basicblock if mode == 'preact' else resnet_basicblock
bottleneck = {
'resnet': resnet_bottleneck,
'preact': preresnet_bottleneck,
'se': se_resnet_bottleneck}[mode]
self.num_blocks, self.block_func = {
18: ([2, 2, 2, 2], basicblock),
34: ([3, 4, 6, 3], basicblock),
50: ([3, 4, 6, 3], bottleneck),
101: ([3, 4, 23, 3], bottleneck),
152: ([3, 8, 36, 3], bottleneck)
}[depth]
def get_logits(self, image):
with argscope([Conv2D, MaxPooling, GlobalAvgPooling, BatchNorm], data_format=self.data_format):
with argscope([BatchNorm], use_local_stat=False):
return resnet_backbone(
image, self.num_blocks,
preresnet_group if self.mode == 'preact' else resnet_group, resnet_group_dilation,
self.block_func, resnet_bottleneck_dilation)#Fintune or Joint Train
def get_data(name, batch):
isTrain = name == 'train'
augmentors = fbresnet_augmentor(isTrain)
return get_voc_dataflow(
args.data, name, batch, augmentors, isDownSample=False, isSqueeze=False, isExpandDim=True)
def get_config(model, fake=False):
nr_tower = max(get_nr_gpu(), 1)
batch = TOTAL_BATCH_SIZE // nr_tower
if fake:
logger.info("For benchmark, batch size is fixed to 64 per tower.")
dataset_train = FakeData(
[[64, 224, 224, 3], [64]], 1000, random=False, dtype='uint8')
callbacks = []
else:
logger.info("Running on {} towers. Batch size per tower: {}".format(nr_tower, batch))
dataset_train = get_data('train', batch)
dataset_val = get_data('val', batch)
callbacks = [
ModelSaver(),
ScheduledHyperParamSetter('learning_rate', [(0, 1.25e-4), (20, 5e-5), (40, 2.5e-5), (60,1.25e-5),(80, 5e-6), (100, 2.5e-6), (120, 1.25e-6)]),
HumanHyperParamSetter('learning_rate'),
]
#Train Val
#[(0, 1.25e-4), (20, 5e-5), (40, 2.5e-5), (60,1.25e-5),(80, 5e-6), (100, 2.5e-6), (120, 1.25e-6)]
#FT VOC
#[(0, 2.5e-4), (20, 1.25e-4), (40, 5e-5), (60, 2.5e-5),(80, 1e-5), (100, 5e-6), (120, 2.5e-6)]
#JT VOC
#[(0, 1.25e-4), (20, 5e-5), (40, 2.5e-5), (60,1.25e-5),(80, 5e-6), (100, 2.5e-6), (120, 1.25e-6)]
#infs = [ClassificationError('wrong-top1', 'val-error-top1'),
# ClassificationError('wrong-top5', 'val-error-top5')]
infs = [ClassificationError('loss-wrong-top1', 'loss-val-error-top1'),
ClassificationError('loss-wrong-top5', 'loss-val-error-top5')]
if nr_tower == 1:
# single-GPU inference with queue prefetch
callbacks.append(InferenceRunner(QueueInput(dataset_val), infs))
else:
# multi-GPU inference (with mandatory queue prefetch)
callbacks.append(DataParallelInferenceRunner(
dataset_val, infs, list(range(nr_tower))))
return TrainConfig(
model=model,
dataflow=dataset_train,
callbacks=callbacks,
steps_per_epoch=181,
max_epoch=140,
nr_tower=nr_tower
)
#Joint Train
#steps_per_epoch=3043,
#max_epoch=50,
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--gpu', help='comma separated list of GPU(s) to use.')
parser.add_argument('--data', help='ILSVRC dataset dir')
parser.add_argument('--load', help='load model')
parser.add_argument('--fake', help='use fakedata to test or benchmark this model', action='store_true')
parser.add_argument('--data_format', help='specify NCHW or NHWC',
type=str, default='NCHW')
parser.add_argument('-d', '--depth', help='resnet depth',
type=int, default=18, choices=[18, 34, 50, 101, 152])
parser.add_argument('--eval', action='store_true')
parser.add_argument('--mode', choices=['resnet', 'preact', 'se'],
help='variants of resnet to use', default='resnet')
parser.add_argument('--log_dir', help='save model dir')
args = parser.parse_args()
if args.gpu:
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
model = Model(args.depth, args.data_format, args.mode)
if args.eval:
batch = 16 # something that can run on one gpu
ds = get_data('val', batch)
eval_on_ILSVRC12(model, get_model_loader(args.load), ds)
else:
logger.set_logger_dir(
os.path.join('train_log', 'imagenet-resnet-d' + str(args.depth)+ "-" + args.log_dir))
#set your save path
config = get_config(model, fake=args.fake)
if args.load:
config.session_init = get_model_loader(args.load)
trainer = SyncMultiGPUTrainerParameterServer(max(get_nr_gpu(), 1))
launch_train_with_config(config, trainer)
<file_sep>#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# File: gr_conv2d.py
# Author: <NAME> <<EMAIL>>
import tensorflow as tf
from tensorpack.models.common import layer_register, VariableHolder
from tensorpack.models.tflayer import rename_get_variable
from tensorpack.utils.argtools import shape2d, shape4d
__all__ = ['GrConv2D']
@layer_register(log_shape=True)
def GrConv2D(x, out_channel, kernel_shape,
padding='SAME', stride=1, dilation_rate=1,
W_init=None, b_init=None,
nl=tf.identity, split=1, use_bias=True,
data_format='channels_last'):
if data_format == 'NHWC' or data_format == 'channels_last':
data_format = 'channels_last'
elif data_format == 'NCHW' or data_format == 'channels_first':
data_format = 'channels_first'
else:
print "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa unknown data format"
in_shape = x.get_shape().as_list()
channel_axis = 3 if data_format == 'NHWC' else 1
in_channel = in_shape[channel_axis]
assert in_channel is not None, "[GrConv2D] Input cannot have unknown channel!"
assert in_channel % split == 0
assert out_channel % split == 0
kernel_shape = shape2d(kernel_shape)
padding = padding.upper()
filter_shape = kernel_shape + [in_channel / split, out_channel]
stride = shape2d(stride)
if W_init is None:
W_init = tf.contrib.layers.variance_scaling_initializer()
if b_init is None:
b_init = tf.constant_initializer()
with rename_get_variable({'kernel': 'W', 'bias': 'b'}):
layer = tf.layers.Conv2D(filters=out_channel, kernel_size=kernel_shape, strides=stride,
padding=padding, data_format=data_format,
dilation_rate=dilation_rate, activation=lambda x: nl(x, name='output'), use_bias=use_bias,
kernel_initializer=W_init, bias_initializer=b_init, trainable=True)
ret = layer.apply(x, scope=tf.get_variable_scope())
ret.variables = VariableHolder(W=layer.kernel)
if use_bias:
ret.variables.b = layer.bias
return ret
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: imagenet_utils.py
# Author: <NAME> (<EMAIL>)
# Author: <NAME> (<EMAIL>)
# Code is developed based on Yuxin Wu's ResNet implementation: https://github.com/ppwwyyxx/tensorpack/tree/master/examples/ResNet
import cv2
import numpy as np
import multiprocessing
import tensorflow as tf
from abc import abstractmethod
from tensorpack import imgaug, dataset, ModelDesc, InputDesc
from tensorpack.dataflow import (
MapData, AugmentImageComponent, PrefetchDataZMQ,
BatchData, MultiThreadMapData)
from tensorpack.predict import PredictConfig, SimpleDatasetPredictor
from tensorpack.utils.stats import RatioCounter
from tensorpack.models import regularize_cost
from tensorpack.tfutils.summary import add_moving_summary
from keras.losses import binary_crossentropy
import keras.backend as K
CROPSHAPE = 448
n_class = 21
def dice_loss(label, logits):
label = tf.cast(label, tf.float32)
logits = tf.nn.softmax(logits)
smooth = 1.
cc = logits.get_shape().as_list()[1]
b_ = tf.shape(label)[0]
grzeros = tf.zeros([b_,])
grones = tf.ones([b_,])
grloss = 0
for c in range(1, cc):
targetlabel = tf.where(tf.equal(label, c), grones, grzeros)
targetlogits = logits[:,c]
intersection = tf.reduce_sum(targetlogits * targetlabel, axis=0)
grloss = grloss + (2. * intersection + smooth) / (tf.reduce_sum(targetlabel) + tf.reduce_sum(targetlogits) + smooth)
return grloss
class GoogleNetResize(imgaug.ImageAugmentor):
"""
crop 8%~100% of the original image
See `Going Deeper with Convolutions` by Google.
"""
def __init__(self, crop_area_fraction=0.08,
aspect_ratio_low=0.75, aspect_ratio_high=1.333,
target_shape=224):
self._init(locals())
def _augment(self, img, _):
h, w = img.shape[:2]
area = h * w
for _ in range(10):
targetArea = self.rng.uniform(self.crop_area_fraction, 1.0) * area
aspectR = self.rng.uniform(self.aspect_ratio_low, self.aspect_ratio_high)
ww = int(np.sqrt(targetArea * aspectR) + 0.5)
hh = int(np.sqrt(targetArea / aspectR) + 0.5)
if self.rng.uniform() < 0.5:
ww, hh = hh, ww
if hh <= h and ww <= w:
x1 = 0 if w == ww else self.rng.randint(0, w - ww)
y1 = 0 if h == hh else self.rng.randint(0, h - hh)
out = img[y1:y1 + hh, x1:x1 + ww]
out = cv2.resize(out, (self.target_shape, self.target_shape), interpolation=cv2.INTER_CUBIC)
return out
out = imgaug.ResizeShortestEdge(self.target_shape, interp=cv2.INTER_CUBIC).augment(img)
out = imgaug.CenterCrop(self.target_shape).augment(out)
return out
def fbresnet_augmentor(isTrain):
"""
Augmentor used in fb.resnet.torch, for BGR images in range [0,255].
"""
if isTrain:
augmentors = [
GoogleNetResize(),
imgaug.RandomOrderAug(
[imgaug.BrightnessScale((0.6, 1.4), clip=False),
imgaug.Contrast((0.6, 1.4), clip=False),
imgaug.Saturation(0.4, rgb=False),
# rgb-bgr conversion for the constants copied from fb.resnet.torch
imgaug.Lighting(0.1,
eigval=np.asarray(
[0.2175, 0.0188, 0.0045][::-1]) * 255.0,
eigvec=np.array(
[[-0.5675, 0.7192, 0.4009],
[-0.5808, -0.0045, -0.8140],
[-0.5836, -0.6948, 0.4203]],
dtype='float32')[::-1, ::-1]
)]),
imgaug.Flip(horiz=True),
]
else:
augmentors = [
imgaug.ResizeShortestEdge(256, cv2.INTER_CUBIC),
imgaug.CenterCrop((224, 224)),
]
return augmentors
def randomHueSaturationValue(image, hue_shift_limit=(-180, 180),
sat_shift_limit=(-255, 255),
val_shift_limit=(-255, 255), u=0.5):
if np.random.random() < u:
image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(image)
hue_shift = np.random.uniform(hue_shift_limit[0], hue_shift_limit[1])
h = cv2.add(h, hue_shift)
sat_shift = np.random.uniform(sat_shift_limit[0], sat_shift_limit[1])
s = cv2.add(s, sat_shift)
val_shift = np.random.uniform(val_shift_limit[0], val_shift_limit[1])
v = cv2.add(v, val_shift)
image = cv2.merge((h, s, v))
image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)
return image
def randomShiftScaleRotate(image, mask,
shift_limit=(-0.0625, 0.0625),
scale_limit=(-0.1, 0.1),
rotate_limit=(-45, 45), aspect_limit=(0, 0),
borderMode=cv2.BORDER_CONSTANT, u=0.5):
if np.random.random() < u:
height, width, channel = image.shape
angle = np.random.uniform(rotate_limit[0], rotate_limit[1]) # degree
scale = np.random.uniform(1 + scale_limit[0], 1 + scale_limit[1])
aspect = np.random.uniform(1 + aspect_limit[0], 1 + aspect_limit[1])
sx = scale * aspect / (aspect ** 0.5)
sy = scale / (aspect ** 0.5)
dx = round(np.random.uniform(shift_limit[0], shift_limit[1]) * width)
dy = round(np.random.uniform(shift_limit[0], shift_limit[1]) * height)
cc = np.math.cos(angle / 180 * np.math.pi) * sx
ss = np.math.sin(angle / 180 * np.math.pi) * sy
rotate_matrix = np.array([[cc, -ss], [ss, cc]])
box0 = np.array([[0, 0], [width, 0], [width, height], [0, height], ])
box1 = box0 - np.array([width / 2, height / 2])
box1 = np.dot(box1, rotate_matrix.T) + np.array([width / 2 + dx, height / 2 + dy])
box0 = box0.astype(np.float32)
box1 = box1.astype(np.float32)
mat = cv2.getPerspectiveTransform(box0, box1)
image = cv2.warpPerspective(image, mat, (width, height), flags=cv2.INTER_LINEAR, borderMode=borderMode,
borderValue=(0, 0,0,))
mask = cv2.warpPerspective(mask, mat, (width, height), flags=cv2.INTER_LINEAR, borderMode=borderMode,
borderValue=(0, 0,0,))
return image, mask
def randomScale(img, label):
scale = np.random.uniform(0.9, 1.1)
h_old = img.shape[0]
w_old = img.shape[1]
h_new = int(float(h_old) * scale)
w_new = int(float(w_old) * scale)
img = cv2.resize(img, (w_new, h_new))
label = cv2.resize(label, (w_new, h_new), interpolation=cv2.INTER_NEAREST)
return img, label
def randomHorizontalFlip(image, mask, u=0.5):
if np.random.random() < u:
image = cv2.flip(image, 1)
mask = cv2.flip(mask, 1)
return image, mask
def randomCropPad(image, label, crop_h, crop_w, ignore_label=255, isTrain=True, isSqueeze=True):
label = np.asarray(label, dtype='float32')
label = np.expand_dims(label, -1)
label = label - float(ignore_label)
combined = np.concatenate((image, label),axis=2)
image_h = image.shape[0]
image_w = image.shape[1]
pad_h = max(0, crop_h - image_h)
pad_w = max(0, crop_w - image_w)
combined_pad = np.lib.pad(combined, ((0,pad_h), (0,pad_w), (0,0)), 'constant',
constant_values=((128,128), (128,128), (128, 128)))
comb_h = combined_pad.shape[0]
comb_w = combined_pad.shape[1]
if isTrain:
crop_scale = np.random.uniform(0.0, 1.0)
else:
crop_scale = 0.5
crop_shift_h = int(crop_scale * float((comb_h - crop_h))/2)
crop_shift_w = int(crop_scale * float((comb_w - crop_w))/2)
combined_crop = combined_pad[crop_shift_h:crop_shift_h+crop_h, crop_shift_w:crop_shift_w+crop_w, :]
img_crop = combined_crop[:, :, :3]
label_crop = combined_crop[:, :, 3:]
label_crop = label_crop + ignore_label
label_crop = np.asarray(label_crop, dtype='uint8')
# Set static shape so that tensorflow knows shape at compile time.
# img_crop.set_shape((crop_h, crop_w, 3))
# label_crop.set_shape((crop_h,crop_w, 1))
if isSqueeze:
label_crop = np.squeeze(label_crop, -1)
return img_crop, label_crop
def get_voc_dataflow(
datadir, name, batch_size,
augmentors, isDownSample=True, isSqueeze=True, isExpandDim=False):
"""
See explanations in the tutorial:
http://tensorpack.readthedocs.io/en/latest/tutorial/efficient-dataflow.html
"""
gr_shape = CROPSHAPE
assert name in ['train', 'val', 'test']
assert datadir is not None
assert isinstance(augmentors, list)
isTrain = name == 'train'
cpu = min(30, multiprocessing.cpu_count())
if isTrain:
ds = dataset.VOC12(datadir, name, shuffle=True)
# ds = AugmentImageComponent(ds, augmentors, copy=False)
aug = imgaug.AugmentorList(augmentors)
def preprocess(imandlabel):
im, label = imandlabel
assert im is not None, 'aaaaaa'
assert label is not None, 'bbbbbbb'
im = im.astype('float32')
label = label.astype('uint8')
im = randomHueSaturationValue(im, hue_shift_limit=(-50, 50), sat_shift_limit=(-50, 50), val_shift_limit=(-50, 50))
im, label = randomScale(im, label)
im, label = randomHorizontalFlip(im, label)
im, label = randomCropPad(im, label, gr_shape, gr_shape, ignore_label=255, isTrain=isTrain, isSqueeze=isSqueeze)
ret = [im]
if isDownSample:
label = cv2.resize(label, (gr_shape/8, gr_shape/8), interpolation=cv2.INTER_NEAREST)
label = np.asarray(label, dtype='uint8')
ret.append(label)
return ret
ds = MapData(ds, preprocess)
ds = PrefetchDataZMQ(ds, cpu)
ds = BatchData(ds, batch_size, remainder=False)
else:
ds = dataset.VOC12Files(datadir, name, shuffle=False)
aug = imgaug.AugmentorList(augmentors)
def mapf(dp):
dataname, labelname = dp
im = cv2.imread(dataname, cv2.IMREAD_COLOR)
label = cv2.imread(labelname, cv2.IMREAD_GRAYSCALE)
im = cv2.resize(im, (gr_shape, gr_shape))
label = cv2.resize(label, (gr_shape, gr_shape), interpolation=cv2.INTER_NEAREST)
if isExpandDim:
label = np.expand_dims(label, -1)
if isDownSample:
label = cv2.resize(label, (gr_shape/8, gr_shape/8), interpolation=cv2.INTER_NEAREST)
label = np.asarray(label, dtype='uint8')
return im, label
#ds = MultiThreadMapData(ds, cpu, mapf, buffer_size=1000, strict=True)
ds = MultiThreadMapData(ds, cpu, mapf, buffer_size=100, strict=True)
ds = BatchData(ds, batch_size, remainder=True)
ds = PrefetchDataZMQ(ds, 1)
return ds
def get_imagenet_dataflow(
datadir, name, batch_size,
augmentors):
"""
See explanations in the tutorial:
http://tensorpack.readthedocs.io/en/latest/tutorial/efficient-dataflow.html
"""
assert name in ['train', 'val', 'test']
assert datadir is not None
assert isinstance(augmentors, list)
isTrain = name == 'train'
cpu = min(30, multiprocessing.cpu_count())
if isTrain:
ds = dataset.ILSVRC12(datadir, name, shuffle=True)
ds = AugmentImageComponent(ds, augmentors, copy=False)
ds = PrefetchDataZMQ(ds, cpu)
ds = BatchData(ds, batch_size, remainder=False)
else:
ds = dataset.ILSVRC12Files(datadir, name, shuffle=False)
aug = imgaug.AugmentorList(augmentors)
def mapf(dp):
fname, cls = dp
im = cv2.imread(fname, cv2.IMREAD_COLOR)
im = aug.augment(im)
return im, cls
ds = MultiThreadMapData(ds, cpu, mapf, buffer_size=2000, strict=True)
ds = BatchData(ds, batch_size, remainder=True)
ds = PrefetchDataZMQ(ds, 1)
return ds
def eval_on_ILSVRC12(model, sessinit, dataflow):
pred_config = PredictConfig(
model=model,
session_init=sessinit,
input_names=['input', 'label'],
output_names=['wrong-top1', 'wrong-top5']
)
pred = SimpleDatasetPredictor(pred_config, dataflow)
acc1, acc5 = RatioCounter(), RatioCounter()
for top1, top5 in pred.get_result():
batch_size = top1.shape[0]
acc1.feed(top1.sum(), batch_size)
acc5.feed(top5.sum(), batch_size)
print("Top1 Error: {}".format(acc1.ratio))
print("Top5 Error: {}".format(acc5.ratio))
class ImageNetModel(ModelDesc):
weight_decay = 1e-4
image_shape = CROPSHAPE
"""
uint8 instead of float32 is used as input type to reduce copy overhead.
It might hurt the performance a liiiitle bit.
The pretrained models were trained with float32.
"""
image_dtype = tf.uint8
def __init__(self, data_format='NCHW', hardmine=False):
self.data_format = data_format
self.hardmine = hardmine
def _get_inputs(self):
return [InputDesc(self.image_dtype, [None, self.image_shape, self.image_shape, 3], 'input'),
InputDesc(tf.int32, [None, self.image_shape /8, self.image_shape/8], 'label')]
def _build_graph(self, inputs):
image, label = inputs
image = self.image_preprocess(image, bgr=True)
if self.data_format == 'NCHW':
image = tf.transpose(image, [0, 3, 1, 2])
logits = self.get_logits(image)
print(type(logits), type(label), logits.get_shape().as_list(), label.get_shape().as_list())
label = tf.reshape(label, [-1])
logits = tf.reshape(logits, [-1, logits.get_shape().as_list()[3]])
#######
if self.hardmine:
print('--------------------hardmine-----------------------')
def process_hardmine_class(logits, label, class_number):
indices = tf.squeeze(tf.where(tf.equal(label, 2)), 1)
label = tf.cast(tf.gather(label, indices), tf.int32)
logits = tf.gather(logits, indices)
return logits, label
logits_bike, label_bike = process_hardmine_class(logits, label, 2)
logits_boat, label_boat = process_hardmine_class(logits, label, 4)
logits_hard = tf.concat(values=[logits_bike, logits_boat] * 1, axis = 0)
label_hard = tf.concat(values=[label_bike, label_boat] * 1, axis = 0)
indices = tf.squeeze(tf.where(tf.less_equal(label, n_class-1)), 1)
label = tf.cast(tf.gather(label, indices), tf.int32)
logits = tf.gather(logits, indices)
label = tf.concat(values = [label, label_hard], axis = 0)
logits = tf.concat(values = [logits, logits_hard], axis = 0)
print('--------------------hardmine-----------------------')
else:
indices = tf.squeeze(tf.where(tf.less_equal(label, n_class-1)), 1)
label = tf.cast(tf.gather(label, indices), tf.int32)
logits = tf.gather(logits, indices)
loss = ImageNetModel.compute_loss_and_error(logits, label)
if self.weight_decay > 0:
wd_loss = regularize_cost('.*/W', tf.contrib.layers.l2_regularizer(self.weight_decay),
name='l2_regularize_loss')
add_moving_summary(loss, wd_loss)
self.cost = tf.add_n([loss, wd_loss], name='cost')
else:
self.cost = tf.identity(loss, name='cost')
add_moving_summary(self.cost)
@abstractmethod
def get_logits(self, image):
"""
Args:
image: 4D tensor of 224x224 in ``self.data_format``
Returns:
Nx1000 logits
"""
def _get_optimizer(self):
lr = tf.get_variable('learning_rate', initializer=0.1, trainable=False)
tf.summary.scalar('learning_rate', lr)
return tf.train.MomentumOptimizer(lr, 0.9, use_nesterov=True)
def image_preprocess(self, image, bgr=True):
with tf.name_scope('image_preprocess'):
if image.dtype.base_dtype != tf.float32:
image = tf.cast(image, tf.float32)
image = image * (1.0 / 255)
mean = [0.485, 0.456, 0.406] # rgb
std = [0.229, 0.224, 0.225]
if bgr:
mean = mean[::-1]
std = std[::-1]
image_mean = tf.constant(mean, dtype=tf.float32)
image_std = tf.constant(std, dtype=tf.float32)
image = (image - image_mean) / image_std
return image
@staticmethod
def compute_loss_and_error(logits, label):
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=label)
loss = tf.reduce_mean(loss, name='xentropy-loss')
# loss = loss + (1 - dice_loss(label, logits))
def prediction_incorrect(logits, label, topk=1, name='incorrect_vector'):
with tf.name_scope('prediction_incorrect'):
x = tf.logical_not(tf.nn.in_top_k(logits, label, topk))
return tf.cast(x, tf.float32, name=name)
wrong = prediction_incorrect(logits, label, 1, name='wrong-top1')
add_moving_summary(tf.reduce_mean(wrong, name='train-error-top1'))
wrong = prediction_incorrect(logits, label, 5, name='wrong-top5')
add_moving_summary(tf.reduce_mean(wrong, name='train-error-top5'))
return loss
class MSC_Model(ModelDesc):
weight_decay = 1e-4
image_shape = CROPSHAPE
"""
uint8 instead of float32 is used as input type to reduce copy overhead.
It might hurt the performance a liiiitle bit.
The pretrained models were trained with float32.
"""
image_dtype = tf.uint8
def __init__(self, data_format='NCHW', hardmine=False):
self.data_format = data_format
self.hardmine = hardmine
def _get_inputs(self):
return [InputDesc(self.image_dtype, [None, self.image_shape, self.image_shape, 3], 'input'),
InputDesc(tf.int32, [None, self.image_shape, self.image_shape, 1], 'label')]
def _build_graph(self, inputs):
image, label = inputs
image = self.image_preprocess(image, bgr=True)
image075 = tf.image.resize_images(image, [int(image.get_shape().as_list()[1]*0.75), int(image.get_shape().as_list()[2]*0.75)])
image05 = tf.image.resize_images(image, [int(image.get_shape().as_list()[1]*0.5), int(image.get_shape().as_list()[2]*0.5)])
if self.data_format == 'NCHW':
image = tf.transpose(image, [0, 3, 1, 2])
logits100 = self.get_logits(image)
with tf.variable_scope('', reuse=True):
logits075 = self.get_logits(image075)
with tf.variable_scope('', reuse=True):
logits05 = self.get_logits(image05)
logits = tf.reduce_max(tf.stack([logits100, tf.image.resize_images(logits075, tf.shape(logits100)[1:3, ]), tf.image.resize_images(logits05, tf.shape(logits100)[1:3, ])]), axis=0)
#logits = self.get_logits(image)
def process_label(logits, label):
label = tf.image.resize_nearest_neighbor(label, logits.get_shape()[1:3])
print(type(logits), type(label), logits.get_shape().as_list(), label.get_shape().as_list())
label = tf.squeeze(label, -1)
label = tf.reshape(label, [-1])
return label
label075 = process_label(logits075, label)
label05 = process_label(logits05, label)
label = process_label(logits, label)
logits = tf.reshape(logits, [-1, logits.get_shape().as_list()[3]])
logits100 = tf.reshape(logits100, [-1, logits100.get_shape().as_list()[3]])
logits075 = tf.reshape(logits075, [-1, logits075.get_shape().as_list()[3]])
logits05 = tf.reshape(logits05, [-1, logits05.get_shape().as_list()[3]])
#######
self.hardmine = False
if self.hardmine:
print('--------------------hardmine-----------------------')
def process_hardmine_class(logits, label, class_number):
indices = tf.squeeze(tf.where(tf.equal(label, 2)), 1)
label = tf.cast(tf.gather(label, indices), tf.int32)
logits = tf.gather(logits, indices)
return logits, label
# logits_bike, label_bike = process_hardmine_class(logits, label, 2)
# logits100_bike, _ = process_hardmine_class(logits100, label, 2)
# logits075_bike, label075_bike = process_hardmine_class(logits075, label075, 2)
# logits05_bike, label05_bike = process_hardmine_class(logits05, label05, 2)
# logits_boat, label_boat = process_hardmine_class(logits, label, 4)
# logits100_boat, _ = process_hardmine_class(logits100, label, 4)
# logits075_boat, label075_boat = process_hardmine_class(logits075, label075, 4)
# logits05_boat, label05_boat = process_hardmine_class(logits05, label05, 4)
'''
indices_bike = tf.squeeze(tf.where(tf.equal(raw_label, 2)), 1)
label_bike = tf.cast(tf.gather(raw_label, indices_bike), tf.int32)
logits_bike = tf.gather(raw_logits, indices_bike)
indices_boat = tf.squeeze(tf.where(tf.equal(raw_label, 4)), 1)
label_boat = tf.cast(tf.gather(raw_label, indices_boat), tf.int32)
logits_boat = tf.gather(raw_logits, indices_boat)
indices_chair = tf.squeeze(tf.where(tf.equal(raw_label, 9)), 1)
label_chair = tf.cast(tf.gather(raw_label, indices_chair), tf.int32)
logits_chair = tf.gather(raw_logits, indices_chair)
indices_table = tf.squeeze(tf.where(tf.equal(raw_label, 11)), 1)
label_table = tf.cast(tf.gather(raw_label, indices_table), tf.int32)
logits_table = tf.gather(raw_logits, indices_table)
indices_plant = tf.squeeze(tf.where(tf.equal(raw_label, 16)), 1)
label_plant = tf.cast(tf.gather(raw_label, indices_plant), tf.int32)
logits_plant = tf.gather(raw_logits, indices_plant)
indices_sofa = tf.squeeze(tf.where(tf.equal(raw_label, 18)), 1)
label_sofa = tf.cast(tf.gather(raw_label, indices_sofa), tf.int32)
logits_sofa = tf.gather(raw_logits, indices_sofa)
logits_hard = tf.concat(values=[logits_bike, logits_bike, logits_boat, logits_chair, logits_chair,
logits_table, logits_table, logits_plant, logits_sofa, logits_sofa] * 1, axis = 0)
label_hard = tf.concat(values=[label_bike, label_bike, label_boat, label_chair, label_chair,
label_table, label_table, label_plant, label_sofa, label_sofa] * 1, axis = 0)
'''
logits_hard = tf.concat(values=[logits_bike, logits_boat] * 1, axis = 0)
logits100_hard = tf.concat(values=[logits100_bike, logits100_boat] * 1, axis = 0)
logits075_hard = tf.concat(values=[logits075_bike, logits075_boat] * 1, axis = 0)
logits05_hard = tf.concat(values=[logits05_bike, logits05_boat] * 1, axis = 0)
label_hard = tf.concat(values=[label_bike, label_boat] * 1, axis = 0)
label075_hard = tf.concat(values=[label075_bike, label075_boat] * 1, axis = 0)
label05_hard = tf.concat(values=[label05_bike, label05_boat] * 1, axis = 0)
indices = tf.squeeze(tf.where(tf.less_equal(label, n_class-1)), 1)
indices075 = tf.squeeze(tf.where(tf.less_equal(label075, n_class-1)), 1)
indices05 = tf.squeeze(tf.where(tf.less_equal(label05, n_class-1)), 1)
label = tf.cast(tf.gather(label, indices), tf.int32)
label075 = tf.cast(tf.gather(label075, indices075), tf.int32)
label05 = tf.cast(tf.gather(label05, indices05), tf.int32)
logits = tf.gather(logits, indices)
logits100 = tf.gather(logits100, indices)
logits075 = tf.gather(logits075, indices075)
logits05 = tf.gather(logits05, indices05)
label = tf.concat(values = [label, label_hard], axis = 0)
label075 = tf.concat(values = [label075, label075_hard], axis = 0)
label05 = tf.concat(values = [label05, label05_hard], axis = 0)
logits = tf.concat(values = [logits, logits_hard], axis = 0)
logits100 = tf.concat(values = [logits100, logits100_hard], axis = 0)
logits075 = tf.concat(values = [logits075, logits075_hard], axis = 0)
logits05 = tf.concat(values = [logits05, logits05_hard], axis = 0)
print('--------------------hardmine-----------------------')
else:
indices = tf.squeeze(tf.where(tf.less_equal(label, n_class-1)), 1)
indices075 = tf.squeeze(tf.where(tf.less_equal(label075, n_class-1)), 1)
indices05 = tf.squeeze(tf.where(tf.less_equal(label05, n_class-1)), 1)
label = tf.cast(tf.gather(label, indices), tf.int32)
label075 = tf.cast(tf.gather(label075, indices075), tf.int32)
label05 = tf.cast(tf.gather(label05, indices05), tf.int32)
logits = tf.gather(logits, indices)
logits100 = tf.gather(logits100, indices)
logits075 = tf.gather(logits075, indices075)
logits05 = tf.gather(logits05, indices05)
loss = MSC_Model.compute_loss_and_error(logits, label, prefix='loss-')
loss100 = MSC_Model.compute_loss_and_error(logits100, label, prefix='loss100-')
loss075 = MSC_Model.compute_loss_and_error(logits075, label075, prefix='loss075-')
loss05 = MSC_Model.compute_loss_and_error(logits05, label05, prefix='loss05-')
if self.weight_decay > 0:
wd_loss = regularize_cost('.*/W', tf.contrib.layers.l2_regularizer(self.weight_decay),
name='l2_regularize_loss')
add_moving_summary(loss,loss100,loss075,loss05, wd_loss)
self.cost = tf.add_n([loss, loss100, loss075, loss05, wd_loss], name='cost')
else:
add_moving_summary(loss,loss100,loss075,loss05)
self.cost = tf.add_n([loss, loss100, loss075, loss05], name='cost')
@abstractmethod
def get_logits(self, image):
"""
Args:
image: 4D tensor of 224x224 in ``self.data_format``
Returns:
Nx1000 logits
"""
def _get_optimizer(self):
lr = tf.get_variable('learning_rate', initializer=0.1, trainable=False)
tf.summary.scalar('learning_rate', lr)
return tf.train.MomentumOptimizer(lr, 0.9, use_nesterov=True)
def image_preprocess(self, image, bgr=True):
with tf.name_scope('image_preprocess'):
if image.dtype.base_dtype != tf.float32:
image = tf.cast(image, tf.float32)
image = image * (1.0 / 255)
mean = [0.485, 0.456, 0.406] # rgb
std = [0.229, 0.224, 0.225]
if bgr:
mean = mean[::-1]
std = std[::-1]
image_mean = tf.constant(mean, dtype=tf.float32)
image_std = tf.constant(std, dtype=tf.float32)
image = (image - image_mean) / image_std
return image
@staticmethod
def compute_loss_and_error(logits, label, prefix=''):
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=label)
loss = tf.reduce_mean(loss, name=prefix+'xentropy-loss')
# loss = loss + (1 - dice_loss(label, logits))
def prediction_incorrect(logits, label, topk=1, name='incorrect_vector'):
with tf.name_scope('prediction_incorrect'):
x = tf.logical_not(tf.nn.in_top_k(logits, label, topk))
return tf.cast(x, tf.float32, name=name)
wrong = prediction_incorrect(logits, label, 1, name=prefix+'wrong-top1')
add_moving_summary(tf.reduce_mean(wrong, name=prefix+'train-error-top1'))
wrong = prediction_incorrect(logits, label, 5, name=prefix+'wrong-top5')
add_moving_summary(tf.reduce_mean(wrong, name=prefix+'train-error-top5'))
return loss
<file_sep>#### <NAME> <<EMAIL>>
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import tensorflow as tf
from tensorpack.tfutils import argscope
from tensorpack.models import (Conv2D, MaxPooling, GlobalAvgPooling, Dropout, BatchNorm)
from tensorpack.tfutils.tower import TowerContext
from coco_utils import (
fbresnet_augmentor, get_voc_dataflow, MSC_Model,
eval_on_ILSVRC12)
from resnet_model_voc_aspp import (
preresnet_group, preresnet_basicblock, preresnet_bottleneck,
resnet_group, resnet_group_dilation,resnet_basicblock, resnet_bottleneck, resnet_bottleneck_dilation, se_resnet_bottleneck,
resnet_backbone)
def load_variables_from_checkpoint(sess, start_checkpoint):
"""Utility function to centralize checkpoint restoration.
Args:
sess: TensorFlow session.
start_checkpoint: Path to saved checkpoint on disk.
"""
saver = tf.train.Saver(tf.global_variables())
saver.restore(sess, start_checkpoint)
def create_resnet_model(image, is_training, isMSC=False, isASPP=False):
mode = 'resnet'
bottleneck = {
'resnet': resnet_bottleneck,
'preact': preresnet_bottleneck,
'se': se_resnet_bottleneck}[mode]
basicblock = preresnet_basicblock if mode == 'preact' else resnet_basicblock
num_blocks, block_func = {
18: ([2, 2, 2, 2], basicblock),
34: ([3, 4, 6, 3], basicblock),
50: ([3, 4, 6, 3], bottleneck),
101: ([3, 4, 23, 3], bottleneck),
152: ([3, 8, 36, 3], bottleneck)
}[101]
with argscope([Conv2D, MaxPooling, GlobalAvgPooling, BatchNorm], data_format='NHWC'):
with argscope([BatchNorm], use_local_stat=False):
logits = resnet_backbone(image, num_blocks, resnet_group, resnet_group_dilation, block_func, resnet_bottleneck_dilation)
# image075 = tf.image.resize_images(image, [int(image.get_shape().as_list()[1]*0.75), int(image.get_shape().as_list()[2]*0.75)])
# with tf.variable_scope('', reuse=True):
# logits075 = resnet_backbone(image075, num_blocks, resnet_group, resnet_group_dilation, block_func, resnet_bottleneck_dilation)
# image05 = tf.image.resize_images(image, [int(image.get_shape().as_list()[1]*0.5), int(image.get_shape().as_list()[2]*0.5)])
# with tf.variable_scope('', reuse=True):
# logits05 = resnet_backbone(image05, num_blocks, resnet_group, resnet_group_dilation, block_func, resnet_bottleneck_dilation)
# logits = tf.reduce_max(tf.stack([logits100, tf.image.resize_images(logits075, tf.shape(logits100)[1:3, ]), tf.image.resize_images(logits05, tf.shape(logits100)[1:3, ])]), axis=0)
# with argscope([Conv2D, MaxPooling, GlobalAvgPooling, BatchNorm], data_format='NHWC'):
# with argscope([BatchNorm], use_local_stat=False):
# logits = resnet_backbone(image, num_blocks, resnet_group, resnet_group_dilation, block_func, resnet_bottleneck_dilation)
return logits
<file_sep>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import argparse
import os.path
import sys
import pandas as pd
import datetime
import numpy as np
from six.moves import xrange
import tensorflow as tf
import gr_models
from tensorflow.python.platform import gfile
from tensorpack.tfutils.tower import TowerContext
import pandas as pd
import cv2
from tqdm import tqdm
import pydensecrf.densecrf as dcrf
FLAGS = None
os.environ['CUDA_VISIBLE_DEVICES'] = "5"
CROPSHAPE = 480
def data_crop_test_output(session, gr_data, logits, image, mean, std, crop_size, stride):
image_h = image.shape[0]
image_w = image.shape[1]
image = np.asarray(image, dtype='float32')
image = image * (1.0 / 255)
image = (image - mean) / std
pad_h = 0
pad_w = 0
if image_h >= crop_size and image_w >= crop_size:
image_pad = image
else:
if image_h < crop_size:
pad_h = crop_size - image_h
if image_w < crop_size:
pad_w = crop_size - image_w
image_pad = np.pad(image, ((0, pad_h), (0, pad_w), (0, 0)), 'constant')
image_crop_batch = []
x_start = range(0, image_pad.shape[0] - crop_size + 1, stride)
y_start = range(0, image_pad.shape[1] - crop_size + 1, stride)
if (image_pad.shape[0]-crop_size)%stride != 0:
x_start.append(image_pad.shape[0]-crop_size)
if (image_pad.shape[1]-crop_size)%stride != 0:
y_start.append(image_pad.shape[1]-crop_size)
for x in x_start:
for y in y_start:
image_crop_batch.append(image_pad[x:x+crop_size, y:y+crop_size])
logits = session.run(
logits,
feed_dict={
gr_data: image_crop_batch,
})
num_class = 21
score_map = np.zeros([image_pad.shape[0], image_pad.shape[1], num_class], dtype = 'float32')
count = np.zeros([image_pad.shape[0], image_pad.shape[1], num_class], dtype = 'float32')
crop_index = 0
for x in x_start:
for y in y_start:
crop_logits = logits[crop_index]
score_map[x:x+crop_logits.shape[0], y:y+crop_logits.shape[1]] += crop_logits
count[x:x+crop_logits.shape[0], y:y+crop_logits.shape[1]] += 1
crop_index += 1
score_map = score_map[:image_h,:image_w] / count[:image_h,:image_w]
return score_map
def dense_crf_batch(probs, img=None, n_iters=10,
sxy_gaussian=(1, 1), compat_gaussian=4,
kernel_gaussian=dcrf.DIAG_KERNEL,
normalisation_gaussian=dcrf.NORMALIZE_SYMMETRIC,
sxy_bilateral=(49, 49), compat_bilateral=5,
srgb_bilateral=(13, 13, 13),
kernel_bilateral=dcrf.DIAG_KERNEL,
normalisation_bilateral=dcrf.NORMALIZE_SYMMETRIC):
"""DenseCRF over unnormalised predictions.
More details on the arguments at https://github.com/lucasb-eyer/pydensecrf.
Args:
probs: class probabilities per pixel.
img: if given, the pairwise bilateral potential on raw RGB values will be computed.
n_iters: number of iterations of MAP inference.
sxy_gaussian: standard deviations for the location component of the colour-independent term.
compat_gaussian: label compatibilities for the colour-independent term (can be a number, a 1D array, or a 2D array).
kernel_gaussian: kernel precision matrix for the colour-independent term (can take values CONST_KERNEL, DIAG_KERNEL, or FULL_KERNEL).
normalisation_gaussian: normalisation for the colour-independent term (possible values are NO_NORMALIZATION, NORMALIZE_BEFORE, NORMALIZE_AFTER, NORMALIZE_SYMMETRIC).
sxy_bilateral: standard deviations for the location component of the colour-dependent term.
compat_bilateral: label compatibilities for the colour-dependent term (can be a number, a 1D array, or a 2D array).
srgb_bilateral: standard deviations for the colour component of the colour-dependent term.
kernel_bilateral: kernel precision matrix for the colour-dependent term (can take values CONST_KERNEL, DIAG_KERNEL, or FULL_KERNEL).
normalisation_bilateral: normalisation for the colour-dependent term (possible values are NO_NORMALIZATION, NORMALIZE_BEFORE, NORMALIZE_AFTER, NORMALIZE_SYMMETRIC).
Returns:
Refined predictions after MAP inference.
"""
n, h, w, _ = probs.shape
if img is not None:
assert(img.shape[0:3] == (n, h, w)), "The image height and width must coincide with dimensions of the logits."
for i in range(n):
probs[i] = dense_crf(probs[i], img[i])
else:
for i in range(n):
probs[i] = dense_crf(probs[i])
return probs
def dense_crf(probs, img=None, n_iters=10,
sxy_gaussian=(1, 1), compat_gaussian=4,
kernel_gaussian=dcrf.DIAG_KERNEL,
normalisation_gaussian=dcrf.NORMALIZE_SYMMETRIC,
sxy_bilateral=(49, 49), compat_bilateral=5,
srgb_bilateral=(13, 13, 13),
kernel_bilateral=dcrf.DIAG_KERNEL,
normalisation_bilateral=dcrf.NORMALIZE_SYMMETRIC):
"""DenseCRF over unnormalised predictions.
More details on the arguments at https://github.com/lucasb-eyer/pydensecrf.
Args:
probs: class probabilities per pixel.
img: if given, the pairwise bilateral potential on raw RGB values will be computed.
n_iters: number of iterations of MAP inference.
sxy_gaussian: standard deviations for the location component of the colour-independent term.
compat_gaussian: label compatibilities for the colour-independent term (can be a number, a 1D array, or a 2D array).
kernel_gaussian: kernel precision matrix for the colour-independent term (can take values CONST_KERNEL, DIAG_KERNEL, or FULL_KERNEL).
normalisation_gaussian: normalisation for the colour-independent term (possible values are NO_NORMALIZATION, NORMALIZE_BEFORE, NORMALIZE_AFTER, NORMALIZE_SYMMETRIC).
sxy_bilateral: standard deviations for the location component of the colour-dependent term.
compat_bilateral: label compatibilities for the colour-dependent term (can be a number, a 1D array, or a 2D array).
srgb_bilateral: standard deviations for the colour component of the colour-dependent term.
kernel_bilateral: kernel precision matrix for the colour-dependent term (can take values CONST_KERNEL, DIAG_KERNEL, or FULL_KERNEL).
normalisation_bilateral: normalisation for the colour-dependent term (possible values are NO_NORMALIZATION, NORMALIZE_BEFORE, NORMALIZE_AFTER, NORMALIZE_SYMMETRIC).
Returns:
Refined predictions after MAP inference.
"""
n_classes = 21
h, w, _ = probs.shape
probs = probs.transpose(2, 0, 1).copy(order='C') # Need a contiguous array.
d = dcrf.DenseCRF2D(w, h, n_classes) # Define DenseCRF model.
U = -np.log(probs) # Unary potential.
U = U.reshape((n_classes, -1)) # Needs to be flat.
d.setUnaryEnergy(U)
d.addPairwiseGaussian(sxy=sxy_gaussian, compat=compat_gaussian,
kernel=kernel_gaussian, normalization=normalisation_gaussian)
if img is not None:
assert(img.shape[0:2] == (h, w)), "The image height and width must coincide with dimensions of the logits."
d.addPairwiseBilateral(sxy=sxy_bilateral, compat=compat_bilateral,
kernel=kernel_bilateral, normalization=normalisation_bilateral,
srgb=srgb_bilateral, rgbim=img)
Q = d.inference(n_iters)
preds = np.array(Q, dtype=np.float32).reshape((n_classes, h, w)).transpose(1, 2, 0)
return preds
def randomCropPad(image, crop_h, crop_w):
image_h = image.shape[0]
image_w = image.shape[1]
pad_h = max(0, crop_h - image_h)
pad_w = max(0, crop_w - image_w)
image_pad = np.lib.pad(image, ((0,pad_h), (0,pad_w), (0,0)), 'constant',
constant_values=((128,128), (128,128), (128, 128)))
comb_h = image_pad.shape[0]
comb_w = image_pad.shape[1]
crop_scale = 0.5
crop_shift_h = int(crop_scale * float((comb_h - crop_h))/2)
crop_shift_w = int(crop_scale * float((comb_w - crop_w))/2)
image_crop = image_pad[crop_shift_h:crop_shift_h+crop_h, crop_shift_w:crop_shift_w+crop_w, :]
return image_crop
def main(_):
batch_size = 32
input_size = CROPSHAPE
num_class = 21
data_shape = CROPSHAPE
CRF = True
fname = []
output = []
#mean = [0.406, 0.485, 0.456]
#std = [0.225, 0.229, 0.224]
# mean = [0.406, 0.456, 0.485]
# std = [0.225, 0.224, 0.229]
mean = [0.406, 0.456, 0.485]
std = [0.225, 0.224, 0.229]
mean = np.asarray(mean, dtype='float32')
std = np.asarray(std, dtype='float32')
crop_size = CROPSHAPE
stride = int(CROPSHAPE/3)
df_test = pd.read_csv('test.csv', delim_whitespace=True, header=0)
# We want to see all the logging messages for this tutorial.
tf.logging.set_verbosity(tf.logging.INFO)
# Start a new TensorFlow session.
sess = tf.InteractiveSession()
###### input data
gr_data = tf.placeholder(
tf.float32, [None, data_shape, data_shape, 3], name='gr_data')
with TowerContext('', is_training=False):
#logits = gr_models.create_resnet_model(gr_data, is_training=False, isMSC=True, isASPP=True)
logits = gr_models.create_resnet_model(gr_data, is_training=False)
logits = tf.image.resize_bilinear(logits, [crop_size, crop_size])
if CRF:
image_mean = tf.constant(mean, dtype=tf.float32)
image_std = tf.constant(std, dtype=tf.float32)
image_origin = tf.cast((gr_data * image_std + image_mean)*255, tf.uint8)
logits = tf.nn.softmax(logits)
logits = tf.py_func(dense_crf_batch, [logits, image_origin], tf.float32)
#softmax ---> resize or resize ---> softmax
logits = tf.nn.softmax(logits)
# Load checkpoint
# assert os.path.isfile(FLAGS.start_checkpoint+'.meta'), FLAGS.start_checkpoint
gr_models.load_variables_from_checkpoint(sess, 'train_log/imagenet-resnet-d101-onlyval/model-1211488')
starttime = datetime.datetime.now()
print('Start eval @ ', starttime.strftime("%Y-%m-%d %H:%M:%S"))
for start in xrange(0, len(df_test), batch_size):
x_batch = []
end = min(start + batch_size, len(df_test))
df_test_batch = df_test[start:end]
img_size = []
real_batch = end - start
for id in df_test_batch['data']:
print ('/home/grwang/seg/voc-data/' + id)
img_ori = cv2.imread('/home/grwang/seg/' + id)
h_ori, w_ori, _ = img_ori.shape
if h_ori*w_ori < 460 * 500:
scs = [0.5, 0.75, 1.0, 1.25, 1.5, 1.75]
else:
scs = [0.5, 0.75, 1.0, 1.25, 1.5]
print(max(h_ori, w_ori))
maps = []
for sc in scs:
img = cv2.resize(img_ori, (int(float(w_ori)*sc), int(float(h_ori)*sc)), interpolation=cv2.INTER_CUBIC)
score_map = data_crop_test_output(sess, gr_data, logits, img, mean, std, crop_size, stride)
score_map = cv2.resize(score_map, (w_ori, h_ori), interpolation=cv2.INTER_CUBIC)
maps.append(score_map)
score_map = np.mean(np.stack(maps), axis=0)
maps2 = []
for sc in scs:
img2 = cv2.resize(img_ori, (int(float(w_ori)*sc), int(float(h_ori)*sc)), interpolation=cv2.INTER_CUBIC)
img2 = cv2.flip(img2, 1)
score_map2 = data_crop_test_output(sess, gr_data, logits, img2, mean, std, crop_size, stride)
score_map2 = cv2.resize(score_map2, (w_ori, h_ori), interpolation=cv2.INTER_CUBIC)
maps2.append(score_map2)
score_map2 = np.mean(np.stack(maps2), axis=0)
score_map2 = cv2.flip(score_map2, 1)
score_map = (score_map + score_map2)/2
pred_label = np.argmax(score_map, 2)
pred_label = np.asarray(pred_label, dtype='uint8')
print(np.max(pred_label))
name = id.split('/', 10)
cv2.imwrite('prediction-val-flip/' + name[1][0:11] + '.png', pred_label)
endtime = datetime.datetime.now()
print('Total time: ', endtime - starttime)
if __name__ == '__main__':
# if FLAGS.gpu:
# os.environ['CUDA_VISIBLE_DEVICES'] = FLAGS.gpu
tf.app.run(main=main)
<file_sep># Training ImageNet and PASCAL VOC2012 via Learning Feature Pyramids
The code is provided by [<NAME>](https://wanggrun.github.io/) ([<NAME>](http://www.sysu-hcp.net/people/) also provides contributions).
Sun Yat-sen University (SYSU)
### Table of Contents
0. [Introduction](#introduction)
0. [ImageNet](#imagenet)
0. [PASCAL VOC2012](#voc)
0. [Citation](#citation)
### Introduction
This repository contains the training & testing code on [ImageNet](http://image-net.org/challenges/LSVRC/2015/) and [PASCAL VOC2012](http://host.robots.ox.ac.uk:8080/leaderboard/displaylb.php?challengeid=11&compid=6) via learning feature pyramids (LFP). LFP is originally used for human pose machine, described in the paper "Learning Feature Pyramids for Human Pose Estimation" (https://arxiv.org/abs/1708.01101). We extend it to the semantic image segmentation.
### Results
+ Segmentation Visualization:
1. (a) input images; (b) segmentation results.

2. (a) images & ground truths; (b) trimap of learning feature pyramids; (c) trimap of the original ResNet.

3. It achieves 81.0% mIoU on PASCAL VOC2011 segmentation [leaderboard](http://host.robots.ox.ac.uk:8080/leaderboard/displaylb.php?challengeid=11&compid=6), a significance improvement over its baseline DeepLabV2 (79.6%).
### ImageNet
+ Training script:
```
cd pyramid/ImageNet/
python imagenet-resnet.py --gpu 0,1,2,3,4,5,6,7 --data_format NHWC -d 101 --mode resnet --data [ROOT-OF-IMAGENET-DATASET]
```
+ Testing script:
```
cd pyramid/ImageNet/
python imagenet-resnet.py --gpu 0,1,2,3,4,5,6,7 --load [ROOT-TO-LOAD-MODEL] --data_format NHWC -d 101 --mode resnet --data [ROOT-OF-IMAGENET-DATASET] --eval
```
+ Trained Models:
ResNet101:
[Baidu Pan](https://pan.baidu.com/s/1SKEmrjcYA-NR9oFBOD7Y2w), code: 269o
[Google Drive](https://drive.google.com/drive/folders/1pVSCQ6gap0b73FFr8bF-5p5Am6e2rXRr?usp=sharing)
ResNet50:
[Baidu Pan](https://pan.baidu.com/s/1ADYUt0QL1Vq42uqz75-W0A), code: zvgd
[Google Drive](https://drive.google.com/drive/folders/1zcwLZVFdm8PONL_R6_8TNSLvb1vs6Lh7?usp=sharing)
### PASCAL VOC2012
+ Training script:
```
# Use the ImageNet classification model as pretrained model.
# Because ImageNet has 1,000 categories while voc only has 21 categories,
# we must first fix all the parameters except the last layer including 21 channels. We only train the last layer for adaption
# by adding: "with freeze_variables(stop_gradient=True, skip_collection=True): " in Line 206 of resnet_model_voc_aspp.py
# Then we finetune all the parameters.
# For evaluation on voc val set, the model is first trained on COCO, then on train_aug of voc.
# For evaluation on voc leaderboard (test set), the above model is further trained on voc val.
# it achieves 81.0% on voc leaderboard.
# a training script example is as follows.
cd pyramid/VOC/
python resnet-msc-voc-aspp.py --gpu 0,1,2,3,4,5,6,7 --load [ROOT-TO-LOAD-MODEL] --data_format NHWC -d 101 --mode resnet --log_dir [ROOT-TO-SAVE-MODEL] --data [ROOT-OF-TRAINING-DATA]
```
+ Testing script:
```
cd pyramid/VOC/
python gr_test_pad_crf_msc_flip.py
```
+ Trained Models:
Model trained for evaluation on voc val set:
[Baidu Pan](https://pan.baidu.com/s/1C7r10EeZEOIn0njRCuuR1g), code: 7dl0
[Google Drive](https://drive.google.com/drive/folders/1c3Fr6yC_rwXGF4hJB4ADmtd2AF8wsO51?usp=sharing)
Model trained for evaluation on voc leaderboard (test set)
[Baidu Pan](https://pan.baidu.com/s/1C7r10EeZEOIn0njRCuuR1g), code: 7dl0
[Google Drive](https://drive.google.com/drive/folders/1c3Fr6yC_rwXGF4hJB4ADmtd2AF8wsO51?usp=sharing)
### Citation
If you use these models in your research, please cite:
@inproceedings{yang2017learning,
title={Learning feature pyramids for human pose estimation},
author={<NAME> and <NAME> and <NAME> and <NAME>},
booktitle={The IEEE International Conference on Computer Vision (ICCV)},
volume={2},
year={2017}
}
### Dependencies
+ Python 2.7 or 3
+ TensorFlow >= 1.3.0
+ [Tensorpack](https://github.com/ppwwyyxx/tensorpack)
The code depends on Yuxin Wu's Tensorpack. For convenience, we provide a stable version 'tensorpack-installed' in this repository.
```
# install tensorpack locally:
cd tensorpack-installed
python setup.py install --user
```
|
b32989ff5f9fa2a8447ddbd2b0428e20f48a9339
|
[
"Markdown",
"Python"
] | 6
|
Python
|
davidxue1989/Learning-Feature-Pyramids
|
8d271aee23369d4cc654dd763954adc95c2107f4
|
d1ee6b64aed26841f0e8da49190d329bb2512369
|
refs/heads/master
|
<file_sep>package pl.lukaszsroka.wraplayoutexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import pl.lukaszsroka.wraplayout.WrapLayout;
public class MainActivity extends AppCompatActivity {
WrapLayout wl;
int num;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wl = (WrapLayout) findViewById(R.id.wrap_layout);
num = 0;
}
public void clicked(View view) {
num++;
if(num == 10){
wl.setChildsInRow(5);
}
ImageView v = new ImageView(this);
v.setImageResource(R.mipmap.ic_launcher);
wl.addView(v);
}
}
<file_sep>include ':sample', ':wraplayout'
|
45f5b6d356725877c51e975d50e71c3a9d226e10
|
[
"Java",
"Gradle"
] | 2
|
Java
|
sroka-lukasz/Android-WrapLayout
|
b59ba4bcca11b4d9952618e3dd24af5c4a000430
|
9cf0c4dd4674478710729ad55bb780c752346392
|
refs/heads/main
|
<repo_name>kingmold/enapi<file_sep>/setup.py
import setuptools
from setuptools import setup
setup(name='enapi',
version='0.02',
description='Common API functionality',
url="https://github.com/kingmold/enapi",
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
packages=setuptools.find_packages(),
install_requires=[],
classifiers=(
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent"))
<file_sep>/enapi/__init__.py
import enapi
__all__ = ['enapi']
|
f230fd6c82d286f31c62e5cd2a99fb195251f51e
|
[
"Python"
] | 2
|
Python
|
kingmold/enapi
|
5e143bebc7cc5ae4b199584cda9fb1bee4cfc221
|
59d5fb7b9284738d23dc8e4ff7136a855d901167
|
refs/heads/master
|
<file_sep>package com.chayanin.hydroponic.model;
import com.google.firebase.database.IgnoreExtraProperties;
@IgnoreExtraProperties
public class SensorModel {
private double ph;
private double templeWater;
public double getPh() {
return ph;
}
public void setPh(double ph) {
this.ph = ph;
}
public double getTempleWater() {
return templeWater;
}
public void setTempleWater(double templeWater) {
this.templeWater = templeWater;
}
}
<file_sep>package com.chayanin.hydroponic;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.chayanin.hydroponic.model.ControllerModel;
import com.chayanin.hydroponic.model.RelayModel;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import az.plainpie.PieView;
import az.plainpie.animation.PieAngleAnimation;
public class HomeActivity extends BaseActivity implements View.OnClickListener {
ImageView relay1, relay2, relay3, relay4, switch_main;
TextView status_relay1, status_relay2, status_relay3, status_relay4;
TextView namerelay1, namerelay2, namerelay3, namerelay4;
PieView sensor1, sensor2;
int status1 = 0;
int status2 = 0;
int status3 = 0;
int status4 = 0;
int run = 0;
FirebaseDatabase database;
DatabaseReference myRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showProgressDialog(LOAD);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("controller").child("1123");
bindView();
getValue();
}
private void bindView() {
switch_main = findViewById(R.id.switch_main);
relay1 = findViewById(R.id.relay1);
relay2 = findViewById(R.id.relay2);
relay3 = findViewById(R.id.relay3);
relay4 = findViewById(R.id.relay4);
namerelay1 = findViewById(R.id.namerelay1);
namerelay2 = findViewById(R.id.namerelay2);
namerelay3 = findViewById(R.id.namerelay3);
namerelay4 = findViewById(R.id.namerelay4);
status_relay1 = findViewById(R.id.status_relay1);
status_relay2 = findViewById(R.id.status_relay2);
status_relay3 = findViewById(R.id.status_relay3);
status_relay4 = findViewById(R.id.status_relay4);
sensor1 = findViewById(R.id.pieView1);
sensor2 = findViewById(R.id.pieView2);
relay1.setOnClickListener(this);
relay2.setOnClickListener(this);
relay3.setOnClickListener(this);
relay4.setOnClickListener(this);
switch_main.setOnClickListener(this);
namerelay1.setText(getString(R.string.realy1));
namerelay2.setText(getString(R.string.realy2));
namerelay3.setText(getString(R.string.realy3));
namerelay4.setText(getString(R.string.realy4));
status_relay1.setText("(ปิดอยู่)");
status_relay2.setText("(ปิดอยู่)");
status_relay3.setText("(ปิดอยู่)");
status_relay4.setText("(ปิดอยู่)");
PieAngleAnimation animation1 = new PieAngleAnimation(sensor1);
PieAngleAnimation animation2 = new PieAngleAnimation(sensor2);
animation1.setDuration(3000);
animation2.setDuration(3000);
sensor1.startAnimation(animation1);
sensor2.startAnimation(animation2);
sensor1.setMaxPercentage(14);
sensor2.setMaxPercentage(100);
}
private void getValue() {
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
setValue(dataSnapshot.getValue(ControllerModel.class));
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void setValue(ControllerModel model) {
if (model.getSystem().getRun() == 0) {
run = 0;
switch_main.setImageDrawable(getDrawable(R.drawable.off));
} else if (model.getSystem().getRun() == 1) {
run = 1;
switch_main.setImageDrawable(getDrawable(R.drawable.on));
}
if (model.getRelay().getPum1() == 0) {
status_relay1.setText("(ปิดอยู่)");
status1 = 0;
relay1.setImageDrawable(getDrawable(R.drawable.switch_off));
} else if (model.getRelay().getPum1() == 1) {
status_relay1.setText("(เปิดอยู่)");
status1 = 1;
relay1.setImageDrawable(getDrawable(R.drawable.switch_on));
}
if (model.getRelay().getPum2() == 0) {
status_relay4.setText("(ปิดอยู่)");
status4 = 0;
relay4.setImageDrawable(getDrawable(R.drawable.switch_off));
} else if (model.getRelay().getPum2() == 1) {
status_relay4.setText("(เปิดอยู่)");
status4 = 1;
relay4.setImageDrawable(getDrawable(R.drawable.switch_on));
}
if (model.getRelay().getSo1() == 0) {
status_relay2.setText("(ปิดอยู่)");
status2 = 0;
relay2.setImageDrawable(getDrawable(R.drawable.switch_off));
} else if (model.getRelay().getSo1() == 1) {
status_relay2.setText("(เปิดอยู่)");
status2 = 1;
relay2.setImageDrawable(getDrawable(R.drawable.switch_on));
}
if (model.getRelay().getSo2() == 0) {
status_relay3.setText("(ปิดอยู่)");
status3 = 0;
relay3.setImageDrawable(getDrawable(R.drawable.switch_off));
} else if (model.getRelay().getSo2() == 1) {
status_relay3.setText("(เปิดอยู่)");
status3 = 1;
relay3.setImageDrawable(getDrawable(R.drawable.switch_on));
}
if (model.getSensor().getPh() > 0) {
sensor1.setPercentage((float) model.getSensor().getPh());
sensor1.setInnerText(model.getSensor().getPh() + " pH");
} else if (model.getSensor().getPh() == 0){
sensor1.setPercentage((float) 0.1);
sensor1.setInnerText(model.getSensor().getPh() + " pH");
}
if (model.getSensor().getTempleWater() > 0) {
sensor2.setPercentage((float) model.getSensor().getTempleWater());
sensor2.setInnerText(model.getSensor().getTempleWater() + "°c");
} else if (model.getSensor().getTempleWater() == 0){
sensor2.setPercentage((float) 0.1);
sensor2.setInnerText(model.getSensor().getTempleWater() + "°c");
}
hideProgressDialog();
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.relay1:
dialogSwitch(getString(R.string.realy1), status1, "pum1");
break;
case R.id.relay2:
dialogSwitch(getString(R.string.realy2), status2, "so1");
break;
case R.id.relay3:
dialogSwitch(getString(R.string.realy3), status3, "so2");
break;
case R.id.relay4:
dialogSwitch(getString(R.string.realy4), status4, "pum2");
break;
case R.id.switch_main:
dialogSwitch("ระบบ "+getString(R.string.app_name), run, "run");
break;
}
}
private void dialogSwitch(String name, int status, final String id) {
String detail = "";
if (status == 0) {
status += 1;
detail = name + " ปิดใช้งานอยู่ ต้องการเปิดหรือไม่ ?";
} else if (status == 1) {
status -= 1;
detail = name + " เปิดใช้งานอยู่ ต้องการปิดหรือไม่ ?";
}
final int finalStatus = status;
new AlertDialog.Builder(this, R.style.AppTheme_Dark_Dialog)
.setTitle("แจ้งเตือน")
.setMessage(detail)
.setNegativeButton("ตกลง", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
showProgressDialog(VERIFY);
dialogInterface.dismiss();
changStatusRelay(finalStatus, id);
}
}).setPositiveButton("ยกเลิก", null)
.setCancelable(false)
.show();
}
private void changStatusRelay(int status, String id) {
if (id.equals("run")) {
myRef.child("system").child(id).setValue(status);
hideProgressDialog();
} else {
myRef.child("relay").child(id).setValue(status);
hideProgressDialog();
}
}
}
|
87f5234f68beabca15d00f590caa8bdc42d21b59
|
[
"Java"
] | 2
|
Java
|
pechy2791/Hydroponic
|
0aa2c66cfc395658eae739c2acb66eb4fc561d1c
|
1262cd2ef36e48fca16f279962576bd5849b86d8
|
refs/heads/master
|
<file_sep>project:
gcc -o Login Login.c -lsocket -lnsl -lresolv
gcc -o Supernode Supernode.c -lsocket -lnsl -lresolv
gcc -o user1 user1.c -lsocket -lnsl -lresolv
gcc -o user2 user2.c -lsocket -lnsl -lresolv
gcc -o user3 user3.c -lsocket -lnsl -lresolv
<file_sep>/*
** Author:<NAME>
** Supernode.c
** Store username and IP address coming from Login server.
** Store the message coming from users and send the messages to the message.
** Some code from Beej's Guide book
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#define MAXDATASIZE 50//max size the buffer can store
#define PORT "22563" //static TCP port number to the Login server
#define PHASE3LISTENER "3563" //static UDP port number to the users
#define MAXBUFLEN 100// max size the buffer can store
#define PHASE3TALKER1 "3663"//static UDP port number to the user1
#define PHASE3TALKER2 "3763"//static UDP port number to the user2
#define PHASE3TALKER3 "3863"//static UDP port number to the user3
#define BACKLOG 10 // how many pending connections queue will hold
char textInfo[100];//Store the message
void sigchld_handler(int s)
{
while(waitpid(-1, NULL, WNOHANG) > 0);
}
// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
//The following code is used for sending the finish signal to tell the users to finish the phase 3
int finishSignal()
{ //The following connection setup code comes from Beej's book
int sockfd;
struct addrinfo hints, *servinfo, *p;
int rv;
int numbytes;
//The part of the code is to tell user1 to finish the phase 3
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
if ((rv = getaddrinfo("nunki.usc.edu", PHASE3TALKER1, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and make a socket
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("talker: socket");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "talker: failed to bind socket\n");
return 2;
}
//send finish signal
if ((numbytes = sendto(sockfd, "F", 1, 0,
p->ai_addr, p->ai_addrlen)) == -1) {
perror("talker: sendto");
exit(1);
}
freeaddrinfo(servinfo);
close(sockfd);
// The part of code is to tell the user2 to finish the phase 3
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
if ((rv = getaddrinfo("nunki.usc.edu", PHASE3TALKER2, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and make a socket
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("talker: socket");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "talker: failed to bind socket\n");
return 2;
}
//send finish signal
if ((numbytes = sendto(sockfd, "F", 1, 0,
p->ai_addr, p->ai_addrlen)) == -1) {
perror("talker: sendto");
exit(1);
}
freeaddrinfo(servinfo);
close(sockfd);
// The part of code is to tell the user2 to finish the phase 3
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
if ((rv = getaddrinfo("nunki.usc.edu", PHASE3TALKER3, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and make a socket
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("talker: socket");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "talker: failed to bind socket\n");
return 2;
}
//send finish signal
if ((numbytes = sendto(sockfd, "F", 1, 0,
p->ai_addr, p->ai_addrlen)) == -1) {
perror("talker: sendto");
exit(1);
}
freeaddrinfo(servinfo);
close(sockfd);
return 0;
}
//Send the message to the user1 through UDP
int phase3tranTo1()
{ //The following connection setup code comes from Beej's book
int sockfd;
struct addrinfo hints, *servinfo, *p;
int rv;
int numbytes;
int len;
struct hostent *host;//Get IP address
struct sockaddr_in sin;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
if ((rv = getaddrinfo("nunki.usc.edu", PHASE3TALKER1, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and make a socket
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("talker: socket");
continue;
}
break;
}
//bind function
bind(sockfd,(struct sockaddr *)&sin,sizeof(sin));
len = sizeof(sin);
if (p == NULL) {
fprintf(stderr, "talker: failed to bind socket\n");
return 2;
}
//Send the message to user1
if ((numbytes = sendto(sockfd, textInfo, strlen(textInfo), 0,
p->ai_addr, p->ai_addrlen)) == -1) {
perror("talker: sendto");
exit(1);
}
//Get the dynamic port number and print it out
getsockname(sockfd,(struct sockaddr *)&sin, &len);
printf("Phase 3: SuperNode sent the message %s on dynamic UDP port number %d\n",textInfo,ntohs(sin.sin_port));
freeaddrinfo(servinfo);
close(sockfd);
return 0;
}
//Send the message to the user2 through UDP
int phase3tranTo2()
{ //The following connection setup code comes from Beej's book
int sockfd;
struct addrinfo hints, *servinfo, *p;
int rv;
int numbytes;
int len;
struct hostent *host;//Get the IP address
struct sockaddr_in sin;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
if ((rv = getaddrinfo("nunki.usc.edu", PHASE3TALKER2, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and make a socket
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("talker: socket");
continue;
}
break;
}
//bind function
bind(sockfd,(struct sockaddr *)&sin,sizeof(sin));
len = sizeof(sin);
if (p == NULL) {
fprintf(stderr, "talker: failed to bind socket\n");
return 2;
}
//Send the message to user2
if ((numbytes = sendto(sockfd, textInfo, strlen(textInfo), 0,
p->ai_addr, p->ai_addrlen)) == -1) {
perror("talker: sendto");
exit(1);
}
//Get the dynamic port number and print it out
getsockname(sockfd,(struct sockaddr *)&sin, &len);
printf("Phase 3: SuperNode sent the message %s on dynamic UDP port number %d\n",textInfo,ntohs(sin.sin_port));
freeaddrinfo(servinfo);
close(sockfd);
return 0;
}
//Send the message to user3 through UDP
int phase3tranTo3()
{ //The following connection setup code comes from Beej's book
int sockfd;
struct addrinfo hints, *servinfo, *p;
int rv;
int numbytes;
int len;
struct hostent *host;//Use for getting IP address
struct sockaddr_in sin;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
if ((rv = getaddrinfo("nunki.usc.edu", PHASE3TALKER3, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and make a socket
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("talker: socket");
continue;
}
break;
}
//bind function
bind(sockfd,(struct sockaddr *)&sin,sizeof(sin));
len = sizeof(sin);
if (p == NULL) {
fprintf(stderr, "talker: failed to bind socket\n");
return 2;
}
//Send the message to the user3
if ((numbytes = sendto(sockfd, textInfo, strlen(textInfo), 0,
p->ai_addr, p->ai_addrlen)) == -1) {
perror("talker: sendto");
exit(1);
}
//Get the dynamic port number and print it out
getsockname(sockfd,(struct sockaddr *)&sin, &len);
printf("Phase 3: SuperNode sent the message %s on dynamic UDP port number %d\n",textInfo,ntohs(sin.sin_port));
freeaddrinfo(servinfo);
close(sockfd);
return 0;
}
//The following code is used for storing message coming from the users and the connection code comes from Beej's Guide book
int phase3listener()
{ //The following connection setup code comes from Beej's book
int sockfd;
struct addrinfo hints, *servinfo, *p;
int rv;
int numbytes;
struct sockaddr_storage their_addr;
char buf[MAXBUFLEN];
socklen_t addr_len;
char s[INET6_ADDRSTRLEN];
int anotherCounter = 0;//Counter to count how many users finish their message sending
struct hostent *host;//Get the IP address
FILE *fpinfo;
FILE *fptran;
fpinfo=fopen("getInfo.txt","w");//use for storing the message coming from users
host = gethostbyname("nunki.usc.edu");
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // set to AF_INET to force IPv4
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE; // use my IP
if ((rv = getaddrinfo(NULL, PHASE3LISTENER, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and bind to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("listener: socket");
continue;
}
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("listener: bind");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "listener: failed to bind socket\n");
return 2;
}
freeaddrinfo(servinfo);
addr_len = sizeof their_addr;
//When finish three users' sending message, it will jump the loop
while (anotherCounter != 3)
{ //Get the signal of which user sending its message
if ((numbytes = recvfrom(sockfd, buf, 100 , 0,
(struct sockaddr *)&their_addr, &addr_len)) == -1) {
perror("recvfrom");
exit(1);
}
//Get the user1's message and if it gets the finish signal, it will jump out the loop
if (numbytes == 1)
{
do
{
if ((numbytes = recvfrom(sockfd, buf, 100 , 0,(struct sockaddr *)&their_addr, &addr_len)) == -1) {
perror("recvfrom");
exit(1);
}
if (numbytes != 6)
{
buf[numbytes] = '\0';
printf("Phase 3: SuperNode received the message %s\n",buf);
fprintf(fpinfo,"%s",buf);
}
if (numbytes == 6)
anotherCounter++;
}while (numbytes != 6);
}//Get the user2's message and if it gets the finish signal, it will jump out the loop
if (numbytes == 2)
{
do
{
if ((numbytes = recvfrom(sockfd, buf, 100 , 0,(struct sockaddr *)&their_addr, &addr_len)) == -1) {
perror("recvfrom");
exit(1);
}
if (numbytes != 6)
{
buf[numbytes] = '\0';
printf("Phase 3: SuperNode received the message %s\n",buf);
fprintf(fpinfo,"%s",buf);
}
if (numbytes == 6)
anotherCounter++;
}while (numbytes != 6);
}
//Get the user3's message and if it gets the finish signal, it will jump out the loop
if (numbytes == 3)
{
do
{
if ((numbytes = recvfrom(sockfd, buf, 100 , 0,(struct sockaddr *)&their_addr, &addr_len)) == -1) {
perror("recvfrom");
exit(1);
}
if (numbytes != 6)
{
buf[numbytes] = '\0';
printf("Phase 3: SuperNode received the message %s\n",buf);
fprintf(fpinfo,"%s",buf);
}
if (numbytes == 6)
anotherCounter++;
}while (numbytes != 6);
}
}
fclose(fpinfo);
close(sockfd);
//Open the getInfo.txt to ready to send the message to the users
fptran=fopen("getInfo.txt","r");
while(fgets(textInfo,100,fptran))
{
//If the message will be send to user1, it will go another function
if(textInfo[5] == '1')
{
phase3tranTo1();
} //If the message will be send to user2, it will go another function
if (textInfo[5] == '2')
{
phase3tranTo2();
} //If the message will be send to user3, it will go another function
if (textInfo[5] == '3')
{
phase3tranTo3();
}
}
fclose(fptran);//close the file
finishSignal();//Send the finish signal to the users
printf("End of Phase 3 for SuperNode.\n");
return 0;
}
int main(void)
{ //The following connection setup code comes from Beej's book
int sockfd, new_fd; // listen on sock_fd, new connection on new_fd
struct addrinfo hints, *servinfo, *p;
struct sockaddr_storage their_addr; // connector's address information
socklen_t sin_size;
struct sigaction sa;
int yes=1;
char s[INET6_ADDRSTRLEN];
char buf[MAXDATASIZE];
int rv;
int numbytes;
int i;
struct hostent *host;//Use for IP address
int count = 0;//counter for receiving information from Login server
char userName[3][50];//Store the username and IP address getting from the login server
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // use my IP
host = gethostbyname("nunki.usc.edu"); //get the IP address
if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and bind to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("server: socket");
continue;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,
sizeof(int)) == -1) {
perror("setsockopt");
exit(1);
}
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("server: bind");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "server: failed to bind\n");
return 2;
}
freeaddrinfo(servinfo); // all done with this structure
if (listen(sockfd, BACKLOG) == -1) {
perror("listen");
exit(1);
}
sa.sa_handler = sigchld_handler; // reap all dead processes
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(SIGCHLD, &sa, NULL) == -1) {
perror("sigaction");
exit(1);
}
//establish TCP connection
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1) {
perror("accept");
}
//print the TCP port number and IP address
printf("Phase 2: SuperNode has TCP port 22563 and IP address:%s\n",inet_ntoa(*((struct in_addr*)host->h_addr_list[0])));
//Get the IP address and username from login server and stor them into array
while(count <= 2) {
if ((numbytes = recv(new_fd, buf, MAXDATASIZE, 0)) == -1) {
perror("recv");
exit(1);
}
buf[numbytes] = '\0';
strcpy(userName[count], buf);
count ++;
}
close(new_fd);
printf("Phase 2: SuperNode received %d username/IP address pairs.\n",count);
printf("End of Phase 2 for SuperNode.\n");
phase3listener();//Jump to phase 3 for getting the message from users
return 0;
}
<file_sep>a. Name: <NAME>
b. The pdf is the description of this homework
c. First, I build the login server for users to login; meanwhile, the server will check the personal information from users is valid or not. Second, I build the connection between login server and supernode. It is for the server to send the correct user which IP address to supernode. Finally, I setup the connections between supernode and users. By using listener() and talker(), users can send their messages to supernode first and then supernode will deliver to the correct receiver later.
d. Login.c is the code for login server. It is the code to match whether the user send the valid information.Meanwhile,it will send user and IP address to supernode.
Supernode.c is the code for building connection between server and supernode. Besides, there is a file called getInfo.txt that is the one for supernode to store the messages from users and then, supernode will send the messages to the user who should receive by checking this file.
User1, user2, and user3 are the codes for users. In addition, there are also the codes for building connection between users and supernode.
Makefile is the easier way to compile the codes.
e. First, TA should run makefile to compile these code.Then, TA should run my login file and supernode file in 2 different terminals. Second, TA should open 3 more terminals as three users. Then, TA can run my user1, user2, and user3 files in order in different 3 terminals. By doing this, the server can check whether their personal information are correct or not. After the server make sure their info are correct, the server will send the IP addresses and these users to supernode. In the end, TA should run user1, user2, and user3 files in different terminals again in order to start their conversations.
f.
In the supernode, getInfo.txt will store the messages which are from users and supernode will read it to send the message to the correct receiver.The other messages are stored in string array.
g.
If TA does not follow the instructions, then my project might fail.
<file_sep>/*
** Author:<NAME>
** user1.c
** Send the user name and password to login and send message to Supernode and get the message from Supernode.
** Some code from Beej's Guide book
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT "21563" // TCP login server static port
#define PHASE3TALKER "3563"//UDP supernode server static port
#define PHASE3LISTENER "3663"//UDP user1 static port
#define MAXBUFLEN 100 //max number of bytes in buffer we can get
#define MAXDATASIZE 100 // max number of bytes in buffer we can tet
// get sockaddr, IPv4 or IPv6: From Beej's Guide book
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
//user1 listen the UDP port with supernode and get message from supernode. The UDP connection code is from Beej's Guide Book
int phase3listener()
{ //The following connection setup code comes from Beej's book
int sockfd;
struct addrinfo hints, *servinfo, *p;
int rv;
int numbytes;
struct sockaddr_storage their_addr;
char buf[MAXBUFLEN];
socklen_t addr_len;
char s[INET6_ADDRSTRLEN];
char *showFirstMessage;//Split the message getting from the supernode
char *showSecondMessage;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // set to AF_INET to force IPv4
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE; // use my IP
if ((rv = getaddrinfo(NULL, PHASE3LISTENER, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and bind to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("listener: socket");
continue;
}
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("listener: bind");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "listener: failed to bind socket\n");
return 2;
}
freeaddrinfo(servinfo);
addr_len = sizeof their_addr;
//The following code will get the message from the supernode and display the receved message on the screen
while(1)
{ //If user get the finish signal, it will jump out the loop
if ((numbytes = recvfrom(sockfd, buf, MAXBUFLEN , 0,
(struct sockaddr *)&their_addr, &addr_len)) == -1) {
perror("recvfrom");
exit(1);
}
if(numbytes == 1)
break;
else
{
buf[numbytes] = '\0';
showFirstMessage = strtok(buf,"-");
showSecondMessage = strtok(NULL,"-");
printf("Phase 3: <User1> received the message %s",showSecondMessage);
}
}
close(sockfd);
printf("End of Phase 3 for <User1>\n");
return 0;
}
int phase3talker()
{ //The following connection setup code comes from Beej's book
int sockfd;
struct addrinfo hints, *servinfo, *p;
int rv;
int numbytes;
int len;
char getInfo[100];//Get the message from UserText1.txt
struct hostent *host;
struct sockaddr_in sin;
FILE *fp;
//Open UserText1.txt to get the message which will be sent to supernode
if((fp = fopen("UserText1.txt", "r")) == NULL){
printf("Can not open UserText1.txt\n");
exit(1);
}
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;// set to AF_INET to force IPv4
hints.ai_socktype = SOCK_DGRAM;
if ((rv = getaddrinfo("nunki.usc.edu", PHASE3TALKER, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and make a socket
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("talker: socket");
continue;
}
break;
}
//Get the dynamic port number
bind(sockfd,(struct sockaddr *)&sin,sizeof(sin));
len = sizeof(sin);
if (p == NULL) {
fprintf(stderr, "talker: failed to bind socket\n");
return 2;
}
//Print the IP address and port number
host = gethostbyname("nunki.usc.edu");
printf("End of Phase 1 for <User1>.\n");
printf("Phase 3: <User1> has static UDP port 3663 IP address %s.\n",inet_ntoa(*((struct in_addr*)host->h_addr_list[0])));
//The following code will get message and send it to supernode
//Send signal to notice that it is user1 to send the message to the supernode
if ((numbytes = sendto(sockfd, "a", 1, 0, p->ai_addr, p->ai_addrlen)) == -1) {
perror("talker: sendto");
exit(1);
}
//Send message line by line in the file
while(fgets(getInfo, 100, fp))
{
if ((numbytes = sendto(sockfd, getInfo, 100, 0,
p->ai_addr, p->ai_addrlen)) == -1) {
perror("talker: sendto");
exit(1);
}
getsockname(sockfd,(struct sockaddr *)&sin, &len);
printf("Phase 3: <User1> is sending the message %s on UDP dynamic port number %d\n",getInfo,ntohs(sin.sin_port));
}
//send signal to notice that user1 finish the process of sending message
if ((numbytes = sendto(sockfd, "finish", 6, 0, p->ai_addr, p->ai_addrlen)) == -1) {
perror("talker: sendto");
exit(1);
}
freeaddrinfo(servinfo);
fclose(fp);
close(sockfd);
//Enter the phase 3 to get the message coming from supernode
phase3listener();
return 0;
}
int main(void)
{ //The following connection setup code comes from Beej's book
int sockfd, numbytes;
char buf[MAXDATASIZE];
struct addrinfo hints, *servinfo, *p;
int rv;
char s[INET6_ADDRSTRLEN];
char userPassword[100];//Open the file and get each pair of password and username
socklen_t len;
struct hostent *host;//Use gethostbyname function
int supernodePortNum = 3563;
char *prUser;//Store the username
char *prPass;//Store the password
FILE *fp;
//Open UserPass1.txt
if((fp = fopen("UserPass1.txt", "r")) == NULL){
printf("Can not open UserPass1.txt\n");
exit(1);
}
//Get each line of password and username in UserPass1.txt
fgets(userPassword, 100, fp);
//Close UserPass1.txt
fclose(fp);
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo("nunki.usc.edu", PORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and connect to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("client: socket");
continue;
}
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
continue;
}
break;
}
if (p == NULL) {
phase3talker();//Go to send message function.
return 2;
}
//get the dynamic port number and IP address
host = gethostbyname("nunki.usc.edu");
getsockname(sockfd,p->ai_addr, &len);
freeaddrinfo(servinfo); // all done with this structure
printf("Phase 1: <User1> has TCP port %d and IP address: %s\n",ntohs(((struct sockaddr_in *)(p->ai_addr))->sin_port),inet_ntoa(*((struct in_addr*)host->h_addr_list[0])));
//Send the pair of username and password to Login server to wait for response
if (send(sockfd, userPassword, 100, 0) == -1)
perror("send");
if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {
perror("recv");
exit(1);
}
//Split the pair of username and password and display each username and password
prUser = strtok(userPassword," ");
prPass = strtok(NULL," ");
printf("Phase 1: Login request. User: %s password: %s",prUser,prPass);
buf[numbytes] = '\0';
//Show the Login request and IP address and port number
printf("Phase 1: Login request reply:%s.\n",buf);
printf("Phase 1: Supernode has IP Address %s and Port Number %d\n",inet_ntoa(*((struct in_addr*)host->h_addr_list[0])),supernodePortNum);
close(sockfd);
return 0;
}
<file_sep>/*
** Author:<NAME>
** Login.c
** Check the username and password coming from users and give request and supernode port number and IP address to users
** Send the IP and username to supernode
** Some code from Beej's Guide book
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#define MAXDATASIZE 100//max size the buffer can store
#define PORT "21563" // static port number the user connect
#define PORT2 "22563"//static port number to connect supernode
#define BACKLOG 10 // how many pending connections queue will hold
char userName[3][50];//Store the username coming from users
char *pass[3];//Store the password
char *interChange;//temporary to store the username
char *WrongUserName;//store the reject username
char *WrongPass;//store the reject password
void sigchld_handler(int s)
{
while(waitpid(-1, NULL, WNOHANG) > 0);
}
// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
//The following function is used for phase 2
int subLogin()
{
//The following connection setup code comes from Beej's book
int sockfd, numbytes;
char buf[MAXDATASIZE];
struct addrinfo hints, *servinfo, *p;
int rv;
char s[INET6_ADDRSTRLEN];
int j;
struct hostent *host;//store the IP address
socklen_t len;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo("nunki.usc.edu", PORT2, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and connect to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("client: socket");
continue;
}
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("client: connect");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "client: failed to connect\n");
return 2;
}
freeaddrinfo(servinfo); // all done with this structure
host = gethostbyname("nunki.usc.edu");//Show the IP address
getsockname(sockfd,p->ai_addr, &len);//Get the dynamic port number
printf("Phase 2: LogIn server has TCP port number %d and IP address %s\n",ntohs(((struct sockaddr_in *)(p->ai_addr))->sin_port),inet_ntoa(*((struct in_addr*)host->h_addr_list[0])));
//Send the username and IP address to Supernode
for (j = 0;j <= 2; j++)
{
if (send(sockfd, userName[j], 50, 0) == -1)
perror("send");
}
printf("Phase 2: LogIn server sent %d username/IP address pairs to SuperNode.\n",j);
close(sockfd);
printf("End of Phase 2 for Login Server.\n");
return 0;
}
int main(void)
{ //The following connection setup code comes from Beej's book
int sockfd, new_fd; // listen on sock_fd, new connection on new_fd
struct addrinfo hints, *servinfo, *p;
struct sockaddr_storage their_addr; // connector's address information
socklen_t sin_size;
struct sigaction sa;
int yes=1;
char s[INET6_ADDRSTRLEN];
char buf[MAXDATASIZE];
int rv;
int numbytes;
int flag = 0;//To justice reject or accept
int i;
struct hostent *host;//Get the IP address
char compareUserPass[100];//Get username and password from UserPassMatch.txt
int count = 0;
FILE *fp;
//Open the file UserPassMatch.txt
if((fp = fopen("UserPassMatch.txt", "r")) == NULL){
printf("Can not open UserPassMatch.txt\n");
exit(1);
}
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // use my IP
host = gethostbyname("nunki.usc.edu"); //get the IP address
printf("Phase 1:LogIn server has TCP port 21563 and IP address %s\n",inet_ntoa(*((struct in_addr*)host->h_addr_list[0])));
if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and bind to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("server: socket");
continue;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,
sizeof(int)) == -1) {
perror("setsockopt");
exit(1);
}
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("server: bind");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "server: failed to bind\n");
return 2;
}
freeaddrinfo(servinfo); // all done with this structure
if (listen(sockfd, BACKLOG) == -1) {
perror("listen");
exit(1);
}
sa.sa_handler = sigchld_handler; // reap all dead processes
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(SIGCHLD, &sa, NULL) == -1) {
perror("sigaction");
exit(1);
}
//If get three correct username and password pairs, it will jump out the loop
while(count <= 2) {
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1) {
perror("accept");
continue;
}
//Get the username and password pair from users
if ((numbytes = recv(new_fd, buf, MAXDATASIZE-1, 0)) == -1) {
perror("recv");
exit(1);
}
buf[numbytes] = '\0';
//Read the UserPassMatch.txt line by line and compare it to the receiving username and password pairs
while(fgets(compareUserPass, 100, fp))
{
if(strcmp(compareUserPass,buf)==0)
{ //Send the accept to the user
if (send(new_fd, "Accept", 6, 0) == -1)
perror("send");
//Split username and password and display it
interChange = strtok(compareUserPass," ");
strcpy(userName[count], interChange);
pass[count] = strtok(NULL," ");
printf("Phase 1: Authentication request. User:%s Password:%s User IP Addr:%s.Authorized:Accepted\n",userName[count],pass[count],inet_ntoa(*((struct in_addr*)host->h_addr_list[0])));
flag = 1;
count ++;
printf("Phase 1: SuperNode IP Address:%s Port Number:3563 sent to the <User%d>\n",inet_ntoa(*((struct in_addr*)host->h_addr_list[0])),count);
break;
}
}
if(flag == 0)
{ //Send the reject to the user if request is rejected
if(send(new_fd, "Reject", 6, 0) == -1)
perror("send");
//Split the username and password to display it
WrongUserName = strtok(buf," ");
WrongPass =strtok(NULL," ");
printf("Phase 1: Authentication request. User:%s Password:%s User IP Addr:%s.Authorized:Rejected\n",WrongUserName,WrongPass,inet_ntoa(*((struct in_addr*)host->h_addr_list[0])));
}
fseek(fp, 0,SEEK_SET);//Set the point at the beginning of the file
flag = 0;
close(new_fd);
}
printf("End of Phase 1 for Login Server\n");
fclose(fp);
close(sockfd);
subLogin();//Go to Phase 2 function
return 0;
}
|
485d79ac4ecec3ceb6b683f6d2cfdb8b763d1027
|
[
"Text",
"C",
"Makefile"
] | 5
|
Makefile
|
liar1974/socketCProgram2
|
2b98272fa501b496b693041e6c976c9616198f4a
|
073531042d4f427a44cc8d3f23cb10abf8a8f726
|
refs/heads/master
|
<repo_name>starwels/adress_book<file_sep>/app/controllers/concerns/authenticable.rb
module Authenticable
def encode_token(payload)
JWT.encode(payload, Rails.application.credentials.read)
end
def decoded_token
if token_from_request_header
begin
JWT.decode(token_from_request_header, Rails.application.credentials.read, true)
rescue JWT::DecodeError
nil
end
end
end
def authenticate_user!
unauthorized_entity unless authenticate
end
def authenticate_admin!
unauthorized_entity unless current_user.admin?
end
def get_current_user
authenticate
end
def authenticate
if decoded_token
begin
user_id = decoded_token[0]['sub']
User.find(user_id)
rescue ActiveRecorde::NotFound, JWT::DecodeError, JWT::EncodeError
nil
end
end
end
def token_from_request_header
request.headers["Authorization"]&.split&.last
end
def unauthorized_entity
head(:unauthorized)
end
end<file_sep>/app/models/contact.rb
class Contact
include Firestore
validates :email, presence: true
validates :name, presence: true
validates :organization_id, presence: true
attr_accessor :id, :name, :email, :phone, :organization_id
belongs_to :organization
end<file_sep>/spec/requests/health_check_spec.rb
require 'rails_helper'
RSpec.describe "HealthChecks", type: :request do
describe "GET /" do
context "when client requests html" do
it "should return proper message" do
get root_path
expect(response.body).to eq("I am up and running!")
end
end
context "when client requests json" do
it "should return proper message" do
get root_path, headers: { "Accept": "application/json" }
expect(response.body).to eq("I am up and running!")
end
end
end
end
<file_sep>/spec/models/organization_spec.rb
require 'rails_helper'
RSpec.describe Organization, type: :model do
let(:organization) { build(:organization) }
it "is not valid without a name" do
organization.name = nil
expect(organization).to_not be_valid
end
it "is valid with valid attributes" do
expect(organization).to be_valid
end
end
<file_sep>/app/controllers/health_check_controller.rb
class HealthCheckController < ActionController::Base
def index
body = 'I am up and running!'
respond_to do |format|
format.json { render json: body, status: :ok }
format.html { render html: body }
end
end
end<file_sep>/app/controllers/api/v1/contacts_controller.rb
class Api::V1::ContactsController < ApplicationController
before_action :set_organization, except: :destroy
before_action :check_organization, only: [:create, :update]
def index
contacts = @organization.contacts
render json: { contacts: contacts }
end
def create
contact = Contact.new(contact_params)
if contact.save
render json: { contact: contact.to_json }, status: :created
else
render json: { errors: contact.errors }, status: :unprocessable_entity
end
end
def update
contact = Contact.find_document(params[:id])
if contact.update(contact_params)
render json: { contact: contact.to_json }, status: :ok
else
render json: { errors: contact.errors }, status: :unprocessable_entity
end
end
def destroy
organizations = current_user.organizations.all
contact = Contact.find_document(params[:id])
return render json: {}, status: :no_content if contact.nil?
return unauthorized_entity if organizations.map(&:id).exclude?(contact.organization_id)
contact.delete
end
private
def contact_params
params.require(:contact).permit(:name, :email, :phone, :organization_id)
end
def check_organization
unauthorized_entity if @organization.nil?
end
def set_organization
@organization = current_user.organizations.find(params[:organization_id] || params[:contact][:organization_id])
end
end<file_sep>/spec/factories/users.rb
FactoryBot.define do
factory :user do
email { Faker::Internet.email }
password { <PASSWORD> }
trait :as_admin do
role { :admin }
end
trait :with_organization do
after(:build) do |user|
user.organizations << create(:organization)
end
before(:create) do |user|
user.organizations << create(:organization)
end
end
end
end
<file_sep>/spec/requests/api/v1/authentications_spec.rb
require 'rails_helper'
require 'support/request_spec_helper'
RSpec.describe "Api::V1::Authentications", type: :request do
include RequestSpecHelper
describe "POST /api/v1/authentications" do
let(:user) { create(:user, :with_organization) }
context 'when params are valid' do
let(:authentication_params) do
{
authentication: {
email: user.email,
password: <PASSWORD>,
}
}
end
it "returns status 201" do
post api_v1_authentications_path, params: authentication_params
expect(response).to have_http_status(201)
end
it "returns the user token" do
post api_v1_authentications_path, params: authentication_params
expect(json_body[:token]).to eq(token_generator(user))
end
end
context 'when params are invalid' do
let(:authentication_params) do
{
authentication: {
email: user.email,
password: <PASSWORD>",
}
}
end
it "returns status 401" do
post api_v1_authentications_path, headers: headers, params: authentication_params
expect(response).to have_http_status(401)
end
end
end
end
<file_sep>/spec/models/contact_spec.rb
require 'rails_helper'
require "google/cloud/firestore"
RSpec.describe Organization do
let(:contact) { build(:contact) }
let(:expected_response) do
{
id: contact.id,
name: contact.name,
email: contact.email,
phone: contact.phone,
organization_id: contact.organization_id
}
end
before do
allow(Contact).to receive(:collection_name).and_return('testing')
end
after(:each) do
contacts = Contact.list_by_association_id(contact.organization_id)
contacts.each do |contact|
contact_document = Contact.find_document(contact[:id])
contact_document.delete
end
end
describe ".find_document" do
context "when document exists" do
it "returns the correct document" do
contact.save
expect(Contact.find_document(contact.id)).to be_instance_of(Contact)
end
it "returns document with correct id" do
contact.save
contact_response = Contact.find_document(contact.id)
expect(contact_response.id).to eq(contact.id)
end
end
context "when document does not exist" do
it "returns the correct document" do
expect(Contact.find_document(-1)).to be_nil
end
end
end
describe ".list_by_association_id" do
let(:contact2) { build(:contact, organization_id: contact.organization_id) }
after do
contact2.delete
end
it "returns the correct size of the contacts by organization" do
contact.save
contact2.save
expect(Contact.list_by_association_id(contact.organization_id).size).to eq(2)
end
end
describe "#get" do
it "returns the correct contact" do
contact.save
contact_doc = Contact.find_document(contact.id)
expect(contact_doc.get).to match(expected_response)
end
end
describe "#save" do
it 'saves contact and returns the saved contact' do
expect(contact.save).to match(expected_response)
end
end
describe "#delete" do
it 'deletes the contact' do
contact.save
expect(contact.delete).to_not be_nil
end
end
describe "#update" do
let(:params) { attributes_for(:contact) }
let(:expected_response) do
{
id: contact.id,
name: params[:name],
email: params[:email],
phone: params[:phone],
organization_id: params[:organization_id]
}
end
it 'updates the contact and returns the updated contact' do
contact.save
expect(contact.update(params)).to match(expected_response)
end
end
end<file_sep>/app/controllers/api/v1/organizations_controller.rb
class Api::V1::OrganizationsController < ApplicationController
before_action :authenticate_admin!, only: :create
def index
organizations = Organization.all
render json: { organizations: organizations }, status: :ok
end
def create
organization = Organization.new(organization_params)
if organization.save
render json: { organization: organization }, status: :created
else
render json: { errors: organization.errors }, status: :unprocessable_entity
end
end
private
def organization_params
params.require(:organization).permit(:name)
end
end<file_sep>/app/models/user.rb
class User < ApplicationRecord
has_secure_password
has_and_belongs_to_many :organizations
validates :email, presence: true, uniqueness: true
validates :organizations, presence: true
validates :password, length: { in: 6..20 }
enum role: { user: 0, admin: 1 }
def admin?
role.eql?('admin')
end
end
<file_sep>/spec/requests/api/v1/registrations_spec.rb
require 'rails_helper'
require 'support/request_spec_helper'
RSpec.describe "Api::V1::Users", type: :request do
include RequestSpecHelper
describe "POST /api/v1/registrations" do
context 'when params are valid' do
let(:organizations_ids) { create_list(:organization, 3).map(&:id) }
let(:registration_params) do
{
registration: {
user: attributes_for(:user),
organizations_ids: organizations_ids,
}
}
end
it "returns status 201" do
post api_v1_registrations_path, params: registration_params
expect(response).to have_http_status(201)
end
it "returns the created user" do
post api_v1_registrations_path, params: registration_params
expect(json_body[:user][:email]).to eq(registration_params[:registration][:user][:email])
end
it "returns the user token" do
post api_v1_registrations_path, params: registration_params
expect(json_body[:token]).to eq(JWT.encode({ sub: json_body[:user][:id] }, Rails.application.credentials.read))
end
it "has 3 associated organizations" do
post api_v1_registrations_path, params: registration_params
user = User.find(json_body[:user][:id])
expect(user.organizations.size).to eq(3)
end
end
context 'when params are invalid' do
let(:registration_params) do
{
registration: {
user: {
email: nil
}
}
}
end
it "returns status 422" do
post api_v1_registrations_path, params: registration_params
expect(response).to have_http_status(422)
end
it "returns errors" do
post api_v1_registrations_path, params: registration_params
expect(json_body).to include(:errors)
end
end
end
end<file_sep>/README.md
## Description
This app uses Ruby 2.7.2 and Rails ~> 6.1.1
## Deployed Backend
Admin user
`email: <EMAIL>`
`password: <PASSWORD>`
Regular user
`<EMAIL>`
`password: <PASSWORD>`
Organization
`name: STRV`
And no contacts
## Development Instructions
To run this app locally you have to run in the project root.
`bundle exec bin/setup`
It will create one admin user
`email: <EMAIL>`
`password: <PASSWORD>`
One organization
`name: STRV`
And one regular user
`<EMAIL>`
`password: <PASSWORD>`
Both admin and user are under STRV organization.
After that you have to paste the json key inside of key.json.
And paste the proper envs inside of .env.local and .env.test
`PROJECT_ID=<project_id>`
`GOOGLE_APPLICATION_CREDENTIALS="./key.json"`
## Endpoints
### POST /api/v1/registrations
##### request
```
{
"registration": {
"user": {
"email": <email>,
"password": <<PASSWORD>>
}
"organizations_ids": <array of ids>
}
```
#### response
```
{
"user": {
"id": <id>,
"email": <email>
},
"token": <token>
}
```
### POST /api/v1/authentications
##### request
```
{
"authentication": {
"email": <email>,
"password": <<PASSWORD>>
}
}
```
#### response
```
{
"token": <token>
}
```
Every request from needs the header
`Authorization: Bearer <token> `
### GET /api/v1/organizations
#### response
```
{
"organizations": [
{
"id": <id>,
"name": <name>,
"created_at": <created_at>,
"updated_at": <updated_at>
},
]
}
```
### POST /api/v1/organizations
Only admin user
#### request
```
{
"organization": {
"name": <name>
}
}
```
#### response
```
{
"organization": {
"id": <id>,
"name": <name>,
"created_at": <created_at>,
"updated_at": <updated_at>
}
}
```
### GET /api/v1/contacts
#### request
```
{
"organization_id": 1
}
```
#### response
```
{
"contacts": [
{
"id": <id_from_firebase>,
"name": <name>,
"email": <email>,
"phone": <phone>,
"organization_id": <organization_id>
}
]
}
```
### POST /api/v1/contacts
#### request
```
{
"contact": {
"name": <name>,
"email": <email>,
"phone": <phone>,
"organization_id": <organization_id>
}
}
```
#### response
```
{
"contact": {
"id": <id_from_firebase>,
"name": <name>,
"email": <email>,
"phone": <phone>,
"organization_id": <organization_id>
}
}
```
### PUT /api/v1/contacts/:id
#### request
```
{
"contact": {
"name": <name>,
"email": <email>,
"phone": <phone>,
"organization_id": <organization_id>
}
}
```
#### response
```
{
"contact": {
"id": <id_from_firebase>,
"name": <name>,
"email": <email>,
"phone": <phone>,
"organization_id": <organization_id>
}
}
```
### DELETE /api/v1/contacts/:id
#### response
204 No Content
## Tests
The project uses Rspec for testing. To run it run in the root project
`bundle exec rspec`
It will run all the test suite.
The project tests the integration to Firebase without mocks or stubs.<file_sep>/spec/requests/api/v1/organizations_spec.rb
require 'rails_helper'
require 'support/request_spec_helper'
RSpec.describe "Api::V1::Organizations", type: :request do
include RequestSpecHelper
describe "GET /api/v1/organizations" do
let(:organizations) { create_list(:organization, 2) }
let(:user) { create(:user, organizations: organizations) }
let(:headers) { { 'Authorization' => token_generator(user) } }
it "lists all organizations" do
get api_v1_organizations_path, headers: headers
expect(json_body[:organizations].size).to eq(2)
end
end
describe "POST /api/v1/organizations" do
let(:user) { create(:user, :as_admin, organizations: [organization]) }
let(:organization) { create(:organization) }
let(:headers) { { 'Authorization' => token_generator(user) } }
context 'when params are valid' do
let(:organization_params) { attributes_for(:organization) }
it "returns status 201" do
post api_v1_organizations_path, headers: headers, params: { organization: organization_params }
expect(response).to have_http_status(201)
end
it "returns the created organization" do
post api_v1_organizations_path, headers: headers, params: { organization: organization_params }
expect(json_body[:organization][:name]).to eq(organization_params[:name])
end
end
context 'when params are invalid' do
let(:organization_params) { { name: nil } }
it "returns status 422" do
post api_v1_organizations_path, headers: headers, params: { organization: organization_params }
expect(response).to have_http_status(422)
end
it "returns errors" do
post api_v1_organizations_path, headers: headers, params: { organization: organization_params }
expect(json_body).to include(:errors)
end
end
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
root 'health_check#index'
namespace :api do
namespace :v1 do
resources :authentications, only: [:create]
resources :contacts, only: [:index, :create, :update, :destroy]
resources :organizations, only: [:index, :create]
resources :registrations, only: [:create]
end
end
end
<file_sep>/app/controllers/api/v1/authentications_controller.rb
class Api::V1::AuthenticationsController < ApplicationController
skip_before_action :authenticate_user!
def create
user = User.find_by(email: authentication_params[:email])
if user && user.authenticate(authentication_params[:password])
token = encode_token({ sub: user.id })
render json: { token: token }, status: :created
else
unauthorized_entity
end
end
private
def authentication_params
params.require(:authentication).permit(:email, :password)
end
end<file_sep>/db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
ActiveRecord::Base.transaction do
organization = Organization.create!(name: 'STRV')
admin = User.new(email: "<EMAIL>", password: '<PASSWORD>', role: :admin)
admin.organizations.push(organization)
admin.save!
user = User.new(email: "<EMAIL>", password: '<PASSWORD>')
user.organizations.push(organization)
user.save!
end
<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::API
include Authenticable
before_action :authenticate_user!
attr_reader :current_user
def current_user
@current_user ||= get_current_user
end
end
<file_sep>/spec/models/user_spec.rb
require 'rails_helper'
RSpec.describe User, type: :model do
let!(:user) { build(:user, :with_organization) }
it "is not valid without an email" do
user.email = nil
expect(user).to_not be_valid
end
it "is not valid without at least one organization" do
user.organizations = []
expect(user).to_not be_valid
end
it "is valid with valid attributes" do
expect(user).to be_valid
end
end
<file_sep>/app/models/organization.rb
class Organization < ApplicationRecord
has_and_belongs_to_many :users
validates :name, presence: true
def contacts
Contact.list_by_association_id(id)
end
end
<file_sep>/app/models/concerns/firestore.rb
require "google/cloud/firestore"
module Firestore
extend ActiveSupport::Concern
include ActiveModel::Validations
include Google::Cloud::Firestore
def self.included(base)
base.extend(ClassMethods)
end
def to_json
{
id: @id,
name: @name,
email: @email,
phone: @phone,
organization_id: @organization_id
}
end
def get
doc = @document.get
if doc.data
response_to_accessors
return_response
end
end
def save
if valid?
doc_ref = self.class.firestore.col(self.class.collection_name)
@document = doc_ref.add({ email: @email, name: @name, phone: @phone, organization_id: @organization_id.to_i })
response_to_accessors
return_response
end
end
def update(attributes = {})
attributes.each do |key, value|
instance_variable_set(:"@#{key}", value)
end
if self.class.belongs_to_klass
association_name = self.class.belongs_to_klass
attributes[:"#{association_name}_id"] = attributes[:"#{association_name}_id"].to_i
end
if valid?
@document.set(attributes.to_h, merge: true)
response_to_accessors
return_response
end
end
def delete
begin
@document.delete(exists: true)
rescue Google::Cloud::NotFoundError
nil
end
end
def initialize(attributes = {})
attributes.each do |key, value|
instance_variable_set(:"@#{key}", value)
end
end
module ClassMethods
def belongs_to(klass)
@belongs_to_klass ||= klass
end
def belongs_to_klass
@belongs_to_klass
end
def collection_name
if Rails.env.development?
@collection_name ||= 'dev'
else
@collection_name ||= self.name.pluralize.downcase
end
end
def list_by_association_id(id)
query = firestore.col(collection_name).where("#{@belongs_to_klass}_id".to_sym, :==, id)
resources = []
query.get do |resource|
resources.push({ id: resource.document_id }.merge(resource.data))
end
resources
end
def find_document(id)
document = firestore.doc("#{collection_name}/#{id}")
if document.get.data
new({id: document.document_id, document: document}.merge(document.get.data))
end
end
def firestore
@firestore ||= Google::Cloud::Firestore.new(project_id: ENV['PROJECT_ID'])
end
end
def response_to_accessors
document_data = @document.get.data
@id ||= @document.document_id
@name ||= document_data[:name]
@email ||= document_data[:email]
@phone ||= document_data[:phone]
@organization_id ||= document_data[:organization_id]
end
private :response_to_accessors
def return_response
response = {
id: @document.document_id,
}
response.merge(@document.get.data)
end
private :return_response
end<file_sep>/spec/support/request_spec_helper.rb
module RequestSpecHelper
def json_body
@json_body ||= JSON.parse(response.body, symbolize_names: true)
end
def token_generator(user)
JWT.encode({ sub: user.id }, Rails.application.credentials.read)
end
end<file_sep>/app/controllers/api/v1/registrations_controller.rb
class Api::V1::RegistrationsController < ApplicationController
skip_before_action :authenticate_user!
def create
user = User.new(registration_params[:user])
organizations = Organization.where(id: registration_params[:organizations_ids])
user.organizations << organizations
if user.save
token = encode_token({ sub: user.id })
render json: { user: { id: user.id, email: user.email } , token: token }, status: :created
else
render json: { errors: user.errors }, status: :unprocessable_entity
end
end
private
def registration_params
params.require(:registration).permit(user: [:email, :password], organizations_ids: [])
end
end
<file_sep>/spec/requests/api/v1/contacts_spec.rb
require 'rails_helper'
require 'support/request_spec_helper'
RSpec.describe "Contacts", type: :request do
include RequestSpecHelper
after(:each) do
contacts = Contact.list_by_association_id(organization.id)
contacts.each do |contact|
contact_document = Contact.find_document(contact[:id])
contact_document.delete
end
end
let(:user) { create(:user, organizations: [organization]) }
let(:organization) { create(:organization) }
let(:headers) { { 'Authorization' => token_generator(user) } }
before do
allow(Contact).to receive(:collection_name).and_return('testing')
end
describe "GET /api/v1/contacts" do
let!(:contacts) do
2.times do
contact = Contact.new(attributes_for(:contact, organization_id: organization.id))
contact.save
end
end
it "lists all contacts" do
get api_v1_contacts_path, headers: headers, params: { organization_id: organization.id }
expect(json_body[:contacts].size).to eq(2)
end
end
describe "POST /api/v1/contacts" do
context 'when params are valid' do
let(:contact_params) { attributes_for(:contact, organization_id: organization.id) }
it "returns status 201" do
post api_v1_contacts_path, headers: headers, params: { contact: contact_params }
expect(response).to have_http_status(201)
end
it "returns the created contact" do
post api_v1_contacts_path, headers: headers, params: { contact: contact_params }
expect(json_body[:contact][:name]).to eq(contact_params[:name])
end
end
context 'when params are invalid' do
let(:contact_params) { { name: nil, organization_id: organization.id } }
it "returns status 422" do
post api_v1_contacts_path, headers: headers, params: { contact: contact_params }
expect(response).to have_http_status(422)
end
it "returns errors" do
post api_v1_contacts_path, headers: headers, params: { contact: contact_params }
expect(json_body).to include(:errors)
end
end
end
describe "PUT /api/v1/contact/:id" do
let(:contact) do
contact = Contact.new(attributes_for(:contact, organization_id: organization.id))
contact.save
contact
end
context 'when params are valid' do
let(:contact_params) { attributes_for(:contact, organization_id: organization.id) }
it "returns status 200" do
put api_v1_contact_path(contact.id), headers: headers, params: { contact: contact_params }
expect(response).to have_http_status(200)
end
it "returns the updated contact" do
put api_v1_contact_path(contact.id), headers: headers, params: { contact: contact_params }
expect(json_body[:contact][:name]).to eq(contact_params[:name])
end
end
context 'when params are invalid' do
let(:contact_params) { { name: nil, organization_id: organization.id } }
it "returns status 422" do
put api_v1_contact_path(contact.id), headers: headers, params: { contact: contact_params }
expect(response).to have_http_status(422)
end
it "returns errors" do
put api_v1_contact_path(contact.id), headers: headers, params: { contact: contact_params }
expect(json_body).to include(:errors)
end
end
end
describe "DELETE /api/v1/contact/:id" do
context "when user belongs to organization" do
let(:contact) do
contact = Contact.new(attributes_for(:contact, organization_id: organization.id))
contact.save
contact
end
it "returns status 204" do
delete api_v1_contact_path(contact.id), headers: headers
expect(response).to have_http_status(204)
end
end
context "when user does not belong to organization" do
let(:organization2) { create(:organization) }
let(:contact) do
contact = Contact.new(attributes_for(:contact, organization_id: organization2.id))
contact.save
contact
end
after do
contact.delete
end
it "returns status 401" do
delete api_v1_contact_path(contact.id), headers: headers
expect(response).to have_http_status(401)
end
end
context "when contact does not exist" do
let(:contact) do
contact = Contact.new(attributes_for(:contact, organization_id: organization.id))
contact.save
contact
end
it "returns status 204" do
delete api_v1_contact_path(contact.id + 1.to_s), headers: headers
expect(response).to have_http_status(204)
end
end
end
end
|
a059deb06a0e18e91446be3c344fadb7d428ed5a
|
[
"Markdown",
"Ruby"
] | 24
|
Ruby
|
starwels/adress_book
|
2c1d2d892173087c4da2415dc82934aea7bd8fdf
|
5807dce87bb134aa9c75dd2175ffba356cd43984
|
refs/heads/master
|
<repo_name>wywdiablo/ChargedAnalysis<file_sep>/Workflow/python/configuration.py
from task import Task
import yaml
import os
import copy
import csv
import ROOT
from collections import defaultdict as dd
def treeread(tasks, config, channel, era, process, syst, shift, postFix = ""):
##Dic with process:filenames
processes = yaml.safe_load(open("{}/ChargedAnalysis/Analysis/data/process.yaml".format(os.environ["CHDIR"]), "r"))
##Skip Down for nominal case or and skip data if systematic
if (syst == "" and shift == "Down") or (process in ["SingleE", "SingleMu"] and syst != ""):
return
systName = "{}{}".format(syst, shift) if syst != "" else ""
skimDir = "{}/{}".format(os.environ["CHDIR"], config["skim-dir"].format_map(dd(str, {"C": channel, "E": era})))
## Scale systematics
scaleSysts = config["scale-systs"].get("all", []) + config["scale-systs"].get(channel, []) if process not in ["SingleE", "SingleMu"] and syst == "" else [""]
fileNames = []
##Data driven scale factors
scaleFactors = ""
if "scaleFactors" in config:
if "Single" not in process and "HPlus" not in process:
scaleFactors = "{}/{}".format(os.environ["CHDIR"], config["scaleFactors"].format_map(dd(str, {"C": channel, "E": era})))
with open(scaleFactors) as f:
reader = csv.reader(f, delimiter='\t')
toAppend = "+Misc"
for row in reader:
if process in row:
toAppend = "+" + process
break
scaleFactors += toAppend
##List of filenames for each process
for d in os.listdir(skimDir):
for processName in processes[process]:
if d.startswith(processName):
fileNames.append("{skim}/{file}/merged/{file}.root".format(skim=skimDir, file = d))
for idx, fileName in enumerate(fileNames):
outDir = config["dir"].format_map(dd(str, {"D": "Histograms", "C": channel, "E": era})) + "/{}/{}/unmerged/{}".format(process, systName, idx)
systDirs = [outDir.replace("unmerged/", "unmerged/{}{}/".format(scaleSyst, scaleShift)) for scaleSyst in scaleSysts if scaleSyst != "" for scaleShift in ["Up", "Down"]]
##Configuration for treeread Task
task = {
"name": "TreeRead_{}_{}_{}_{}_{}_{}".format(channel, era, process, systName, idx, postFix),
"executable": "hist",
"dir": outDir,
"run-mode": config["run-mode"],
"arguments": {
"filename": fileName,
"parameters": config["parameters"].get("all", []) + config["parameters"].get(channel, []),
"cuts": config["cuts"].get("all", []) + config["cuts"].get(channel, []),
"out-dir": outDir,
"out-file": "{}.root".format(process),
"channel": channel,
"clean-jet": config.get("clean-jet", {}).get(channel, ""),
"syst-dirs": systDirs,
"scale-systs": scaleSysts,
"scale-factors": scaleFactors,
"era": era
}
}
tasks.append(Task(task, "--"))
def mergeHists(tasks, config, channel, era, process, syst, shift, postFix = ""):
inputFiles, dependencies = [], []
##Skip Down for nominal case or and skip data if systematic
if (syst == "" and shift == "Down") or (process in ["SingleE", "SingleMu"] and syst != ""):
return
systName = "{}{}".format(syst, shift) if syst != "" else ""
outDir = config["dir"].format_map(dd(str, {"D": "Histograms", "C": channel, "E": era})) + "/{}/{}/merged".format(process, systName)
for t in tasks:
if "TreeRead_{}_{}_{}_{}".format(channel, era, process, systName) in t["name"] and postFix in t["name"]:
dependencies.append(t["name"])
inputFiles.append("{}/{}".format(t["arguments"]["out-dir"], t["arguments"]["out-file"]))
task = {
"name": "MergeHists_{}_{}_{}_{}_{}".format(channel, era, process, systName, postFix),
"executable": "merge",
"dir": outDir,
"dependencies": dependencies,
"process": process,
"arguments": {
"input-files": inputFiles,
"out-file": "{}/{}.root".format(outDir, process),
"exclude-objects": [],
}
}
tasks.append(Task(task, "--"))
def plotting(tasks, config, channel, era, processes, postFix = ""):
dependencies = []
bkgProcesses, sigProcesses = [], []
bkgFiles, sigFiles = [], []
data, dataFile = "", ""
processes.sort()
outDir = config["dir"].format_map(dd(str, {"D": "PDF", "C": channel, "E": era}))
webDir = ""
if "Results/Plot" in outDir:
webDir = outDir.replace("Results/Plot", "CernWebpage/Plots").replace("PDF", "")
for t in tasks:
for process in processes:
if "MergeHists_{}_{}_{}_".format(channel, era, process) in t["name"] and postFix in t["name"]:
dependencies.append(t["name"])
if "HPlus" in process:
sigProcesses.append(process)
sigFiles.append(t["arguments"]["out-file"])
elif "Single" in process:
data = process
dataFile = t["arguments"]["out-file"]
else:
bkgProcesses.append(process)
bkgFiles.append(t["arguments"]["out-file"])
task = {
"name": "Plot_{}_{}_{}".format(channel, era, postFix),
"executable": "plot",
"dir": outDir,
"dependencies": dependencies,
"arguments": {
"channel": channel,
"era": era,
"bkg-processes": bkgProcesses,
"bkg-files": bkgFiles,
"sig-processes": sigProcesses,
"sig-files": sigFiles,
"data": data,
"data-file": dataFile,
"out-dirs": [outDir, webDir] if webDir != "" else [outDir],
}
}
tasks.append(Task(task, "--"))
def treeappend(tasks, config, channel, era, syst, shift, postFix = ""):
##Skip Down for nominal case
if syst == "" and shift == "Down":
return
systName = "{}{}".format(syst, shift) if syst != "" else ""
skimDir = "{}/{}".format(os.environ["CHDIR"], config["skim-dir"].format_map(dd(str, {"C": channel, "E": era})))
outDir = config["dir"].format_map(dd(str, {"C": channel, "E": era}))
for fileName in os.listdir(skimDir):
if "Run2" in fileName and syst != "":
continue
##Configuration for treeread Task
task = {
"name": "Append_{}_{}_{}_{}_{}".format(channel, era, fileName, systName, postFix),
"dir": "{}/{}/{}".format(outDir, fileName, systName),
"executable": "treeappend",
"run-mode": config["run-mode"],
"arguments": {
"out-file": "{}/{}/merged/{}/{}.root".format(skimDir, fileName, systName, fileName),
"tree-name": channel,
"functions": config["functions"].get("all", []) + config["functions"].get(channel, []),
"era": era,
}
}
tasks.append(Task(task, "--"))
def sendToDCache(tasks, config, removePrefix, postFix = ""):
for idx, t in enumerate(copy.deepcopy(tasks)):
taskDir = t["dir"] + "/toDCache"
task = {
"name": "toDache_{}_{}".format(idx, postFix),
"dir": taskDir,
"executable": "sendToDCache",
"dependencies": [t["name"]],
"arguments": {
"input-file": t["arguments"]["out-file"],
"out-file": t["arguments"]["out-file"].split("/")[-1],
"dcache-path": "/pnfs/desy.de/cms/tier2/store/user/dbrunner/",
"relative-path": "/".join(t["arguments"]["out-file"].split("/")[:-1]).replace(removePrefix, ""),
}
}
tasks.append(Task(task, "--"))
def bkgEstimation(tasks, config, channel, era, mass, postFix = ""):
outDir = config["dir"].format_map(dd(str, {"D": "ScaleFactor", "C": channel, "E": era, "MHC": mass}))
data = config["data"][channel][0]
depTasks = [t for t in tasks if "MergeHists_{}_{}".format(channel, era) in t["name"] and mass in t["name"]]
task = {
"name": "Estimate_{}_{}_{}".format(channel, era, mass, postFix),
"dir": outDir,
"executable": "estimate",
"dependencies": [t["name"] for t in depTasks],
"arguments": {
"out-dir": outDir,
"processes": list(config["estimate-process"].keys()),
"parameter": config["parameter"],
}
}
for process in config["estimate-process"].keys():
fileNames = [t["arguments"]["out-file"] for t in depTasks if "{}-Region".format(process) in t["dir"]]
for p in reversed(config["estimate-process"]):
for idx, f in enumerate(fileNames):
if p in f.split("/")[-1]:
fileNames.pop(idx)
fileNames.insert(0, f)
elif data in f.split("/")[-1]:
dataFile = fileNames.pop(idx)
task["arguments"]["{}-bkg-files".format(process)] = fileNames
task["arguments"]["{}-data-file".format(process)] = dataFile
tasks.append(Task(task, "--"))
def treeslim(tasks, config, inChannel, outChannel, era, syst, shift, postFix = ""):
##Construct systname and skim dir
systName = "" if syst == "" else "{}{}".format(syst, shift)
tmpDir = "/nfs/dust/cms/group/susy-desy/david/Slim/{}/{}".format(outChannel, era)
skimDir = "{}/{}".format(os.environ["CHDIR"], config["skim-dir"].format_map(dd(str, {"E": era})))
##If nominal skip Down loop
if(syst == "" and shift == "Down"):
return
for d in os.listdir(skimDir):
##Skip if data and not nominal
if ("Electron" in d or "Muon" in d or "Gamma" in d) and syst != "":
continue
inFile = "{}/{}/merged/{}/{}.root".format(skimDir, d, systName, d)
if not os.path.exists(inFile):
raise FileNotFoundError("File not found: " + inFile)
f = ROOT.TFile.Open(inFile)
t = f.Get(inChannel)
nEvents = t .GetEntries()
eventRanges = [[i if i == 0 else i+1, i+config["n-events"] if i+config["n-events"] <= nEvents else nEvents] for i in range(0, nEvents, config["n-events"])]
##Configuration for treeread Task
for idx, (start, end) in enumerate(eventRanges):
outDir = "{}/{}/unmerged/{}/{}".format(tmpDir, d, systName, idx)
dir = "{}/{}/unmerged/{}/{}".format(config["dir"].format_map(dd(str, {"C": outChannel, "E": era})), d, systName, idx)
##Configuration for treeread Task
task = {
"name": "TreeSlim_{}_{}_{}_{}_{}_{}_{}".format(inChannel, outChannel, era, d, systName, idx, postFix),
"executable": "treeslim",
"run-mode": config["run-mode"],
"dir": dir,
"arguments": {
"input-file": inFile,
"input-channel": inChannel,
"out-channel": outChannel,
"cuts": config["cuts"].get(outChannel, []),
"out-file": "{}/{}.root".format(outDir, d),
"event-start": start,
"event-end": end,
}
}
tasks.append(Task(task, "--"))
def mergeFiles(tasks, config, inChannel, outChannel, era, syst, shift, postFix = ""):
##Construct systname and skim dir
systName = "" if syst == "" else "{}{}".format(syst, shift)
skimDir = "{}/{}".format(os.environ["CHDIR"], config["skim-dir"].format_map(dd(str, {"C": outChannel, "E": era})))
##If nominal skip Down loop
if(syst == "" and shift == "Down"):
return
for d in os.listdir(skimDir):
inputFiles, dependencies = [], []
if ("Electron" in d or "Muon" in d or "Gamma" in d) and syst != "":
continue
dir = "{}/{}/merged/{}".format(config["dir"].format_map(dd(str, {"D": "Histograms", "C": outChannel, "E": era})), d, systName)
outDir = "{}/{}/{}/merged/{}".format(os.environ["CHDIR"], config["out-dir"].format_map(dd(str, {"D": "Histograms", "C": outChannel, "E": era})), d, systName)
for t in tasks:
if "TreeSlim_{}_{}_{}_{}_{}".format(inChannel, outChannel, era, d, systName) in t["name"] and postFix in t["name"]:
dependencies.append(t["name"])
inputFiles.append(t["arguments"]["out-file"])
task = {
"name": "MergeHists_{}_{}_{}_{}_{}".format(outChannel, era, d, systName, postFix),
"executable": "merge",
"dir": dir,
"dependencies": dependencies,
"arguments": {
"input-files": inputFiles,
"out-file": "{}/{}.root".format(outDir, d),
"exclude-objects": config["exclude-merging"],
"delete-input": "",
}
}
tasks.append(Task(task, "--"))
def mergeSkim(tasks, config, channel, era, syst, shift, postFix = ""):
skimDir = "{}/{}".format(os.environ["CHDIR"], config["skim-dir"].format_map(dd(str, {"C": channel, "E": era})))
tmpDir = "/nfs/dust/cms/group/susy-desy/david/MergeSkim/{}".format(era)
##Loop over all directories in the skim dir
for d in os.listdir(skimDir):
mergeFiles = {}
##Skip if data and not nominal
if ("Electron" in d or "Muon" in d or "Gamma" in d) and syst != "":
continue
##Skip Down for nominal case
if syst == "" and shift == "Down":
continue
systName = "{}{}".format(syst, shift) if syst != "" else ""
##Open file with xrootd paths to output files
with open("{}/{}/outputFiles.txt".format(skimDir, d)) as fileList:
files, tmpTask = [], []
nFilesMerge = 30
nFiles = len(list(fileList))
fileList.seek(0)
for idx, f in enumerate(fileList):
fileName = ""
if syst != "":
if systName in f:
fileName = f.replace("\n", "")
else:
if "Up" not in f and "Down" not in f:
fileName = f.replace("\n", "")
if(fileName != ""):
files.append(fileName)
if (len(files) > nFilesMerge or idx == nFiles - 1) and len(files) != 0:
task = {
"name": "MergeSkim_{}_{}_{}_{}_{}_{}".format(channel, era, d, systName, len(tmpTask), postFix),
"dir": "{}/{}/tmp/{}/{}".format(config["dir"].format_map(dd(str, {"C": channel, "E": era})), d, systName, len(tmpTask)),
"executable": "merge",
"run-mode": config["run-mode"],
"arguments": {
"input-files": copy.deepcopy(files),
"out-file": "{}/{}/tmp/{}/{}/{}.root".format(tmpDir, d, systName, len(tmpTask), d),
"exclude-objects": ["Lumi", "xSec", "pileUp", "pileUpUp", "pileUpDown"],
}
}
tmpTask.append(Task(task, "--"))
files.clear()
task = {
"name": "MergeSkim_{}_{}_{}_{}_{}".format(channel, era, d, systName, postFix),
"dir": "{}/{}/merged/{}".format(config["dir"].format_map(dd(str, {"C": channel, "E": era})), d, systName),
"executable": "merge",
"run-mode": config["run-mode"],
"dependencies": [t["name"] for t in tmpTask],
"arguments": {
"input-files": [t["arguments"]["out-file"] for t in tmpTask],
"out-file": "{}/{}/merged/{}/{}.root".format(skimDir, d, systName, d),
"exclude-objects": ["Lumi", "xSec", "pileUp", "pileUpUp", "pileUpDown"],
"delete-input": "",
}
}
tasks.extend(tmpTask)
tasks.append(Task(task, "--"))
def DNN(tasks, config, channel, era, evType, postFix = ""):
processes = yaml.safe_load(open("{}/ChargedAnalysis/Analysis/data/process.yaml".format(os.environ["CHDIR"]), "r"))
skimDir = "{}/{}".format(os.environ["CHDIR"], config["skim-dir"].format_map(dd(str, {"C": channel, "E": era})))
outDir = config["dir"].format_map(dd(str, {"C": channel, "E": era, "T": evType}))
classes, signals = {}, []
for d in sorted(os.listdir(skimDir)):
for process in config["classes"] + config.get("Misc", []):
for processName in processes[process]:
if d.startswith(processName):
cls = process if process in config["classes"] else "Misc"
classes.setdefault(cls, []).append("{skim}/{file}/merged/{file}.root".format(skim=skimDir, file = d))
for process in [config["signal"].format_map(dd(str, {"MHC": mass})) for mass in config["masses"]]:
for processName in processes[process]:
if d.startswith(processName):
signals.append("{skim}/{file}/merged/{file}.root".format(skim=skimDir, file = d))
os.makedirs(outDir, exist_ok=True)
with open(outDir + "/parameter.txt", "w") as param:
for parameter in config["parameters"].get("all", []) + config["parameters"].get(channel, []):
param.write(parameter + "\n")
with open(outDir + "/classes.txt", "w") as param:
for cls in classes.keys():
param.write(cls + "\n")
with open(outDir + "/masses.txt", "w") as param:
for mass in config["masses"]:
param.write(str(mass) + "\n")
task = {
"name": "DNN_{}_{}_{}_{}".format(channel, era, evType, postFix),
"executable": "dnn",
"dir": outDir,
"run-mode": config["run-mode"],
"arguments": {
"out-path": outDir,
"channel": channel,
"cuts": config["cuts"].get("all", []) + config["cuts"].get(channel, []),
"parameters": config["parameters"].get("all", []) + config["parameters"].get(channel, []),
"sig-files": signals,
"masses": config["masses"],
"opt-param": config.get("hyper-opt", "").format_map(dd(str, {"C": channel, "E": era, "T": evType})),
"era": era,
"bkg-classes": list(classes.keys()),
}
}
if evType == "Even":
task["arguments"]["is-even"] = ""
for cls, files in classes.items():
task["arguments"]["{}-files".format(cls)] = files
tasks.append(Task(task, "--"))
def eventCount(tasks, config, channel, era, processes, postFix = ""):
outDir = config["dir"].format_map(dd(str, {"D": "EventCount", "C": channel, "E": era}))
files, dependencies = [], []
for process in processes:
for t in tasks:
if "MergeHists_{}_{}_{}_".format(channel, era, process) in t["name"] and postFix in t["name"]:
dependencies.append(t["name"])
files.append(t["arguments"]["out-file"])
task = {
"name": "EventCount_{}_{}_{}".format(channel, era, postFix),
"executable": "eventcount",
"dir": outDir,
"dependencies": dependencies,
"arguments": {
"processes": processes,
"files": files,
"out-dir": outDir,
}
}
tasks.append(Task(task, "--"))
def datacard(tasks, config, channel, era, processes, mHPlus, mH, postFix = ""):
dependencies = []
bkgFiles, sigFiles = [], []
dataFile = ""
outDir = config["dir"].format_map(dd(str, {"D": "DataCard", "C": channel, "E": era}))
for t in tasks:
if "MergeHists_{}_{}".format(channel, era) in t["name"] and "{}_{}".format(mHPlus, mH) in t["name"]:
dependencies.append(t["name"])
for proc in config["backgrounds"]:
if proc in t["name"]:
bkgFiles.append(t["arguments"]["out-file"])
break
if config["signal"] in t["name"]:
sigFiles.append(t["arguments"]["out-file"])
if config["data"].get("channel", "") != "" and config["data"].get("channel", "") in t["name"]:
dataFile = t["arguments"]["out-file"]
task = {
"name": "DataCard_{}_{}_{}_{}_{}".format(channel, era, mHPlus, mH, postFix),
"dir": outDir,
"executable": "writecard",
"dependencies": dependencies,
"arguments": {
"discriminant": config["discriminant"],
"bkg-processes": config["backgrounds"],
"sig-process": config["signal"],
"data": config["data"].get("channel", ""),
"bkg-files": bkgFiles,
"sig-files": sigFiles,
"data-file": dataFile,
"out-dir": outDir,
"channel": channel,
"systematics": ['""'] + config["shape-systs"].get("all", [])[1:] + config["shape-systs"].get(channel, []) + config["scale-systs"].get("all", [])[1:] + config["scale-systs"].get(channel, []),
}
}
tasks.append(Task(task, "--"))
def limits(tasks, config, channel, era, mHPlus, mH, postFix = ""):
outDir = config["dir"].format_map(dd(str, {"D": "Limit", "C": channel, "E": era}))
cardDir = config["dir"].format_map(dd(str, {"D": "DataCard", "C": channel, "E": era}))
task = {
"name": "Limit_{}_{}_{}_{}_{}".format(channel, era, mHPlus, mH, postFix),
"dir": outDir,
"executable": "combine",
"dependencies": [t["name"] for t in tasks if t["dir"] == cardDir],
"arguments": {
"datacard": "{}/datacard.txt".format(cardDir),
"saveWorkspace": "",
}
}
tasks.append(Task(task, "--", ["source $CHDIR/ChargedAnalysis/setenv.sh CMSSW", "cd {}".format(outDir)], ["mv higgs*.root limit.root"]))
def plotlimit(tasks, config, channel, era, postFix = ""):
outDir = config["dir"].format_map(dd(str, {"D": "LimitPDF", "C": channel, "E": era}))
webDir = ""
if "Results/Limit" in outDir:
webDir = outDir.replace("Results", "CernWebpage/Plots").replace("LimitPDF", "")
xSecs, limitFiles, dependencies = [], [], []
for mHPlus in config["charged-masses"]:
for mH in config["neutral-masses"]:
f = ROOT.TFile.Open("$CHDIR/Skim/Inclusive/2016/HPlusAndH_ToWHH_ToL4B_{MHC}_{MH}/merged/HPlusAndH_ToWHH_ToL4B_{MHC}_{MH}.root".format(MHC=mHPlus, MH=mH))
xSecs.append(f.Get("xSec").GetBinContent(1))
for t in tasks:
for mHPlus in config["charged-masses"]:
for mH in config["neutral-masses"]:
if "Limit_{}_{}_{}_{}".format(channel, era, mHPlus, mH) in t["name"]:
dependencies.append(t["name"])
limitFiles.append("{}/limit.root".format(t["dir"]))
task = {
"name": "PlotLimit_{}_{}_{}".format(channel, era, postFix),
"dir": outDir,
"executable": "plotlimit",
"dependencies": dependencies,
"arguments": {
"limit-files": limitFiles,
"charged-masses": config["charged-masses"],
"neutral-masses": config["neutral-masses"],
"channel": channel,
"era": era,
"x-secs": xSecs,
"out-dirs": [outDir, webDir] if webDir != "" else [outDir],
}
}
tasks.append(Task(task, "--"))
def mergeDataCards(tasks, config, channels, eras, mHPlus, mH, postFix = ""):
chanName, chanList = channels.popitem() if type(channels) == dict else (channels, [])
eraName, eraList = eras.popitem() if type(eras) == dict else (eras, [])
outDir = config["dir"].format_map(dd(str, {"D": "DataCard", "C": chanName, "E": eraName}))
dependencies = []
args = ""
for t in tasks:
for chan in chanList if len(chanList) != 0 else [chanName]:
for era in eraList if len(eraList) != 0 else [eraName]:
if "DataCard_{}_{}_{}_{}".format(chan, era, mHPlus, mH) in t["name"]:
dependencies.append(t["name"])
args += "{}={} ".format(chan + "_" + era, "{}/datacard.txt".format(t["dir"]))
task = {
"name": "MergeCards_{}_{}_{}_{}_{}".format(chanName, eraName, mHPlus, mH, postFix),
"dir": outDir,
"executable": "combineCards.py",
"dependencies": dependencies,
"arguments": {
args + " > {}/datacard.txt".format(outDir) : "",
}
}
tasks.append(Task(task, "", ["source $CHDIR/ChargedAnalysis/setenv.sh CMSSW"]))
<file_sep>/Utility/src/parser.cc
#include <ChargedAnalysis/Utility/include/parser.h>
#include <typeinfo>
Parser::Parser(int argc, char** argv){
int counter=1;
while(counter != argc){
std::size_t pos = std::string(argv[counter]).find("--");
//Variables for saving option and values
std::string option = std::string(argv[counter]).substr(2);
std::vector<std::string> values;
counter++;
//Break if last statement is bool option like --help
if(counter == argc){
options[option] = values;
break;
}
//Catch all values one option
while(std::string(argv[counter]).find("--") == std::string::npos){
values.push_back(std::string(argv[counter]));
counter++;
//Break if this is last option
if(counter == argc) break;
}
//Save option and values in a map
options[option] = values;
}
}
template <typename T>
T Parser::GetValue(const std::string& option, const T& defaultValue){
try{
return GetValue<T>(option);
}
catch(...){
return defaultValue;
}
}
template int Parser::GetValue(const std::string&, const int&);
template float Parser::GetValue(const std::string&, const float&);
template double Parser::GetValue(const std::string&, const double&);
template std::string Parser::GetValue(const std::string&, const std::string&);
template <typename T>
T Parser::GetValue(const std::string& option){
T value;
std::string type = typeid(value).name();
std::string data;
if(options.find(option) != options.end()){
if(options[option].size() == 0) data = type == "b" ? "1" : "";
else data = options[option][0];
}
else{
if(type == "b"){
data = "0";
}
else throw std::invalid_argument("No parser argument: " + option);
}
std::istringstream iss(data);
iss >> value;
return value;
}
template bool Parser::GetValue(const std::string&);
template int Parser::GetValue(const std::string&);
template float Parser::GetValue(const std::string&);
template double Parser::GetValue(const std::string&);
template std::string Parser::GetValue(const std::string&);
template <typename T>
std::vector<T> Parser::GetVector(const std::string& option){
std::vector<T> values;
if(options.find(option) == options.end()){
throw std::invalid_argument("No parser argument: " + option);
}
for(const std::string& data: options[option]){
T value;
std::istringstream iss(data);
iss >> value;
values.push_back(value);
}
return values;
}
template std::vector<int> Parser::GetVector(const std::string&);
template std::vector<float> Parser::GetVector(const std::string&);
template std::vector<double> Parser::GetVector(const std::string&);
template std::vector<std::string> Parser::GetVector(const std::string&);
template <typename T>
std::vector<T> Parser::GetVector(const std::string& option, const std::vector<T>& defaultValue){
try{
return GetVector<T>(option);
}
catch(...){
return defaultValue;
}
}
template std::vector<int> Parser::GetVector(const std::string&, const std::vector<int>&);
template std::vector<float> Parser::GetVector(const std::string&, const std::vector<float>&);
template std::vector<double> Parser::GetVector(const std::string&, const std::vector<double>&);
template std::vector<std::string> Parser::GetVector(const std::string&, const std::vector<std::string>&);
<file_sep>/Analysis/src/treefunction.cc
#include <ChargedAnalysis/Analysis/include/treefunction.h>
TreeFunction::TreeFunction(std::shared_ptr<TFile>& inputFile, const std::string& treeName, const int& era, const bool& useSyst) :
inputFile(inputFile),
inputTree(inputFile->Get<TTree>(treeName.c_str())),
era(era),
useSyst(useSyst) {
funcInfo = {
{"Pt", {&TreeFunction::Pt, "p_{T}(@) [GeV]"}},
{"Mt", {&TreeFunction::Mt, "m_{T}(@) [GeV]"}},
{"Phi", {&TreeFunction::Phi, "#phi(@) [rad]"}},
{"Eta", {&TreeFunction::Eta, "#eta(@) [rad]"}},
{"Mass", {&TreeFunction::Mass, "m(@) [GeV]"}},
{"dR", {&TreeFunction::DeltaR, "#Delta R(@, @) [rad]"}},
{"dPhi", {&TreeFunction::DeltaPhi, "#Delta #phi(@, @) [rad]"}},
{"Tau", {&TreeFunction::JetSubtiness, "#tau_{@}(@)"}},
{"HT", {&TreeFunction::HT, "H_{T} [GeV]"}},
{"N", {&TreeFunction::NParticle, "N(@)"}},
{"EvNr", {&TreeFunction::EventNumber, "Event number"}},
{"HTag", {&TreeFunction::HTag, "Higgs score(@)"}},
{"DAK8", {&TreeFunction::DeepAK, "DeepAK8 score(@)"}},
{"DAK8C", {&TreeFunction::DeepAKClass, "DeepAK8 class"}},
{"DNN", {&TreeFunction::DNN, "DNN score @ (m_{H^{#pm}} = @ GeV)"}},
{"DNNC", {&TreeFunction::DNNClass, "DNN class (m_{H^{#pm}} = @ GeV)"}},
{"Count", {&TreeFunction::Count, "Count"}},
};
partInfo = {
{"", {VACUUM, "", "", ""}},
{"e", {ELECTRON, "Electron", "Electron", "e_{@}"}},
{"mu", {MUON, "Muon", "Muon", "#mu_{@}"}},
{"j", {JET, "Jet", "Jet", "j_{@}"}},
{"met", {MET, "MET", "MET", "#vec{p}_{T}^{miss}"}},
{"sj", {SUBJET, "SubJet", "SubJet", "j^{sub}_{@}"}},
{"bj", {BJET, "Jet", "BJet", "b_{@}"}},
{"bsj", {BSUBJET, "SubJet", "BSubJet", "b^{sub}_{@}"}},
{"fj", {FATJET, "FatJet", "FatJet", "j_{@}^{AK8}"}},
{"h1", {HIGGS, "H1", "H1", "h_{1}"}},
{"h2", {HIGGS, "H2", "H2", "h_{2}"}},
{"hc", {CHAREDHIGGS, "HPlus", "HPlus", "H^{#pm}"}},
{"W", {W, "W", "W", "W^{#pm}"}},
{"trk", {TRACK, "IsoTrack", "IsoTrack", "Iso. track @"}},
};
wpInfo = {
{"", {NONE, ""}},
{"l", {LOOSE, "loose"}},
{"m", {MEDIUM, "medium"}},
{"t", {TIGHT, "tight"}},
};
comparisons = {
{"bigger", {BIGGER, ">"}},
{"smaller", {SMALLER, "<"}},
{"equal", {EQUAL, "=="}},
{"divisible", {DIVISIBLE, "%"}},
{"notdivisible", {NOTDIVISIBLE, "%!"}},
};
systInfo = {
{"BTag", BTAG},
{"ElectronID", ELEID},
{"ElectronReco", ELERECO},
{"MuonIso", MUISO},
{"MuonID", MUID},
{"MuonTriggerEff", MUTRIGG},
};
}
TreeFunction::~TreeFunction(){}
const bool TreeFunction::hasYAxis(){return yFunction != nullptr;}
void TreeFunction::SetYAxis(){
if(this == nullptr) yFunction = std::make_shared<TreeFunction>(inputFile, inputTree->GetName());
}
template<Axis A>
void TreeFunction::SetP1(const std::string& part, const int& idx, const std::string& wp, const int& genMother){
if(A == Axis::Y){
yFunction->SetP1<Axis::X>(part, idx, wp, genMother);
return;
}
part1 = std::get<0>(VUtil::At(partInfo, part));
wp1 = std::get<0>(VUtil::At(wpInfo, wp));
idx1 = idx-1;
genMother1 = genMother;
partLabel1 = std::get<3>(VUtil::At(partInfo, part));
if(!StrUtil::Find(partLabel1, "@").empty())
partLabel1 = StrUtil::Replace(partLabel1, "@", idx1 == -1. ? "" : std::to_string(idx1+1));
partName1 = part;
wpName1 = wp;
}
template void TreeFunction::SetP1<Axis::X>(const std::string&, const int&, const std::string&, const int&);
template void TreeFunction::SetP1<Axis::Y>(const std::string&, const int&, const std::string&, const int&);
template<Axis A>
void TreeFunction::SetP2(const std::string& part, const int& idx, const std::string& wp, const int& genMother){
if(A == Axis::Y){
yFunction->SetP2<Axis::X>(part, idx, wp);
return;
}
part2 = std::get<0>(VUtil::At(partInfo, part));
wp2 = std::get<0>(VUtil::At(wpInfo, wp));
idx2 = idx-1;
genMother2 = genMother;
partLabel2 = std::get<3>(VUtil::At(partInfo, part));
if(!StrUtil::Find(partLabel2, "@").empty())
partLabel2 = StrUtil::Replace(partLabel2, "@", idx1 == -1. ? "" : std::to_string(idx2+1));
partName2 = part;
wpName2 = wp;
}
template void TreeFunction::SetP2<Axis::X>(const std::string&, const int&, const std::string&, const int&);
template void TreeFunction::SetP2<Axis::Y>(const std::string&, const int&, const std::string&, const int&);
template<Axis A>
void TreeFunction::SetCleanJet(const std::string& part, const std::string& wp){
if(A == Axis::Y){
yFunction->SetCleanJet<Axis::X>(part, wp);
return;
}
if(part1 == JET or part1 == BJET){
cleanPhi = RUtil::Get<TLeaf>(inputTree, StrUtil::Replace("@_Phi", "@", std::get<1>(VUtil::At(partInfo, part))));
cleanEta = RUtil::Get<TLeaf>(inputTree, StrUtil::Replace("@_Eta", "@", std::get<1>(VUtil::At(partInfo, part))));
ID = RUtil::Get<TLeaf>(inputTree, StrUtil::Replace("@_ID", "@", std::get<1>(VUtil::At(partInfo, part))));
Isolation = RUtil::Get<TLeaf>(inputTree, StrUtil::Replace(part == "e" ? "@_Isolation" : "@_isoID", "@", std::get<1>(VUtil::At(partInfo, part))));
jetPhi = RUtil::Get<TLeaf>(inputTree, "Jet_Phi");
jetEta = RUtil::Get<TLeaf>(inputTree, "Jet_Eta");
cleanPart = std::get<0>(VUtil::At(partInfo, part));
cleanedWP = std::get<0>(VUtil::At(wpInfo, wp));
}
}
template void TreeFunction::SetCleanJet<Axis::X>(const std::string&, const std::string&);
template void TreeFunction::SetCleanJet<Axis::Y>(const std::string&, const std::string&);
void TreeFunction::SetCut(const std::string& comp, const float& compValue){
this->comp = std::get<0>(VUtil::At(comparisons, comp));
this->compValue = compValue;
std::string compV = std::to_string(compValue);
compV.erase(compV.find_last_not_of('0') + 1, std::string::npos);
compV.erase(compV.find_last_not_of('.') + 1, std::string::npos);
cutLabel = axisLabel + " " + std::get<1>(VUtil::At(comparisons, comp)) + " " + compV;
}
void TreeFunction::SetSystematics(const std::vector<std::string>& systNames){
if(systNames.size() == 1) return;
for(const std::string syst : VUtil::Slice(systNames, 1, systNames.size())){
systematics.push_back(VUtil::At(systInfo, syst));
}
systWeights = std::vector<float>(systematics.size()*2, 1.);
}
template<Axis A>
void TreeFunction::SetFunction(const std::string& funcName, const std::string& inputValue){
if(A == Axis::Y){
yFunction->SetFunction<Axis::X>(funcName, inputValue);
return;
}
if(genMother1 != -1.){
particleID = RUtil::Get<TLeaf>(inputTree, "GenParticle_ParticleID");
motherID = RUtil::Get<TLeaf>(inputTree, "GenParticle_MotherID");
}
this->funcPtr = std::get<0>(VUtil::At(funcInfo, funcName));
this->inputValue = inputValue;
std::string part1Prefix = genMother1 == -1. ? std::get<1>(partInfo[partName1]) : "GenParticle";
std::string part2Prefix = genMother1 == -1. ? std::get<1>(partInfo[partName2]) : "GenParticle";
if(funcName == "Pt"){
const std::string branchName = StrUtil::Replace("@_Pt", "@", part1Prefix);
TLeaf* leaf = RUtil::Get<TLeaf>(inputTree, branchName);
quantities.push_back(std::move(leaf));
}
else if(funcName == "Mt"){
const std::string branchName = StrUtil::Replace("@_Mt", "@", part1Prefix);
TLeaf* leaf = RUtil::Get<TLeaf>(inputTree, branchName);
quantities.push_back(std::move(leaf));
}
else if(funcName == "Eta"){
const std::string branchName = StrUtil::Replace("@_Eta", "@", part1Prefix);
TLeaf* leaf = RUtil::Get<TLeaf>(inputTree, branchName);
quantities.push_back(std::move(leaf));
}
else if(funcName == "Phi"){
const std::string branchName = StrUtil::Replace("@_Phi", "@", part1Prefix);
TLeaf* leaf = RUtil::Get<TLeaf>(inputTree, branchName);
quantities.push_back(std::move(leaf));
}
else if(funcName == "Mass"){
const std::string branchName = StrUtil::Replace("@_Mass", "@", part1Prefix);
TLeaf* leaf = RUtil::Get<TLeaf>(inputTree, branchName);
quantities.push_back(std::move(leaf));
}
else if(funcName == "dPhi"){
for(const std::string part : {part1Prefix, part2Prefix}){
TLeaf* phi = RUtil::Get<TLeaf>(inputTree, StrUtil::Replace("@_Phi", "@", part));
quantities.push_back(std::move(phi));
}
}
else if(funcName == "dR"){
for(const std::string part : {part1Prefix, part2Prefix}){
TLeaf* phi = RUtil::Get<TLeaf>(inputTree, StrUtil::Replace("@_Phi", "@", part));
TLeaf* eta = RUtil::Get<TLeaf>(inputTree, StrUtil::Replace("@_Eta", "@", part));
quantities.push_back(std::move(phi));
quantities.push_back(std::move(eta));
}
}
else if(funcName == "HT"){
for(const std::string& jetName : {"Jet", "FatJet"}){
const std::string branchName = StrUtil::Replace("@_Pt", "@", jetName);
TLeaf* leaf = RUtil::Get<TLeaf>(inputTree, branchName);
quantities.push_back(std::move(leaf));
}
}
else if(funcName == "Tau"){
const std::string branchName = StrUtil::Replace("@_Njettiness" + inputValue, "@", part1Prefix);
TLeaf* leaf = RUtil::Get<TLeaf>(inputTree, branchName);
quantities.push_back(std::move(leaf));
}
else if(funcName == "HTag"){
const std::string branchName = "ML_HTagFJ" + std::to_string(idx1+1);
TLeaf* leaf = RUtil::Get<TLeaf>(inputTree, branchName);
quantities.push_back(std::move(leaf));
}
else if(funcName == "DNN"){
const std::string branchName = StrUtil::Replace("DNN_@", "@", inputValue);
TLeaf* leaf = RUtil::Get<TLeaf>(inputTree, branchName);
quantities.push_back(std::move(leaf));
}
else if(funcName == "DNNC"){
for(const std::string p : {"Misc", "TT2L", "TT1L", "HPlus"}){
const std::string branchName = StrUtil::Replace("DNN_@@", "@", p, inputValue);
TLeaf* leaf = RUtil::Get<TLeaf>(inputTree, branchName);
quantities.push_back(std::move(leaf));
}
}
else if(funcName == "DAK8"){
std::string branchName = StrUtil::Replace("@_DeepAK8@", "@", part1Prefix, inputValue);
TLeaf* leaf = RUtil::Get<TLeaf>(inputTree, branchName);
quantities.push_back(std::move(leaf));
}
else if(funcName == "DAK8C"){
for(const std::string p : {"Higgs", "Top", "W", "QCD"}){
std::string branchName = StrUtil::Replace("@_DeepAK8@", "@", part1Prefix, p);
TLeaf* leaf = RUtil::Get<TLeaf>(inputTree, branchName);
quantities.push_back(std::move(leaf));
}
}
else if(funcName == "EvNr"){
TLeaf* leaf = RUtil::Get<TLeaf>(inputTree, "Misc_eventNumber");
quantities.push_back(std::move(leaf));
}
else if(funcName == "N"){
if(part1 == BJET or part1 == BSUBJET){
for(const std::string& param : {"Pt", "Eta"}){
const std::string branchName = std::string(part1 == BJET ? "Jet" : "SubJet") + "_" + param;
TLeaf* leaf = RUtil::Get<TLeaf>(inputTree, branchName);
quantities.push_back(std::move(leaf));
}
}
}
const std::string branchName1 = StrUtil::Replace("@_Size", "@", part1Prefix);
nPart1 = inputTree->GetLeaf(branchName1.c_str());
const std::string branchName2 = StrUtil::Replace("@_Size", "@", part2Prefix);
nPart2 = inputTree->GetLeaf(branchName2.c_str());
if(wp1 != NONE){
std::string wpname = std::get<1>(wpInfo[wpName1]);
switch(part1){
case ELECTRON:
ID = RUtil::Get<TLeaf>(inputTree, "Electron_ID");
Isolation = RUtil::Get<TLeaf>(inputTree, "Electron_Isolation");
scaleFactors[ELERECO] = RUtil::Get<TLeaf>(inputTree, "Electron_recoSF");
if(useSyst) scaleFactorsUp[ELERECO] = RUtil::Get<TLeaf>(inputTree, "Electron_recoSFUp");
if(useSyst) scaleFactorsDown[ELERECO] = RUtil::Get<TLeaf>(inputTree, "Electron_recoSFDown");
scaleFactors[ELEID] = RUtil::Get<TLeaf>(inputTree, StrUtil::Replace("Electron_@SF", "@", wpname));
if(useSyst) scaleFactorsUp[ELEID] = RUtil::Get<TLeaf>(inputTree, StrUtil::Replace("Electron_@SFUp", "@", wpname));
if(useSyst) scaleFactorsDown[ELEID] = RUtil::Get<TLeaf>(inputTree, StrUtil::Replace("Electron_@SFDown", "@", wpname));
break;
case MUON:
ID = RUtil::Get<TLeaf>(inputTree, "Muon_ID");
Isolation = RUtil::Get<TLeaf>(inputTree, "Muon_isoID");
scaleFactors[MUTRIGG] = RUtil::Get<TLeaf>(inputTree, "Muon_triggerSF");
if(useSyst) scaleFactorsUp[MUTRIGG] = RUtil::Get<TLeaf>(inputTree, "Muon_triggerSFUp");
if(useSyst) scaleFactorsDown[MUTRIGG] = RUtil::Get<TLeaf>(inputTree, "Muon_triggerSFDown");
scaleFactors[MUID] = RUtil::Get<TLeaf>(inputTree, StrUtil::Replace("Muon_@SF", "@", wpname));
if(useSyst) scaleFactorsUp[MUID] = RUtil::Get<TLeaf>(inputTree, StrUtil::Replace("Muon_@SFUp", "@", wpname));
if(useSyst) scaleFactorsDown[MUID] = RUtil::Get<TLeaf>(inputTree, StrUtil::Replace("Muon_@SFDown", "@", wpname));
wpname[0] = std::toupper(wpname[0]);
scaleFactors[MUISO] = RUtil::Get<TLeaf>(inputTree, StrUtil::Replace("Muon_tightIso@SF", "@", wpname));
if(useSyst) scaleFactorsUp[MUISO] = RUtil::Get<TLeaf>(inputTree, StrUtil::Replace("Muon_tightIso@SFUp", "@", wpname));
if(useSyst) scaleFactorsDown[MUISO] = RUtil::Get<TLeaf>(inputTree, StrUtil::Replace("Muon_tightIso@SFDown", "@", wpname));
break;
case BJET:
TrueFlavour = RUtil::Get<TLeaf>(inputTree, "Jet_TrueFlavour");
BScore = RUtil::Get<TLeaf>(inputTree, "Jet_CSVScore");
scaleFactors[BTAG] = RUtil::Get<TLeaf>(inputTree, StrUtil::Replace("Jet_@CSVbTagSF", "@", wpname));
if(useSyst) scaleFactorsUp[BTAG] = RUtil::Get<TLeaf>(inputTree, StrUtil::Replace("Jet_@CSVbTagSFUp", "@", wpname));
if(useSyst) scaleFactorsDown[BTAG] = RUtil::Get<TLeaf>(inputTree, StrUtil::Replace("Jet_@CSVbTagSFDown", "@", wpname));
break;
case BSUBJET:
TrueFlavour = RUtil::Get<TLeaf>(inputTree, "SubJet_TrueFlavour");
BScore = RUtil::Get<TLeaf>(inputTree, "SubJet_CSVScore");
scaleFactors[SUBBTAG] = RUtil::Get<TLeaf>(inputTree, StrUtil::Replace("SubJet_@CSVbTagSF", "@", wpname));
if(useSyst) scaleFactorsUp[SUBBTAG] = RUtil::Get<TLeaf>(inputTree, StrUtil::Replace("SubJet_@CSVbTagSFUp", "@", wpname));
if(useSyst) scaleFactorsDown[SUBBTAG] = RUtil::Get<TLeaf>(inputTree, StrUtil::Replace("SubJet_@CSVbTagSFDown", "@", wpname));
break;
default: break;
}
}
if(part1 == BJET or part1 == BSUBJET){
std::string wpname = std::get<1>(wpInfo[wpName1]);
wpname[0] = std::toupper(wpname[0]);
if(inputFile->Get("nTrueB") != nullptr){
effB = (TH2F*)RUtil::Get<TH2F>(inputFile.get(), StrUtil::Replace("n@BCSVbTag", "@", wpname))->Clone();
effB->Divide(RUtil::Get<TH2F>(inputFile.get(), "nTrueB"));
effC = (TH2F*)RUtil::Get<TH2F>(inputFile.get(), StrUtil::Replace("n@CCSVbTag", "@", wpname))->Clone();
effC->Divide(RUtil::Get<TH2F>(inputFile.get(), "nTrueC"));
effLight = (TH2F*)RUtil::Get<TH2F>(inputFile.get(), StrUtil::Replace("n@LightCSVbTag", "@", wpname))->Clone();
effLight->Divide(RUtil::Get<TH2F>(inputFile.get(), "nTrueLight"));
}
}
//Set Name of functions/axis label
name = funcName + (inputValue != "" ? StrUtil::Replace("_@", "@", inputValue) : "") + (partName1 != "" ? "_" + std::get<2>(VUtil::At(partInfo, partName1)) : "") + (idx1 != -1 ? "_" + std::to_string(idx1+1) : "") + (wp1 != NONE ? "_" + std::get<1>(VUtil::At(wpInfo, wpName1)) : "") + (partName2 != "" ? "_" + std::get<2>(VUtil::At(partInfo, partName2)) : "") + (idx2 != -1 ? "_" + std::to_string(idx2+1) : "") + (wp2 != NONE ? "_" + std::get<1>(VUtil::At(wpInfo, wpName2)) : "");
axisLabel = (genMother1 != -1. ? "Gen " : "") + std::get<1>(VUtil::At(funcInfo, funcName));
if(inputValue != ""){
if(!StrUtil::Find(axisLabel, "@").empty()){
if(funcName == "DNN"){
axisLabel = StrUtil::Replace(axisLabel, "@", inputValue.substr(0, inputValue.size() - 3), inputValue.substr(inputValue.size() - 3, inputValue.size()));
}
else axisLabel = StrUtil::Replace(axisLabel, "@", inputValue);
}
}
for(const std::string partLabel : {partLabel1, partLabel2}){
if(!StrUtil::Find(axisLabel, "@").empty()){
axisLabel = StrUtil::Replace(axisLabel, "@", partLabel);
}
}
}
template void TreeFunction::SetFunction<Axis::X>(const std::string&, const std::string&);
template void TreeFunction::SetFunction<Axis::Y>(const std::string&, const std::string&);
void TreeFunction::SetEntry(const int& entry){
TreeFunction::entry = entry;
}
template<Axis A>
const float TreeFunction::Get(){
if(A == Axis::Y) return yFunction->Get<Axis::X>();
realIdx1 = whichIndex(nPart1, part1, idx1, wp1, genMother1);
if(part2 != VACUUM) realIdx2 = whichIndex(nPart2, part2, idx2, wp2, genMother2);
try{
(this->*funcPtr)();
return value;
}
catch(const std::exception& e){
return -999.;
}
}
template const float TreeFunction::Get<Axis::X>();
template const float TreeFunction::Get<Axis::Y>();
const float TreeFunction::GetWeight(const Systematic syst, const Shift& shift){
weight = 1.;
if(funcPtr == &TreeFunction::NParticle){
float wData = 1., wMC = 1.;
if((part1 == BJET or part1 == BSUBJET) and effB != nullptr){
TLeaf* scaleFactor;
if(shift != NON and (syst == BTAG or syst == SUBBTAG)){
if(shift == UP) scaleFactor = scaleFactorsUp[part1 == BJET ? BTAG : SUBBTAG];
else scaleFactor = scaleFactorsDown[part1 == BJET ? BTAG : SUBBTAG];
}
else scaleFactor = scaleFactors[part1 == BJET ? BTAG : SUBBTAG];
const std::vector<float>& sf = RUtil::GetVecEntry<float>(scaleFactor, entry);
const std::vector<char>& trueFlav = RUtil::GetVecEntry<char>(TrueFlavour, entry);
const std::vector<float>& jetPt = RUtil::GetVecEntry<float>(quantities[0], entry);
const std::vector<float>& jetEta = RUtil::GetVecEntry<float>(quantities[1], entry);
for(unsigned int i = 0; i < sf.size(); i++){
float eff;
if(std::abs(trueFlav.at(i)) == 5) eff = effB->GetBinContent(effB->FindBin(VUtil::At(jetPt, i), VUtil::At(jetEta, i)));
else if(std::abs(trueFlav.at(i)) == 4) eff = effC->GetBinContent(effC->FindBin(VUtil::At(jetPt, i), VUtil::At(jetEta, i)));
else eff = effLight->GetBinContent(effLight->FindBin(VUtil::At(jetPt, i), VUtil::At(jetEta, i)));
if(eff == 0) continue;
if(whichWP(part1, i) >= wp1){
wData *= VUtil::At(sf, i) * eff;
wMC *= eff;
}
else{
wData *= 1 - VUtil::At(sf, i)*eff;
wMC *= (1 - eff);
}
}
weight = wData/wMC;
}
else{
for(const Systematic& sys: VUtil::MapKeys(scaleFactors)){
TLeaf* scaleFactor;
if(shift != NON and sys == syst){
if(shift == UP) scaleFactor = scaleFactorsUp[sys];
else scaleFactor = scaleFactorsDown[sys];
}
else scaleFactor = scaleFactors[sys];
const std::vector<float>& sf = RUtil::GetVecEntry<float>(scaleFactor, entry);
for(int i = 0; i < sf.size(); i++){
if(whichWP(part1, i) >= wp1){
weight *= Utils::CheckZero(VUtil::At(sf, i));
}
}
}
}
}
return weight;
}
const std::vector<float> TreeFunction::GetSystWeight(){
for(int i = 0; i < systematics.size(); i++){
VUtil::At(systWeights, MUtil::RowMajIdx({systematics.size(), 2}, {i, 0})) = this->GetWeight(systematics[i], UP);
VUtil::At(systWeights, MUtil::RowMajIdx({systematics.size(), 2}, {i, 1})) = this->GetWeight(systematics[i], DOWN);
}
return systWeights;
}
const bool TreeFunction::GetPassed(){
switch(comp){
case BIGGER:
return this->Get<Axis::X>() > compValue;
case SMALLER:
return this->Get<Axis::X>() < compValue;
case EQUAL:
return this->Get<Axis::X>() == compValue;
case DIVISIBLE:
return int(this->Get<Axis::X>()) % int(compValue) == 0;
case NOTDIVISIBLE:
return int(this->Get<Axis::X>()) % int(compValue) != 0;
}
}
template<Axis A>
const std::string TreeFunction::GetAxisLabel(){
if(A == Axis::Y) return yFunction->GetAxisLabel<Axis::X>();
return axisLabel;
}
template const std::string TreeFunction::GetAxisLabel<Axis::X>();
template const std::string TreeFunction::GetAxisLabel<Axis::Y>();
const std::string TreeFunction::GetCutLabel(){
return cutLabel;
}
template<Axis A>
const std::string TreeFunction::GetName(){
if(A == Axis::Y) return yFunction->GetName<Axis::X>();
return name;
}
int TreeFunction::whichIndex(TLeaf* nPart, const Particle& part, const int& idx, const WP& wp, const int& genMother){
if((nPart == nullptr or idx == -1) and genMother == -1.) return -1.;
int realIdx = 0, counter = idx;
if(genMother != -1.){
const std::vector<char>& partID = RUtil::GetVecEntry<char>(particleID, entry);
const std::vector<char>& mothID = RUtil::GetVecEntry<char>(motherID, entry);
for(int i = 0; i < partID.size(); i++){
if(VUtil::At(partID, i) == part and VUtil::At(mothID, i) == genMother){
counter--;
++realIdx;
if(counter < 0) return realIdx;
}
}
}
else{
const char& n = RUtil::GetEntry<char>(nPart1, entry);
if(idx >= n) return -1.;
for(int i = 0; i < n; ++i){
if(whichWP(part, i) >= wp) --counter;
if(counter < 0) return realIdx;
++realIdx;
}
return realIdx;
}
}
TreeFunction::WP TreeFunction::whichWP(const Particle& part, const int& idx){
std::vector<char> id, isoID, trkid, trkcharge, mcharge;
std::vector<float> iso, score, pt,trkpt, trketa, trkphi, trkiso, mphi, meta;
bool passed = true;
switch(part){
case ELECTRON:
id = RUtil::GetVecEntry<char>(RUtil::Get<TLeaf>(inputTree, "Electron_ID"), entry);
iso = RUtil::GetVecEntry<float>(RUtil::Get<TLeaf>(inputTree, "Electron_Isolation"), entry);
if(VUtil::At(id, idx) > MEDIUM && VUtil::At(iso, idx) < 0.15) return TIGHT;
if(VUtil::At(id, idx) > LOOSE && VUtil::At(iso, idx) < 0.20) return MEDIUM;
if(VUtil::At(id, idx) > NONE && VUtil::At(iso, idx) < 0.25) return LOOSE;
return NONE;
case MUON:
id = RUtil::GetVecEntry<char>(RUtil::Get<TLeaf>(inputTree, "Muon_ID"), entry);
isoID = RUtil::GetVecEntry<char>(RUtil::Get<TLeaf>(inputTree, "Muon_isoID"), entry);
if(VUtil::At(id, idx) > MEDIUM && VUtil::At(isoID, idx) > MEDIUM) return TIGHT;
if(VUtil::At(id, idx) > LOOSE && VUtil::At(isoID, idx) > MEDIUM) return MEDIUM;
if(VUtil::At(id, idx) > NONE && VUtil::At(isoID, idx) > MEDIUM) return LOOSE;
return NONE;
case JET:
if(cleanPart != VACUUM){
if(isCleanJet(idx)) return NONE;
else return NOTCLEAN;
}
return NONE;
case BJET:
if(cleanPart != VACUUM){
if(!isCleanJet(idx)) return NOTCLEAN;
}
case BSUBJET:
score = RUtil::GetVecEntry<float>(RUtil::Get<TLeaf>(inputTree, "Jet_CSVScore"), entry);
if(VUtil::At(score, idx) > tightBCut[era]) return TIGHT;
if(VUtil::At(score, idx) > mediumBCut[era]) return MEDIUM;
if(VUtil::At(score, idx) > looseBCut[era]) return LOOSE;
case TRACK:
trkid = RUtil::GetVecEntry<char>(RUtil::Get<TLeaf>(inputTree, "IsoTrack_PDG"), entry);
trkpt = RUtil::GetVecEntry<float>(RUtil::Get<TLeaf>(inputTree, "IsoTrack_Pt"), entry);
trkiso = RUtil::GetVecEntry<float>(RUtil::Get<TLeaf>(inputTree, "IsoTrack_Isolation"), entry);
trkphi = RUtil::GetVecEntry<float>(RUtil::Get<TLeaf>(inputTree, "IsoTrack_Phi"), entry);
trketa = RUtil::GetVecEntry<float>(RUtil::Get<TLeaf>(inputTree, "IsoTrack_Eta"), entry);
trkcharge = RUtil::GetVecEntry<char>(RUtil::Get<TLeaf>(inputTree, "IsoTrack_Charge"), entry);
mphi = RUtil::GetVecEntry<float>(RUtil::Get<TLeaf>(inputTree, "Muon_Phi"), entry);
meta = RUtil::GetVecEntry<float>(RUtil::Get<TLeaf>(inputTree, "Muon_Eta"), entry);
mcharge = RUtil::GetVecEntry<char>(RUtil::Get<TLeaf>(inputTree, "Muon_Charge"), entry);
try{
if(trkpt.empty()) return NOTCLEAN;
for(unsigned int i = 0; i < mphi.size(); ++i){
if(whichWP(MUON, i) < MEDIUM) continue;
float dR = std::sqrt(std::pow(VUtil::At(mphi, i) - VUtil::At(trkphi, idx), 2) + std::pow(VUtil::At(meta, i) - VUtil::At(trketa, idx), 2));
int diCharge = VUtil::At(mcharge, i) * VUtil::At(trkcharge, idx);
if(dR < 0.1 or diCharge > 0) passed = false;
}
if(VUtil::At(trkiso, idx) < 0.2 and VUtil::At(trkpt, idx) > 20 && (abs(VUtil::At(trkid, idx)) == 11 or abs(VUtil::At(trkid, idx)) == 13) and passed) return NONE;
return NOTCLEAN;
}
catch(...){
return NOTCLEAN;
}
default: return NONE;
}
}
template const std::string TreeFunction::GetName<Axis::X>();
template const std::string TreeFunction::GetName<Axis::Y>();
bool TreeFunction::isCleanJet(const int& idx){
const std::vector<float>& phi = RUtil::GetVecEntry<float>(cleanPhi, entry);
const std::vector<float>& eta = RUtil::GetVecEntry<float>(cleanEta, entry);
const std::vector<float>& jPhi = RUtil::GetVecEntry<float>(jetPhi, entry);
const std::vector<float>& jEta = RUtil::GetVecEntry<float>(jetEta, entry);
for(unsigned int i = 0; i < phi.size(); i++){
if(whichWP(cleanPart, i) < cleanedWP) continue;
if(std::sqrt(std::pow(VUtil::At(phi, i) - VUtil::At(jPhi, idx), 2) + std::pow(VUtil::At(eta, i) - VUtil::At(jEta, idx), 2)) < 0.4) return false;
}
return true;
}
void TreeFunction::Pt(){
if(realIdx1 != -1) value = VUtil::At(RUtil::GetVecEntry<float>(quantities[0], entry), realIdx1);
else value = RUtil::GetEntry<float>(quantities[0], entry);
}
void TreeFunction::Phi(){
if(realIdx1 != -1) value = VUtil::At(RUtil::GetVecEntry<float>(quantities[0], entry), realIdx1);
else value = RUtil::GetEntry<float>(quantities[0], entry);
}
void TreeFunction::Mass(){
if(realIdx1 != -1) value = VUtil::At(RUtil::GetVecEntry<float>(quantities[0], entry), realIdx1);
else value = RUtil::GetEntry<float>(quantities[0], entry);
}
void TreeFunction::Mt(){
value = RUtil::GetEntry<float>(quantities[0], entry);
}
void TreeFunction::Eta(){
if(realIdx1 != -1) value = VUtil::At(RUtil::GetVecEntry<float>(quantities[0], entry), realIdx1);
else value = RUtil::GetEntry<float>(quantities[0], entry);
}
void TreeFunction::DeltaPhi(){
float phi1 = realIdx1 != -1 ? VUtil::At(RUtil::GetVecEntry<float>(quantities[0], entry), realIdx1) : RUtil::GetEntry<float>(quantities[0], entry);
float phi2 = realIdx2 != -1 ? VUtil::At(RUtil::GetVecEntry<float>(quantities[1], entry), realIdx2) : RUtil::GetEntry<float>(quantities[1], entry);
value = std::acos(std::cos(phi1)*std::cos(phi2) + std::sin(phi1)*std::sin(phi2));
}
void TreeFunction::DeltaR(){
float phi1 = realIdx1 != -1 ? VUtil::At(RUtil::GetVecEntry<float>(quantities[0], entry), realIdx1) : RUtil::GetEntry<float>(quantities[0], entry);
float phi2 = realIdx2 != -1 ? VUtil::At(RUtil::GetVecEntry<float>(quantities[1], entry), realIdx2) : RUtil::GetEntry<float>(quantities[1], entry);
float eta1 = realIdx1 != -1 ? VUtil::At(RUtil::GetVecEntry<float>(quantities[2], entry), realIdx1) : RUtil::GetEntry<float>(quantities[2], entry);
float eta2 = realIdx2 != -1 ? VUtil::At(RUtil::GetVecEntry<float>(quantities[3], entry), realIdx2) : RUtil::GetEntry<float>(quantities[3], entry);
value = std::sqrt(std::pow(phi1-phi2, 2) + std::pow(eta1-eta2, 2));
}
void TreeFunction::JetSubtiness(){
value = VUtil::At(RUtil::GetVecEntry<float>(quantities[0], entry), realIdx1);
}
void TreeFunction::EventNumber(){
value = Utils::BitCount(int(RUtil::GetEntry<float>(quantities[0], entry)));
}
void TreeFunction::HTag(){
value = RUtil::GetEntry<float>(quantities[0], entry);
}
void TreeFunction::DeepAK(){
value = VUtil::At(RUtil::GetVecEntry<float>(quantities[0], entry), realIdx1);
}
void TreeFunction::DeepAKClass(){
float max = 0;
int maxIdx = 0;
for(int i = 0; i < quantities.size(); ++i){
const float& v = VUtil::At(RUtil::GetVecEntry<float>(quantities[i], entry), realIdx1);
if(v > max){
maxIdx = i;
max = v;
}
}
value = maxIdx;
}
void TreeFunction::DNNClass(){
float max = 0;
int maxIdx = 0;
for(int i = 0; i < quantities.size(); ++i){
const float& v = RUtil::GetEntry<float>(quantities[i], entry);
if(v > max){
maxIdx = i;
max = v;
}
}
value = maxIdx;
}
void TreeFunction::DNN(){
value = RUtil::GetEntry<float>(quantities[0], entry);
}
void TreeFunction::HT(){
value = 0;
for(TLeaf* jet : quantities){
const std::vector<float>& jetPt = RUtil::GetVecEntry<float>(jet, entry);
for(const float& pt : jetPt){
value += pt;
}
}
}
void TreeFunction::Count(){
value = std::stof(this->inputValue);
}
void TreeFunction::NParticle(){
value = 0;
if(part1 == ELECTRON or part1 == MUON){
const std::vector<char>& id = RUtil::GetVecEntry<char>(ID, entry);
for(int i = 0; i < id.size(); i++){
if(whichWP(part1, i) >= wp1) value++;
}
}
else if(part1 == JET){
const char& n = RUtil::GetEntry<char>(nPart1, entry);
for(int i = 0; i < n; ++i){
if(whichWP(part1, i) >= wp1) value++;
}
}
else if(part1 == BJET or part1 == BSUBJET){
const std::vector<float>& score = RUtil::GetVecEntry<float>(BScore, entry);
for(int i = 0; i < score.size(); i++){
if(whichWP(part1, i) >= wp1) value++;
}
}
else if(part1 == TRACK){
const char& n = RUtil::GetEntry<char>(nPart1, entry);
for(int i = 0; i < n; i++){
if(whichWP(part1, i) > NOTCLEAN) value++;
}
}
else{
value = RUtil::GetEntry<char>(nPart1, entry);
}
}
<file_sep>/Workflow/python/taskmanager.py
import time
import os
import copy
import subprocess
import csv
import json
import yaml
import multiprocessing as mp
from collections import OrderedDict
from taskmonitor import TaskMonitor
from task import Task
class TaskManager(object):
def __init__(self, tasks = [], existingFlow = "", dir = "", condorSub = "$CHDIR/ChargedAnalysis/Workflow/templates/tasks.sub", html = "$CHDIR/ChargedAnalysis/Workflow/templates/workflow.html"):
self.time = time.time()
##Read in tasks or create from given csv summary file of other workflow
self._tasks = {}
if tasks:
self._tasks = {t["name"]: t for t in tasks}
##Check for unique name/directory
names = list(self._tasks.keys())
nonUnique = list(set([n for n in names if names.count(n) > 1]))
if nonUnique:
raise RuntimeError("Each task has to have an unique name! Non unique names: \n{}".format("\n".join(nonUnique)))
dirs = [t["dir"] for t in self._tasks.values()]
nonUnique = list(set([d for d in dirs if dirs.count(d) > 1]))
if nonUnique:
raise RuntimeError("Each task has to have an unique directory! Non unique names: \n{}".format("\n".join(nonUnique)))
elif existingFlow:
with open(existingFlow, "r") as flow:
summary = csv.reader(flow, delimiter = "\t")
next(summary, None)
for (taskStatus, taskName, taskDir) in summary:
with open("{}/task.yaml".format(taskDir)) as task:
t = yaml.safe_load(task)
if taskStatus == "Finished":
continue
self._tasks[taskName] = Task(t, "--")
else:
raise RuntimeError("No tasks will be running! You need to provide a list of tasks or a existing workflow by handing the csv summary!")
##Create working dir
self.dir = dir if dir else "Tasks/{}".format(time.asctime().replace(" ", "_").replace(":", "_"))
os.makedirs(self.dir, exist_ok = True)
self.condorSub = condorSub
self.html = html
##Template for workflow.html displaying jobs
self.htmlTemplate, self.divTemplate = "", ""
with open(os.path.expandvars(html), "r") as workflow:
for line in workflow:
if "div class='task'" in line:
self.divTemplate = line
self.htmlTemplate += "{divs}"
else:
self.htmlTemplate += line
##Monitor displayed
self.monitor = TaskMonitor(len(self._tasks.keys()))
self.remove = []
self.runningTasks = {}
self.status = {}
##Write summary to csv file
self.summary = csv.DictWriter(open("{}/summary.csv".format(self.dir), "w"), delimiter = "\t", fieldnames = ["Status", "Task", "Dir"])
self.summary.writeheader()
def __del__(self):
##Write remaining jobs in case of failure
for t in self._tasks.values():
self.summary.writerow({"Task": t["name"], "Dir": t["dir"], "Status": t["status"]})
def __writeHTML(self):
finished = ""
running = ""
##Loop over all jobs and create div element with template
for name, t in self._tasks.items():
div = self.divTemplate.format(data = json.dumps(t, separators=(',', ':')), id = name, dependent = ",".join(t["dependencies"]))
if t["status"] != "Finished":
running += div
else:
finished += div
##Create workflow html
self.htmlTemplate = self.htmlTemplate.replace("{divs}", finished + "{divs}")
with open("{}/workflow.html".format(self.dir), "w") as workflow:
workflow.write(self.htmlTemplate.replace("{divs}", running))
def __changeStatus(self, task, status, runType):
if task["status"] != "None":
##Decrement number of old status
self.status.setdefault(runType, {}).setdefault(task["status"], 0)
self.status[runType][task["status"]] -= 1
##Mark task to be removed from self._tasks
if status == "Finished":
self.remove.append(task["name"])
##Increment number of new status
self.status.setdefault(runType, {}).setdefault(status, 0)
self.status[runType][status] += 1
task["status"] = status
##Write workflow.html
# self.__writeHTML()
##Break if job failed
if status == "Failed":
self.monitor.updateMonitor(time.time() - self.time, self.status)
raise RuntimeError("Task '{}' failed! See error message: {}/err.txt".format(task["name"], task["dir"]))
def __getJobs(self):
pool = mp.Pool(processes=20)
condorSubmit = "condor_submit {} -batch-name TaskManager -queue DIR in ".format(self.condorSub)
toSubmit = []
while(self._tasks):
##Remove finished jobs
while(self.remove):
t = self._tasks.pop(self.remove.pop())
self.summary.writerow({"Task": t["name"], "Dir": t["dir"], "Status": t["status"]})
for name, task in self._tasks.items():
yield True
if task["status"] != "Valid":
continue
##Check if dependencies all finished
try:
for dep in task["dependencies"]:
if dep in self._tasks:
raise ValueError("")
except ValueError:
continue
##Local job configuration
if task["run-mode"] == "Local":
if len(self.runningTasks.get("Local", [])) >= 20:
continue
task.job = pool.apply_async(copy.deepcopy(task.run))
self.__changeStatus(task, "Running", "Local")
self.runningTasks.setdefault("Local", OrderedDict())[name] = task
##Condor job configuration
if task["run-mode"] == "Condor":
if len(self.runningTasks.get("Condor", [])) >= 500:
continue
if len(toSubmit) >= 100:
subprocess.run(condorSubmit + " ".join(toSubmit), shell = True, stdout=open(os.devnull, 'wb'))
toSubmit.clear()
self.runningTasks.setdefault("Condor", OrderedDict())[name] = task
self.__changeStatus(task, "Submitted", "Condor")
toSubmit.append(task["dir"])
if len(toSubmit) != 0:
subprocess.run(condorSubmit + " ".join(toSubmit), shell = True, stdout=open(os.devnull, 'wb'))
toSubmit.clear()
def run(self, dryRun = False):
##Create directories/executable etc.
for task in self._tasks.values():
task.prepare()
self.__changeStatus(task, "Valid", task["run-mode"])
if dryRun:
return 0
##Update monitor
self.monitor.updateMonitor(time.time() - self.time, self.status)
##Generator to process list of tasks sequentially
jobHandler = self.__getJobs()
next(jobHandler)
##Tasks are saved in FIFO, if task not finished, its pushed back to FIFO
while(True):
if self.runningTasks.get("Local", OrderedDict()):
name, task = self.runningTasks["Local"].popitem(0)
if task.job.ready():
if task.job.get() == 0:
self.__changeStatus(task, "Finished", "Local")
else:
self.__changeStatus(task, "Failed", "Local")
else:
self.runningTasks["Local"][name] = task
if self.runningTasks.get("Condor", []):
name, task = self.runningTasks["Condor"].popitem(0)
with open("{}/log.txt".format(task["dir"]), "r") as logFile:
condorLog = logFile.read()
if "Job executing" in condorLog and task["status"] != "Running":
self.__changeStatus(task, "Running", "Condor")
if "Normal termination" in condorLog:
if "(return value 0)" in condorLog:
self.__changeStatus(task, "Finished", "Condor")
else:
self.__changeStatus(task, "Failed", "Condor")
else:
self.runningTasks["Condor"][name] = task
##Update monitor
self.monitor.updateMonitor(time.time() - self.time, self.status)
next(jobHandler, None)
if not self._tasks:
break
<file_sep>/Utility/src/datacard.cc
#include <ChargedAnalysis/Utility/include/datacard.h>
Datacard::Datacard(){}
Datacard::Datacard(const std::string& outDir, const std::string& channel, const std::vector<std::string>& bkgProcesses, const std::vector<std::string>& bkgFiles, const std::string& sigProcess, const std::vector<std::string>& sigFiles, const std::string& data, const std::string& dataFile, const std::vector<std::string>& systematics) :
outDir(outDir),
channel(channel),
bkgProcesses(bkgProcesses),
bkgFiles(bkgFiles),
sigProcess(sigProcess),
sigFiles(sigFiles),
data(data),
dataFile(dataFile),
systematics(systematics){}
void Datacard::GetHists(const std::string& discriminant){
TH1::AddDirectory(kFALSE);
//Open file which saves all process shapes
std::shared_ptr<TFile> outFile = std::make_shared<TFile>((outDir + "/shapes.root").c_str(), "RECREATE");
TDirectory* dir = outFile->mkdir(channel.c_str());
std::shared_ptr<TH1F> bkgSum;
//Open file with shape and get histogram
for(const std::string& syst : systematics){
for(const std::string shift : {"Up", "Down"}){
//Skip Down loop for nominal case
if(syst == "" and shift == "Down") continue;
std::string systName = syst == "" ? "" : StrUtil::Merge(syst, shift);
for(std::size_t i = 0; i < bkgFiles.size(); ++i){
std::shared_ptr<TFile> file = RUtil::Open(bkgFiles.at(i));
std::shared_ptr<TH1F> hist = RUtil::GetSmart<TH1F>(file.get(), discriminant);
hist->SetName(syst == "" ? bkgProcesses.at(i).c_str() : StrUtil::Join("_", bkgProcesses.at(i), systName).c_str());
hist->SetTitle(syst == "" ? bkgProcesses.at(i).c_str() : StrUtil::Join("_", bkgProcesses.at(i), systName).c_str());
//Save yield of histogram
if(syst == ""){
rates[bkgProcesses.at(i)] = hist->Integral();
if(bkgSum == nullptr) bkgSum = RUtil::CloneSmart<TH1F>(hist.get());
else bkgSum->Add(hist.get());
}
dir->cd();
hist->Write();
}
for(std::size_t i = 0; i < sigFiles.size(); ++i){
std::shared_ptr<TFile> file = RUtil::Open(sigFiles.at(i));
std::shared_ptr<TH1F> hist = RUtil::GetSmart<TH1F>(file.get(), discriminant);
hist->SetName(syst == "" ? sigProcess.c_str() : StrUtil::Join("_", sigProcess, systName).c_str());
hist->SetTitle(syst == "" ? sigProcess.c_str() : StrUtil::Join("_", sigProcess, systName).c_str());
//Save yield of histogram
if(syst == "") rates[sigProcess] = hist->Integral();
dir->cd();
hist->Write();
}
}
}
if(dataFile == ""){
bkgSum->SetName("data_obs");
bkgSum->SetTitle("data_obs");
rates["data_obs"] = bkgSum->Integral();
dir->cd();
bkgSum->Write();
}
else{
//Open file with shape and get histogram
std::shared_ptr<TFile> file = RUtil::Open(dataFile);
std::shared_ptr<TH1F> hist = RUtil::GetSmart<TH1F>(file.get(), discriminant);
hist->SetName("data_obs");
hist->SetTitle("data_obs");
//Save yield of histogram
rates["data_obs"] = hist->Integral();
dir->cd();
hist->Write();
}
}
void Datacard::Write(){
std::ofstream datacard;
datacard.open(outDir + "/datacard.txt");
std::string border = "--------------------------------------------------------------------------------";
datacard << "imax 1 number of channel\n";
datacard << "jmax " << bkgProcesses.size() << " number of backgrounds\n";
datacard << "kmax " << (systematics.size() - 1) << " number of nuisance parameters\n";
datacard << border << std::endl;
for(std::string& process: bkgProcesses){
datacard << "shapes " << process << " " << channel << " shapes.root $CHANNEL/$PROCESS $CHANNEL/$PROCESS_$SYSTEMATIC\n";
}
datacard << "shapes " << sigProcess << " " << channel << " shapes.root $CHANNEL/$PROCESS $CHANNEL/$PROCESS_$SYSTEMATIC\n";
datacard << "shapes " << "data_obs" << " " << channel << " shapes.root $CHANNEL/$PROCESS $CHANNEL/$PROCESS_$SYSTEMATIC\n";
datacard << border << std::endl;
datacard << std::left << std::setw(40) << "bin" << channel << "\n";
datacard << std::left << std::setw(40) << "observation" << rates["data_obs"] << "\n";
datacard << border << std::endl;
std::stringstream binNames; binNames << std::left << std::setw(40) << "bin";
std::stringstream processNr; processNr << std::left << std::setw(40) << "process";
std::stringstream processName; processName << std::left << std::setw(40) << "process";
std::stringstream rate; rate << std::left << std::setw(40) << "rate";
binNames << std::left << std::setw(25) << channel;
processNr << std::left << std::setw(25) << -1;
processName << std::left << std::setw(25) << sigProcess;
rate << std::left << std::setw(25) << rates[sigProcess];
for(unsigned int i = 0; i < bkgProcesses.size(); i++){
binNames << std::left << std::setw(i!=bkgProcesses.size()-1 ? 25 : channel.size()) << channel;
if(i==bkgProcesses.size()-1) binNames << "\n";
processNr << std::left << std::setw(i!=bkgProcesses.size()-1 ? 25 : std::ceil((i+1)/10.)) << i+1;
if(i==bkgProcesses.size()-1) processNr << "\n";
processName << std::left << std::setw(i!=bkgProcesses.size()-1 ? 25 : bkgProcesses[i].size()) << bkgProcesses[i];
if(i==bkgProcesses.size()-1) processName << "\n";
rate << std::left << std::setw(i!=bkgProcesses.size()-1 ? 25 : std::to_string(rates[bkgProcesses[i]]).size()) << rates[bkgProcesses[i]];
if(i==bkgProcesses.size()-1) rate << "\n";
}
datacard << binNames.rdbuf();
datacard << processNr.rdbuf();
datacard << processName.rdbuf();
datacard << rate.rdbuf();
datacard << border << std::endl;
for(const std::string syst : systematics){
if(syst == "") continue;
std::stringstream systLine;
systLine << std::left << std::setw(20) << syst << std::setw(20) << "shape";
for(unsigned int i = 0; i < bkgProcesses.size() + 1; i++){
systLine << std::left << std::setw(i!=bkgProcesses.size() ? 25 : channel.size()) << "1";
if(i==bkgProcesses.size()) systLine << "\n";
}
datacard << systLine.rdbuf();
}
datacard.close();
}
<file_sep>/Utility/src/utils.cc
#include <ChargedAnalysis/Utility/include/utils.h>
template <typename T>
std::vector<T> Utils::SplitString(const std::string& splitString, const std::string& delimeter){
T value;
std::vector<T> values;
std::size_t current, previous = 0;
current = splitString.find(delimeter);
while (current != std::string::npos){
std::istringstream iss(splitString.substr(previous, current - previous));
iss >> value;
values.push_back(value);
previous = current + 1;
current = splitString.find(delimeter, previous);
}
std::istringstream iss(splitString.substr(previous, current - previous));
iss >> value;
values.push_back(value);
return values;
}
template std::vector<std::string> Utils::SplitString(const std::string&, const std::string&);
template std::vector<int> Utils::SplitString(const std::string&, const std::string&);
template std::vector<float> Utils::SplitString(const std::string&, const std::string&);
template <typename T>
std::string Utils::Format(const std::string& label, const std::string& initial, const T& replace, const bool& ignoreMissing){
std::string result = initial;
std::stringstream repl;
repl << replace;
if(result.find(label) != std::string::npos){
result.replace(result.find(label), 1, repl.str());
}
else{
if(!ignoreMissing) throw std::out_of_range("Did not found '" + label + "' in string '" + result + "'");
}
return result;
}
template std::string Utils::Format(const std::string&, const std::string&, const std::string&, const bool&);
template std::string Utils::Format(const std::string&, const std::string&, const int&, const bool&);
template std::string Utils::Format(const std::string&, const std::string&, const float&, const bool&);
std::string Utils::Join(const std::string& delimeter, const std::vector<std::string> strings){
std::string out;
for(std::vector<std::string>::const_iterator it = strings.begin(); it != strings.end(); ++it){
out += *it;
if(it != strings.end() - 1) out += delimeter;
}
return out;
}
template <typename T>
std::vector<T> Utils::Merge(const std::vector<T>& vec1, const std::vector<T>& vec2){
std::vector<T> vec = vec1;
vec.insert(vec.end(), vec2.begin(), vec2.end());
return vec;
}
template std::vector<std::string> Utils::Merge(const std::vector<std::string>&, const std::vector<std::string>&);
template std::vector<int> Utils::Merge(const std::vector<int>&, const std::vector<int>&);
template std::vector<float> Utils::Merge(const std::vector<float>&, const std::vector<float>&);
template <typename T>
int Utils::Find(const std::string& string, const T& itemToFind){
int position = -1.;
std::stringstream item;
item << itemToFind;
if(string.find(item.str()) != std::string::npos){
position=string.find(item.str());
}
return position;
}
template int Utils::Find(const std::string&, const int&);
template int Utils::Find(const std::string&, const float&);
template int Utils::Find(const std::string&, const std::string&);
void Utils::ProgressBar(const int& progress, const std::string& addInfo){
std::string progressBar = "[";
for(int i = 0; i <= progress; i++){
if(i%10 == 0) progressBar += "#";
}
for(int i = 0; i < 100 - progress; i++){
if(i%10 == 0) progressBar += " ";
}
progressBar = progressBar + "] " + addInfo;
std::cout << "\r" << progressBar << std::flush;
if(progress == 100) std::cout << std::endl;
}
Utils::RunTime::RunTime(){
start = std::chrono::steady_clock::now();
}
float Utils::RunTime::Time(){
end = std::chrono::steady_clock::now();
return std::chrono::duration_cast<std::chrono::seconds>(end - start).count();
}
unsigned int Utils::BitCount(unsigned int num){
unsigned int count = 0;
while (num) {
count += num & 1;
num >>= 1;
}
return count;
}
float Utils::CheckZero(const float& input){
return input == 0. ? 1: input;
}
void Utils::CopyToCache(const std::string inFile, const std::string outPath){
std::string gfalPrefix = "srm://dcache-se-cms.desy.de:8443/srm/managerv2?SFN=";
std::string dCachePath = "/pnfs/desy.de/cms/tier2/store/user/dbrunner/";
std::string fileName = Utils::SplitString<std::string>(inFile, "/").back();
std::system(("gfal-mkdir -p " + gfalPrefix + dCachePath + outPath).c_str());
std::system(("gfal-copy -f " + inFile + " " + gfalPrefix + dCachePath + outPath + "/" + fileName).c_str());
std::system(("rm -fv " + inFile).c_str());
std::system(("ln -sv " + dCachePath + outPath + "/" + fileName + " " + inFile).c_str());
}
TGraph* Utils::GetROC(const std::vector<float>& pred, const std::vector<int>& target, const int& nPoints){
TGraph* ROC = new TGraph();
for(int i = 1; i <= nPoints; i++){
int truePositive = 0, trueTotal = 0, falsePositive = 0, falseTotal = 0;
float thresHold = (float)i/nPoints;
for(int j = 0; j < pred.size(); j++){
if(target[j] == 0){
falseTotal++;
if(pred[j] > thresHold) falsePositive++;
}
if(target[j] == 1){
trueTotal++;
if(pred[j] > thresHold) truePositive++;
}
}
ROC->SetPoint(i, (float)falsePositive/falseTotal, (float)truePositive/trueTotal);
}
return ROC;
}
void Utils::DrawScore(const torch::Tensor pred, const torch::Tensor truth, const std::string& scorePath){
TCanvas* canvas = new TCanvas("canvas", "canvas", 1000, 800);
canvas->Draw();
TH1F* higgsHist = new TH1F("Higgs", "Higgs", 30, 0, 1);
higgsHist->SetLineColor(kBlue+1);
higgsHist->SetFillStyle(3335);
higgsHist->SetFillColor(kBlue);
higgsHist->SetLineWidth(4);
TH1F* topHist = new TH1F("Top", "Top", 30, 0, 1);
topHist->SetLineColor(kRed+1);
topHist->SetFillStyle(3353);
topHist->SetFillColor(kRed);
topHist->SetLineWidth(4);
TGraph* ROC;
TLatex* rocText;
PUtil::SetPad(canvas);
PUtil::SetStyle();
PUtil::SetHist(canvas, topHist);
for(unsigned int k=0; k < pred.size(0); k++){
if(truth[k].item<float>() == 0){
topHist->Fill(pred[k].item<float>());
}
else{
higgsHist->Fill(pred[k].item<float>());
}
}
topHist->DrawNormalized("HIST");
higgsHist->DrawNormalized("HIST SAME");
PUtil::DrawHeader(canvas, "All channel", "Work in Progress");
canvas->SaveAs((scorePath + "/score.pdf").c_str());
delete canvas; delete topHist; delete higgsHist;
}
<file_sep>/Network/exesrc/dnn.cc
#include <torch/torch.h>
#include <random>
#include <map>
#include <vector>
#include <string>
#include <filesystem>
#include <experimental/random>
#include <ChargedAnalysis/Network/include/dnnmodel.h>
#include <ChargedAnalysis/Network/include/dnndataset.h>
#include <ChargedAnalysis/Utility/include/parser.h>
#include <ChargedAnalysis/Utility/include/utils.h>
#include <ChargedAnalysis/Utility/include/stringutil.h>
#include <ChargedAnalysis/Utility/include/rootutil.h>
#include <ChargedAnalysis/Utility/include/vectorutil.h>
#include <ChargedAnalysis/Utility/include/plotutil.h>
#include <ChargedAnalysis/Utility/include/frame.h>
float Train(std::shared_ptr<DNNModel> model, std::vector<DNNDataset>& sigSets, std::vector<DNNDataset>& bkgSets, std::vector<int>& masses, torch::Device& device, const int& batchSize, const float& lr, const bool& optimize, const std::string& outPath, const std::vector<std::string>& bkgClasses){
//Calculate weights to equalize pure number of events for signal and background
std::vector<int> nBkg(bkgClasses.size(), 0);
int nSig = 0, nBkgTotal = 0;
for(DNNDataset& set : sigSets) nSig += set.size().value();
for(DNNDataset& set : bkgSets){
nBkg[set.GetClass()] += set.size().value();
nBkgTotal += set.size().value();
}
float wSig = (nBkgTotal+nSig)/float(nSig);
std::vector<float> wBkg(bkgClasses.size(), 1.);
for(int i = 0; i < bkgClasses.size(); ++i){
wBkg[i] = (nBkgTotal+nSig)/float(nBkg[i]);
}
//Calculate number of batches
int nBatches = nSig+nBkgTotal % batchSize == 0 ? (nSig+nBkgTotal)/batchSize - 1 : std::ceil((nSig+nBkgTotal)/batchSize);
//Get dataloader
std::vector<std::vector<std::pair<int, int>>> signal;
std::vector<std::vector<std::pair<int, int>>> bkg;
for(DNNDataset& set : sigSets){
int bSize = float(set.size().value())*batchSize/(nBkgTotal+nSig);
int skip = bSize > 1 ? 0 : std::ceil(1./bSize);
std::vector<std::pair<int, int>> batches(nBatches, std::pair<int, int>{});
for(std::size_t i = 0; i < nBatches; ++i){
if(skip == 0){
batches.at(i) = {i*bSize, (i + 1)*bSize};
}
else if(i % skip == 0){
batches.at(i/skip) = {i/skip*bSize, (i/skip + 1)*bSize};
}
}
signal.push_back(batches);
}
for(DNNDataset& set : bkgSets){
float bSize = float(set.size().value())*batchSize/(nBkgTotal+nSig);
int skip = bSize > 1 ? 0 : std::ceil(1./bSize);
std::vector<std::pair<int, int>> batches(nBatches, std::pair<int, int>{});
for(std::size_t i = 0; i < nBatches; ++i){
if(skip == 0){
batches.at(i) = {i*bSize, (i + 1)*bSize};
}
else if(i % skip == 0){
batches.at(i/skip) = {i/skip*bSize, (i/skip + 1)*bSize};
}
}
bkg.push_back(batches);
}
torch::Tensor weight = torch::from_blob(VUtil::Append(wBkg, wSig).data(), {bkgClasses.size() + 1}).clone().to(device);
//Optimizer
torch::optim::Adam optimizer(model->parameters(), torch::optim::AdamOptions(lr).weight_decay(lr/10.));
torch::nn::CrossEntropyLoss loss(torch::nn::CrossEntropyLossOptions().weight(weight));
//Initial best loss for later early stopping
float bestLoss = 1e7;
int patience = optimize ? 2 : 10;
int notBetter = 0;
for(int i=0; i < 10000; ++i){
//Measure time
Utils::RunTime timer;
float meanTrainLoss=0., meanTestLoss=0.;
//Declaration of input train/test tensors
DNNTensor train, test;
std::vector<int> trainMass, testMass;
if(optimize and timer.Time() > 60*5) break;
std::vector<int> rndBatchIdx = VUtil::Range(0, nBatches - 1, nBatches);
int seed = int(std::time(0));
std::srand(seed);
std::random_shuffle(rndBatchIdx.begin(), rndBatchIdx.end());
for(std::size_t j = 0; j < nBatches; ++j){
//Do fewer n of batches for hyperopt
if(optimize and j == 50) break;
//Set gradients to zero
optimizer.zero_grad();
//Put signal + background in batch vector
std::vector<DNNTensor> batch;
std::vector<int> batchMass;
for(int k = 0; k < sigSets.size(); ++k){
for(int l = signal.at(k).at(rndBatchIdx.at(j)).first; l < signal.at(k).at(rndBatchIdx.at(j)).second; ++l){
batchMass.push_back(masses.at(k));
batch.push_back(sigSets.at(k).get(l));
}
}
for(int k = 0; k < bkgSets.size(); ++k){
for(int l = bkg.at(k).at(rndBatchIdx.at(j)).first; l < bkg.at(k).at(rndBatchIdx.at(j)).second; ++l){
int index = std::experimental::randint(0, (int)masses.size() -1);
batchMass.push_back(masses.at(index));
batch.push_back(bkgSets.at(k).get(l));
}
}
//Set batch for testing and go to next iteration
if(j == 0){
test = DNNDataset::Merge(batch);
testMass = batchMass;
continue;
}
//Set batch for training
train = DNNDataset::Merge(batch);
trainMass = batchMass;
//Prediction
model->train();
torch::Tensor predictionTrain = model->forward(train.input, torch::from_blob(trainMass.data(), {trainMass.size(), 1}, torch::kInt).clone().to(device));
model->eval();
torch::Tensor predictionTest = model->forward(test.input, torch::from_blob(testMass.data(), {testMass.size(), 1}, torch::kInt).clone().to(device));
//Calculate loss and mean of loss of the batch
torch::Tensor lossTrain = loss->forward(predictionTrain, train.label);
torch::Tensor lossTest = loss->forward(predictionTest, test.label);
meanTrainLoss = (meanTrainLoss*j + lossTrain.item<float>())/(j+1);
meanTestLoss = (meanTestLoss*j + lossTest.item<float>())/(j+1);
//Draw signal/background score during training of monitoring
if(j % 3 == 0){
torch::Tensor pred = torch::nn::functional::softmax(predictionTest, torch::nn::functional::SoftmaxFuncOptions(1));
torch::Tensor predLab = std::get<1>(torch::max(pred, 1));
std::vector<long> predLabel(predLab.data_ptr<long>(), predLab.data_ptr<long>() + predLab.numel());
test.label = test.label.contiguous();
std::vector<long> trueLabel(test.label.data_ptr<long>(), test.label.data_ptr<long>() + test.label.numel());
std::vector<std::string> allClasses = VUtil::Append(bkgClasses, "HPlus");
PUtil::DrawConfusion(trueLabel, predLabel, allClasses, outPath);
for(int l = 0; l < allClasses.size(); ++l){
std::shared_ptr<TCanvas> c = std::make_shared<TCanvas>("c", "c", 1000, 1000);
std::shared_ptr<TLegend> leg = std::make_shared<TLegend>(0., 0., 1, 1);
PUtil::SetStyle();
PUtil::SetPad(c.get());
std::vector<std::shared_ptr<TH1F>> hists;
for(const std::string& cls : allClasses){
hists.push_back(std::make_shared<TH1F>(cls.c_str(), cls.c_str(), 20, 0, 1));
hists.back()->SetLineColor(20 + 5*hists.size());
hists.back()->SetLineWidth(4);
hists.back()->GetXaxis()->SetTitle(("Probabilities for " + allClasses[l]).c_str());
leg->AddEntry(hists.back().get(), cls.c_str(), "L");
}
PUtil::SetHist(c.get(), hists.back().get());
for(int n = 0; n < trueLabel.size(); ++n){
if(trueLabel[n] != l) continue;
for(int o = 0; o < allClasses.size(); ++o){
hists[o]->Fill(pred[n][o].item<float>());
}
}
for(const std::shared_ptr<TH1F>& h : hists) h->Draw("SAME HIST");
PUtil::DrawLegend(c.get(), leg.get(), allClasses.size());
c->SaveAs((outPath + "/score_" + allClasses[l] + ".pdf").c_str());
}
}
//Back propagation
lossTrain.backward();
optimizer.step();
//Progess bar
std::string barString = StrUtil::Merge<3>("Epoch: ", i+1,
" | Batch: ", j, "/", nBatches - 1,
" | Mean Loss: ", meanTrainLoss, "/", meanTestLoss,
" | Overtrain: ", notBetter, "/", patience,
" | Time: ", timer.Time(), " s"
);
Utils::ProgressBar(float(j+1)/nBatches*100, barString);
if(optimize and timer.Time() > 60*5) break;
}
//Early stopping
if(meanTestLoss > bestLoss) notBetter++;
else{
bestLoss = meanTestLoss;
notBetter = 0;
//Save model
if(!optimize){
model->to(torch::kCPU);
torch::save(model, outPath + "/model.pt");
std::cout << "Model was saved: " + outPath + "/model.pt" << std::endl;
model->to(device);
}
}
if(notBetter == patience) break;
}
return bestLoss;
}
int main(int argc, char** argv){
//Parser arguments
Parser parser(argc, argv);
std::string outPath = parser.GetValue<std::string>("out-path");
std::string channel = parser.GetValue<std::string>("channel");
int era = parser.GetValue<int>("era");
bool isEven = parser.GetValue<bool>("is-even");
std::vector<std::string> sigFiles = parser.GetVector<std::string>("sig-files");
std::vector<std::string> bkgClasses = parser.GetVector<std::string>("bkg-classes");
std::vector<std::string> parameters = parser.GetVector<std::string>("parameters");
std::vector<std::string> cuts = parser.GetVector<std::string>("cuts");
std::vector<int> masses = parser.GetVector<int>("masses");
std::string optParam = parser.GetValue<std::string>("opt-param", "");
std::unique_ptr<Frame> hyperParam;
if(optParam != "") hyperParam = std::make_unique<Frame>(optParam);
int batchSize = parser.GetValue<int>("batch-size", optParam != "" ? hyperParam->Get("batch-size", 0) : 2000);
int nNodes = parser.GetValue<int>("n-nodes", optParam != "" ? hyperParam->Get("n-nodes", 0) : 40);
int nLayers = parser.GetValue<int>("n-layers", optParam != "" ? hyperParam->Get("n-layers", 0) : 3);
float dropOut = parser.GetValue<float>("drop-out", optParam != "" ? hyperParam->Get("drop-out", 0) : 0.1);
float lr = parser.GetValue<float>("lr", optParam != "" ? hyperParam->Get("lr", 0) : 1e-4);
if(lr < 0) lr = std::pow(10, lr);
bool optimize = parser.GetValue<bool>("optimize");
//Check if you are on CPU or GPU
torch::Device device(torch::kCPU);
//Restrict number of threads to one
at::set_num_interop_threads(1);
at::set_num_threads(1);
//Pytorch dataset class
std::vector<std::shared_ptr<TFile>> files;
std::vector<std::shared_ptr<TTree>> trees;
std::vector<DNNDataset> sigSets;
std::vector<DNNDataset> bkgSets;
//Create model
std::shared_ptr<DNNModel> model = std::make_shared<DNNModel>(parameters.size(), nNodes, nLayers, dropOut, masses.size() == 1 ? false : true, bkgClasses.size() + 1, device);
if(std::filesystem::exists(outPath + "/model.pt")) torch::load(model, outPath + "/model.pt");
model->Print();
if(optimize and model->GetNWeights() > 300000){
std::cout << -1 << std::endl;
return 0;
}
//Collect input data
for(std::string fileName: sigFiles){
files.push_back(RUtil::Open(fileName));
trees.push_back(RUtil::GetSmart<TTree>(files.back().get(), channel));
DNNDataset sigSet(trees.back(), parameters, cuts, era, isEven, device, bkgClasses.size());
sigSets.push_back(std::move(sigSet));
}
for(int i = 0; i < bkgClasses.size(); ++i){
std::vector<std::string> bkgFiles = parser.GetVector<std::string>(StrUtil::Replace("@-files", "@", bkgClasses.at(i)));
for(std::string fileName: bkgFiles){
files.push_back(RUtil::Open(fileName));
trees.push_back(RUtil::GetSmart<TTree>(files.back().get(), channel));
DNNDataset bkgSet(trees.back(), parameters, cuts, era, isEven, device, i);
bkgSets.push_back(std::move(bkgSet));
}
}
//Do training
float bestLoss = Train(model, sigSets, bkgSets, masses, device, batchSize, lr, optimize, outPath, bkgClasses);
if(optimize) std::cout << "\n" << bestLoss << std::endl;
}
<file_sep>/Analysis/src/treereader.cc
#include <ChargedAnalysis/Analysis/include/treereader.h>
//Constructor
TreeReader::TreeReader(){}
TreeReader::TreeReader(const std::vector<std::string> ¶meters, const std::vector<std::string> &cutStrings, const std::string& outDir, const std::string &outFile, const std::string &channel, const std::vector<std::string>& systDirs, const std::vector<std::string>& scaleSysts, const std::string& scaleFactors, const int& era):
parameters(parameters),
cutStrings(cutStrings),
outDir(outDir),
outFile(outFile),
channel(channel),
systDirs(systDirs),
scaleSysts(scaleSysts),
scaleFactors(scaleFactors),
era(era){}
void TreeReader::PrepareLoop(){
TreeParser parser;
if(VUtil::Find(scaleSysts, std::string("")).empty()) scaleSysts.insert(scaleSysts.begin(), "");
for(const std::string& scaleSyst : scaleSysts){
for(const std::string shift : {"Up", "Down"}){
//Skip Down loop for nominal case
if(scaleSyst == "" and shift == "Down") continue;
std::string systName = StrUtil::Merge(scaleSyst, shift);
std::string outName;
//Change outdir for systematic
if(scaleSyst.empty()) outName = StrUtil::Join("/", outDir, outFile);
else{
for(const std::string dir : systDirs){
if(!StrUtil::Find(dir, systName).empty()) outName = StrUtil::Join("/", dir, outFile);
}
}
outFiles.push_back(std::make_shared<TFile>(outName.c_str(), "RECREATE"));
for(const std::string& parameter: parameters){
//Functor structure and arguments
TreeFunction function(inputFile, inputTree->GetName(), era, scaleSysts.size() != 1);
//Read in everything, orders matter
parser.GetParticle(parameter, function);
parser.GetFunction(parameter, function);
if(!StrUtil::Find(parameter, "h:").empty()){
if(!function.hasYAxis()){
std::shared_ptr<TH1F> hist1D = std::make_shared<TH1F>();
parser.GetBinning(parameter, hist1D.get());
hist1D->SetDirectory(outFiles.back().get());
hist1D->SetName((function.GetName<Axis::X>()).c_str());
hist1D->SetTitle((function.GetName<Axis::X>()).c_str());
hist1D->GetXaxis()->SetTitle(function.GetAxisLabel<Axis::X>().c_str());
if(scaleSyst == "") hists1D.push_back(std::move(hist1D));
else hists1DSyst.push_back(std::move(hist1D));
if(scaleSyst == "") hist1DFunctions.push_back(function);
}
else{
std::shared_ptr<TH2F> hist2D = std::make_shared<TH2F>();
parser.GetBinning(parameter, hist2D.get());
hist2D->SetDirectory(outFiles.back().get());
hist2D->SetName((function.GetName<Axis::X>() + "_VS_" + function.GetName<Axis::Y>()).c_str());
hist2D->SetTitle((function.GetName<Axis::X>() + "_VS_" + function.GetName<Axis::Y>()).c_str());
hist2D->GetXaxis()->SetTitle(function.GetAxisLabel<Axis::X>().c_str());
hist2D->GetYaxis()->SetTitle(function.GetAxisLabel<Axis::Y>().c_str());
if(scaleSyst == "") hists2D.push_back(std::move(hist2D));
else hists2DSyst.push_back(std::move(hist2D));
if(scaleSyst == "") hist2DFunctions.push_back(function);
}
}
if(!StrUtil::Find(parameter, "t:").empty() and scaleSyst == ""){
if(outTree == nullptr){
outTree = std::make_shared<TTree>(channel.c_str(), channel.c_str());
outTree->SetDirectory(outFiles.back().get());
}
branchNames.push_back(function.GetName<Axis::X>());
treeValues.push_back(1.);
treeFunctions.push_back(function);
}
if(!StrUtil::Find(parameter, "csv:").empty()){
CSVNames.push_back(function.GetName<Axis::X>());
CSVFunctions.push_back(function);
}
}
}
}
//Declare branches of output tree if wished
for(int i=0; i < branchNames.size(); i++){
outTree->Branch(branchNames[i].c_str(), &treeValues[i]);
}
//Declare columns in CSV file if wished
if(!CSVNames.empty()){
frame = std::make_shared<Frame>();
frame->InitLabels(CSVNames);
}
for(const std::string& cut: cutStrings){
//Functor structure and arguments
TreeFunction function(inputFile, inputTree->GetName(), era, scaleSysts.size() != 1);
parser.GetParticle(cut, function);
parser.GetFunction(cut, function);
parser.GetCut(cut, function);
function.SetSystematics(scaleSysts);
cutFunctions.push_back(function);
std::cout << "Cut will be applied: '" << function.GetCutLabel() << "'" << std::endl;
}
}
void TreeReader::EventLoop(const std::string &fileName, const std::string& cleanJet){
//Take time
Utils::RunTime timer;
//Get input tree
inputFile = RUtil::Open(fileName);
inputTree = RUtil::GetSmart<TTree>(inputFile.get(), channel);
TLeaf* nTrueInter = RUtil::Get<TLeaf>(inputTree.get(), "Misc_TrueInteraction");
std::cout << "Read file: '" << fileName << "'" << std::endl;
std::cout << "Read tree '" << channel << std::endl;
gROOT->SetBatch(kTRUE);
if(outFile.find("csv") != std::string::npos) StrUtil::Replace(outFile, "csv", "root");
//Open output file and set up all histograms/tree and their function to call
PrepareLoop();
//Determine what to clean from jets
std::vector<std::string> cleanInfo = Utils::SplitString<std::string>(cleanJet, "/");
if(cleanInfo.size() != 1){
for(int j=0; j < hist1DFunctions.size(); j++){
hist1DFunctions[j].SetCleanJet<Axis::X>(cleanInfo[0], cleanInfo[1]);
}
for(int j=0; j < hist2DFunctions.size(); j++){
hist2DFunctions[j].SetCleanJet<Axis::X>(cleanInfo[0], cleanInfo[1]);
hist2DFunctions[j].SetCleanJet<Axis::Y>(cleanInfo[0], cleanInfo[1]);
}
for(int j=0; j < cutFunctions.size(); j++){
cutFunctions[j].SetCleanJet<Axis::X>(cleanInfo[0], cleanInfo[1]);
}
for(int j=0; j < treeFunctions.size(); j++){
treeFunctions[j].SetCleanJet<Axis::X>(cleanInfo[0], cleanInfo[1]);
}
for(int j=0; j < CSVFunctions.size(); j++){
CSVFunctions[j].SetCleanJet<Axis::X>(cleanInfo[0], cleanInfo[1]);
}
}
//Get number of generated events
if(inputFile->GetListOfKeys()->Contains("nGen")){
nGen = RUtil::Get<TH1F>(inputFile.get(), "nGen")->Integral();
}
if(inputFile->GetListOfKeys()->Contains("xSec")){
xSec = RUtil::Get<TH1F>(inputFile.get(), "xSec")->GetBinContent(1);
}
if(inputFile->GetListOfKeys()->Contains("Lumi")){
lumi = RUtil::Get<TH1F>(inputFile.get(), "Lumi")->GetBinContent(1);
}
//Set all branch addresses needed for the event
bool passed = true;
bool isData = true;
//Calculate pile up weight histogram
std::shared_ptr<TH1F> pileUpWeight, pileUpWeightUp, pileUpWeightDown;
if(inputFile->GetListOfKeys()->Contains("puMC")){
isData = false;
std::shared_ptr<TH1F> puMC = RUtil::GetSmart<TH1F>(inputFile.get(), "puMC");
std::shared_ptr<TH1F> puReal = RUtil::GetSmart<TH1F>(inputFile.get(), "pileUp");
std::shared_ptr<TH1F> puRealUp = RUtil::GetSmart<TH1F>(inputFile.get(), "pileUpUp");
std::shared_ptr<TH1F> puRealDown = RUtil::GetSmart<TH1F>(inputFile.get(), "pileUpDown");
pileUpWeight.reset(static_cast<TH1F*>(puReal->Clone()));
pileUpWeightUp.reset(static_cast<TH1F*>(puRealUp->Clone()));
pileUpWeightDown.reset(static_cast<TH1F*>(puRealDown->Clone()));
pileUpWeight->Scale(1./pileUpWeight->Integral());
pileUpWeightUp->Scale(1./pileUpWeightUp->Integral());
pileUpWeightDown->Scale(1./pileUpWeightDown->Integral());
puMC->Scale(1./puMC->Integral());
pileUpWeight->Divide(puMC.get());
pileUpWeightUp->Divide(puMC.get());
pileUpWeightDown->Divide(puMC.get());
}
//Data driven scale factors
float sf = 1.;
if(!scaleFactors.empty()){
std::string fileName = StrUtil::Split(scaleFactors, "+")[0];
std::string process = StrUtil::Split(scaleFactors, "+")[1];
CSV scaleFactors(fileName, "r", "\t");
std::vector<std::string> processes = scaleFactors.GetColumn("Process");
sf = scaleFactors.Get<float>(VUtil::Find(processes, process).at(0), "Factor");
}
//Cutflow
std::shared_ptr<TH1F> cutflow = RUtil::GetSmart<TH1F>(inputFile.get(), "cutflow_" + channel);
cutflow->SetName("cutflow"); cutflow->SetTitle("cutflow");
cutflow->Scale(1./nGen);
for (int i = 0; i < inputTree->GetEntries(); ++i){
if(i % 100000 == 0 and i != 0){
std::cout << "Processed events: " << i << " (" << i/timer.Time() << " eve/s)" << std::endl;
}
//Set Entry
TreeFunction::SetEntry(i);
nTrueInter->GetBranch()->GetEntry(i);
//Multiply all common weights
float weight = xSec*lumi/nGen*sf;
if(pileUpWeight!=nullptr) weight *= pileUpWeight->GetBinContent(pileUpWeight->FindBin(*(float*)nTrueInter->GetValuePointer()));
//Check if event passed all cuts
passed=true;
for(int j=0; j < cutFunctions.size(); j++){
passed *= cutFunctions[j].GetPassed();
if(passed){
weight *= cutFunctions[j].GetWeight();
cutflow->Fill(cutFunctions[j].GetCutLabel().c_str(), weight);
}
else break;
}
if(!passed) continue;
//Fill nominal histogram
for(int j=0; j < hist1DFunctions.size(); j++){
hists1D[j]->Fill(hist1DFunctions[j].Get<Axis::X>(), weight);
}
for(int j=0; j < hist2DFunctions.size(); j++){
hists2D[j]->Fill(hist2DFunctions[j].Get<Axis::X>(), hist2DFunctions[j].Get<Axis::Y>(), weight);
}
//Fill histogram with systematic shifts
for(int syst = 0; syst < scaleSysts.size() - 1; syst++){
for(int shift = 0; shift < 2; shift++){
weight = xSec*lumi/nGen*sf;
if(pileUpWeight!=nullptr) weight *= pileUpWeight->GetBinContent(pileUpWeight->FindBin(*(float*)nTrueInter->GetValuePointer()));
for(int j=0; j < cutFunctions.size(); j++){
const std::vector<float>& systWeights = cutFunctions[j].GetSystWeight();
weight *= VUtil::At(systWeights, MUtil::RowMajIdx({scaleSysts.size() - 1, 2}, {syst, shift}));
}
for(int j=0; j < hist1DFunctions.size(); j++){
VUtil::At(hists1DSyst, MUtil::RowMajIdx({scaleSysts.size() - 1, 2, hist1DFunctions.size()}, {syst, shift, j}))->Fill(hist1DFunctions[j].Get<Axis::X>(), weight);
}
for(int j=0; j < hist2DFunctions.size(); j++){
VUtil::At(hists2DSyst, MUtil::RowMajIdx({scaleSysts.size() - 1, 2, hist2DFunctions.size()}, {syst, shift, j}))->Fill(hist2DFunctions[j].Get<Axis::X>(), hist2DFunctions[j].Get<Axis::Y>(), weight);
}
}
}
//Fill trees
for(int j=0; j < treeFunctions.size(); j++){
treeValues[j] = treeFunctions[j].Get<Axis::X>();
}
if(outTree != nullptr) outTree->Fill();
//Fill CSV file
if(frame != nullptr){
std::vector<float> values;
for(int j=0; j < CSVFunctions.size(); j++){
values.push_back(CSVFunctions[j].Get<Axis::X>());
}
frame->AddColumn(values);
}
}
//Write all histograms and delete everything
for(std::shared_ptr<TH1F>& hist: VUtil::Merge(hists1D, hists1DSyst)){
hist->GetDirectory()->cd();
hist->Write();
std::cout << "Saved histogram: '" << hist->GetName() << "' with " << hist->GetEntries() << " entries" << std::endl;
}
for(std::shared_ptr<TH2F>& hist: VUtil::Merge(hists2D, hists2DSyst)){
hist->GetDirectory()->cd();
hist->Write();
std::cout << "Saved histogram: '" << hist->GetName() << "' with " << hist->GetEntries() << " entries" << std::endl;
}
hist1DFunctions.clear();
cutFunctions.clear();
if(outTree != nullptr){
outTree->Write();
std::cout << "Saved tree: '" << outTree->GetName() << "' with " << outTree->GetEntries() << " entries" << std::endl;
std::cout << "Branches which are saved in tree:" << std::endl;
for(std::string& branchName: branchNames){
std::cout << branchName << std::endl;
}
}
//Remove empty bins and write cutflow
int nonEmpty = 0;
for(int i=0; i < cutflow->GetNbinsX(); i++){
if(std::string(cutflow->GetXaxis()->GetBinLabel(i)) != "") nonEmpty++;
}
VUtil::At(outFiles, 0)->cd();
cutflow->SetAxisRange(0, nonEmpty);
cutflow->Write();
if(frame!=nullptr){
frame->WriteCSV(StrUtil::Join("/", outDir, outFile));
}
std::cout << "Closed output file: '" << outFile << "'" << std::endl;
std::cout << "Time passed for complete processing: " << timer.Time() << " s" << std::endl;
}
<file_sep>/Analysis/src/treeslimmer.cc
#include <ChargedAnalysis/Analysis/include/treeslimmer.h>
TreeSlimmer::TreeSlimmer(const std::string& inputFile, const std::string& inputChannel) :
inputFile(inputFile),
inputChannel(inputChannel){}
void TreeSlimmer::DoSlim(const std::string outputFile, const std::string outChannel, const std::vector<std::string>& cuts, const int& start, const int& end){
//Get input tree
std::shared_ptr<TFile> inFile(TFile::Open(inputFile.c_str(), "READ"));
std::shared_ptr<TTree> inTree(inFile->Get<TTree>(inputChannel.c_str()));
std::cout << "Read file: '" << inputFile << "'" << std::endl;
std::cout << "Read tree '" << inputChannel << "'" << std::endl;
//Prepare output tree and cutflow
std::shared_ptr<TFile> outFile(TFile::Open(outputFile.c_str(), "RECREATE"));
std::shared_ptr<TTree> outTree(inTree->CloneTree(0, "fast"));
outTree->SetName(outChannel.c_str());
outTree->SetTitle(outChannel.c_str());
TH1F* cutflow(inFile->Get<TH1F>(("cutflow_" + inputChannel).c_str()));
cutflow->SetDirectory(outFile.get());
cutflow->SetName(("cutflow_" + outChannel).c_str());
cutflow->SetTitle(("cutflow_" + outChannel).c_str());
//Prepare functions for cut
TreeParser parser;
std::vector<TreeFunction> cutFuncs;
for(const std::string cut: cuts){
TreeFunction func(inFile, inputChannel);
parser.GetParticle(cut, func);
parser.GetFunction(cut, func);
parser.GetCut(cut, func);
cutFuncs.push_back(func);
}
//Get lumi and xsec for weighting cut flow
float xSec = 1., lumi = 1.;
if(inFile->GetListOfKeys()->Contains("xSec")){
xSec = inFile->Get<TH1F>("xSec")->GetBinContent(1);
}
if(inFile->GetListOfKeys()->Contains("Lumi")){
lumi = inFile->Get<TH1F>("Lumi")->GetBinContent(1);
}
//Loop
bool passed = true;
for(int i = start; i < end; i++){
if(i % 100000 == 0 and i != 0){
std::cout << "Processed events: " << i << std::endl;
}
passed = true;
TreeFunction::SetEntry(i);
for(TreeFunction& cut: cutFuncs){
passed = cut.GetPassed();
if(passed) cutflow->Fill(cut.GetCutLabel().c_str(), xSec*lumi);
else break;
}
if(passed){
inTree->GetEntry(i);
outTree->Fill();
}
}
//Write everything
outTree->Write();
cutflow->Write();
TList* keys = static_cast<TList*>(inFile->GetListOfKeys());
for(int i=0; i < keys->GetSize(); i++){
bool skipKey = false;
TObject* obj(inFile->Get(keys->At(i)->GetName()));
if(obj->InheritsFrom(TTree::Class())) continue;
if(Utils::Find<std::string>(obj->GetName(), "cutflow") == -1) obj->Write();
}
std::cout << "Saved tree: '" << outTree->GetName() << "' with " << outTree->GetEntries() << " entries" << std::endl;
}
<file_sep>/Utility/src/bimap.cc
#include <vector>
#include <tuple>
#include <algorithm>
#include <sstream>
#include <iostream>
#include <initializer_list>
namespace Utils{
template <class Key, class Value>
class Bimap {
private:
std::vector<Key> keys;
std::vector<Value> values;
public:
Bimap(){}
Bimap(const std::initializer_list<std::pair<Key, Value>>& mapValues){
for(const std::pair<Key, Value> item: mapValues){
keys.push_back(item.first);
values.push_back(item.second);
}
}
void Add(const Key& key, const Value& value){
key.push_back(key);
value.push_back(value);
}
Value operator[](const Key& key){
typename std::vector<Key>::iterator pos = std::find(keys.begin(), keys.end(), key);
if(pos == keys.end()){
std::stringstream notFound;
notFound << key;
throw std::out_of_range("Key not found: '" + notFound.str() + "'");
}
return values[pos - keys.begin()];
}
Key operator[](const Value& value){
typename std::vector<Value>::iterator pos = std::find(values.begin(), values.end(), value);
if(pos == values.end()){
std::stringstream notFound;
notFound << value;
throw std::out_of_range("Value not found: '" + notFound.str() + "'");
}
return keys[pos - values.begin()];
}
};
};
<file_sep>/Analysis/src/treeparser.cc
#include <ChargedAnalysis/Analysis/include/treeparser.h>
TreeParser::TreeParser(){}
void TreeParser::GetFunction(const std::string& parameter, TreeFunction& func){
if(Utils::Find<std::string>(parameter, "f:") == -1) throw std::runtime_error("No function key 'f' in '" + parameter + "'");
std::vector lines = Utils::SplitString<std::string>(parameter, "/");
lines.erase(std::remove_if(lines.begin(), lines.end(), [&](std::string l){return Utils::Find<std::string>(l, "f:") == -1;}), lines.end());
for(const std::string line : lines){
std::string funcName; std::string value = ""; bool isX = true;
std::string funcLine = line.substr(line.find("f:")+2);
for(std::string& funcParam: Utils::SplitString<std::string>(funcLine, ",")){
std::vector<std::string> fInfo = Utils::SplitString<std::string>(funcParam, "=");
if(fInfo[0] == "n") funcName = fInfo[1];
else if(fInfo[0] == "v") value = fInfo[1];
else if(fInfo[0] == "ax") isX = fInfo[1] != "y";
else throw std::runtime_error("Invalid key '" + fInfo[0] + "' in parameter '" + funcLine + "'");
}
if(isX) func.SetFunction<Axis::X>(funcName, value);
else{
func.SetYAxis();
func.SetFunction<Axis::Y>(funcName, value);
}
}
}
void TreeParser::GetParticle(const std::string& parameter, TreeFunction& func){
if(Utils::Find<std::string>(parameter, "p:") == -1) return;
std::vector lines = Utils::SplitString<std::string>(parameter, "/");
lines.erase(std::remove_if(lines.begin(), lines.end(), [&](std::string l){return Utils::Find<std::string>(l, "p:") == -1;}), lines.end());
for(const std::string line : lines){
std::string partLine = line.substr(line.find("p:")+2);
std::string part = ""; std::string wp = ""; int idx = 0; bool isX = true; int pos = 1; int genMother = -1.;
for(const std::string& partParam: Utils::SplitString<std::string>(partLine, ",")){
std::vector<std::string> pInfo = Utils::SplitString<std::string>(partParam, "=");
if(pInfo[0] == "n") part = pInfo[1];
else if (pInfo[0] == "wp") wp = pInfo[1];
else if (pInfo[0] == "i") idx = std::atoi(pInfo[1].c_str());
else if (pInfo[0] == "gen") genMother = std::atoi(pInfo[1].c_str());
else if (pInfo[0] == "pos") pos = std::atoi(pInfo[1].c_str());
else if(pInfo[0] == "ax") isX = pInfo[1] != "y";
else throw std::runtime_error("Invalid key '" + pInfo[0] + "' in parameter '" + partLine + "'");
}
if(pos == 1){
if(isX) func.SetP1<Axis::X>(part, idx, wp, genMother);
else{
func.SetYAxis();
func.SetP1<Axis::Y>(part, idx, wp, genMother);
}
}
if(pos == 2){
if(isX) func.SetP2<Axis::X>(part, idx, wp, genMother);
else{
func.SetYAxis();
func.SetP2<Axis::Y>(part, idx, wp, genMother);
}
}
}
}
void TreeParser::GetCut(const std::string& parameter, TreeFunction& func){
if(Utils::Find<std::string>(parameter, "c:") == -1) throw std::runtime_error("No cut key 'c' in '" + parameter + "'");
std::string comp; float compValue = -999.;
std::string cutLine = parameter.substr(parameter.find("c:")+2, parameter.substr(parameter.find("c:")).find("/")-2);
for(std::string& cutParam: Utils::SplitString<std::string>(cutLine, ",")){
std::vector<std::string> cInfo = Utils::SplitString<std::string>(cutParam, "=");
if(cInfo[0] == "n") comp = cInfo[1];
else if(cInfo[0] == "v") compValue = std::stof(cInfo[1]);
else throw std::runtime_error("Invalid key '" + cInfo[0] + "' in parameter '" + cutLine + "'");
}
func.SetCut(comp, compValue);
}
void TreeParser::GetBinning(const std::string& parameter, TH1* hist){
if(Utils::Find<std::string>(parameter, "h:") == -1) throw std::runtime_error("No hist key 'h' in '" + parameter + "'");
std::string histLine = parameter.substr(parameter.find("h:")+2, parameter.substr(parameter.find("h:")).find("/")-2);
int xBins = 30, yBins = -1.;
float xlow = 0, xhigh = 1, ylow = 0, yhigh = 1;
for(std::string& histParam: Utils::SplitString<std::string>(histLine, ",")){
std::vector<std::string> hInfo = Utils::SplitString<std::string>(histParam, "=");
if(hInfo[0] == "nxb") xBins = std::stof(hInfo[1]);
else if(hInfo[0] == "xl") xlow = std::stof(hInfo[1]);
else if(hInfo[0] == "xh") xhigh = std::stof(hInfo[1]);
else if(hInfo[0] == "nyb") yBins = std::stof(hInfo[1]);
else if(hInfo[0] == "yl") ylow = std::stof(hInfo[1]);
else if(hInfo[0] == "yh") yhigh = std::stof(hInfo[1]);
else throw std::runtime_error("Invalid key '" + hInfo[0] + " in parameter '" + histLine + "'");
}
if(yBins == -1.) hist->SetBins(xBins, xlow, xhigh);
else hist->SetBins(xBins, xlow, xhigh, yBins, ylow, yhigh);
}
<file_sep>/Analysis/src/ntuplereader.cc
#include <ChargedAnalysis/Analysis/include/ntuplereader.h>
bool Bigger(const float& v1, const float& v2){return v1 != -999 and v1 >= v2;}
bool BiggerAbs(const float& v1, const float& v2){return v1 != -999 and std::abs(v1) >= v2;}
bool Smaller(const float& v1, const float& v2){return v1 != -999 and v1 <= v2;}
bool SmallerAbs(const float& v1, const float& v2){return v1 != -999 and std::abs(v1) <= v2;}
bool Equal(const float& v1, const float& v2){return v1 != -999 and v1 == v2;}
bool EqualAbs(const float& v1, const float& v2){return v1 != -999 and std::abs(v1) == v2;}
//Constructor
NTupleReader::NTupleReader(){}
NTupleReader::NTupleReader(const std::shared_ptr<TTree>& inputTree, const int& era) : inputTree(inputTree), era(era) {
pt::json_parser::read_json(StrUtil::Merge(std::getenv("CHDIR"), "/ChargedAnalysis/Analysis/data/particle.json"), partInfo);
pt::json_parser::read_json(StrUtil::Merge(std::getenv("CHDIR"), "/ChargedAnalysis/Analysis/data/function.json"), funcInfo);
}
//Read out vector like branch at index idx
float NTupleReader::GetEntry(TLeaf* leaf, const int& idx){
if(idx == -1) return RUtil::GetEntry<float>(leaf, entry);
try{
return RUtil::GetVecEntry<float>(leaf, entry).at(idx);
}
catch(...){
return -999.;
}
}
//Read out vector like branch at index idx with wished WP
float NTupleReader::GetEntryWithWP(TLeaf* leaf, std::vector<std::shared_ptr<CompiledFunc>>& cuts, const int& idx, const std::size_t& hash){
const std::vector<float> data = RUtil::GetVecEntry<float>(leaf, entry);
if(idx >= data.size()) return -999.;
//Check if idx already calculated for this particle
if(idxCache.count(hash) and idxCache.at(hash).count(idx)) return data.at(idxCache.at(hash).at(idx));
int wpIdx = -1, counter = -1;
//Loop over all entries in collection
for(std::size_t i = 0; i < data.size(); ++i){
bool passed = true;
//Check if all id cuts are passed
for(std::shared_ptr<CompiledFunc>& cut : cuts){
if(i == 0) cut->Reset();
if(passed) passed = passed && cut->GetPassed();
cut->Next();
}
if(passed) ++counter;
if(counter == idx){
wpIdx = i;
break;
}
}
if(wpIdx != -1){
idxCache[hash][idx] = wpIdx;
return data.at(wpIdx);
}
else return -999.;
}
std::shared_ptr<CompiledFunc> NTupleReader::compileBranchReading(pt::ptree& func, pt::ptree& part){
std::shared_ptr<CompiledFunc> bindedFunc;
//Labels names
if(func.get_optional<std::string>("axis-name") and part.get_optional<std::string>("axis-name")){
func.put("axis-name", StrUtil::Replace(func.get<std::string>("axis-name"), "[P]", particles.at(0).get<std::string>("axis-name")));
func.put("hist-name", StrUtil::Replace(func.get<std::string>("hist-name"), "[P]", particles.at(0).get<std::string>("hist-name")));
}
std::string branchName = func.get<std::string>("branch");
if(part.get_optional<std::string>("name")){
branchName = StrUtil::Replace(branchName, "[P]", part.get<std::string>("name"));
}
//Compile vector branch with WP
if(part.get_optional<int>("index") && (part.get_child_optional("identification") or part.get_child_optional("requirements"))){
std::vector<std::shared_ptr<CompiledFunc>> cuts;
//Make part without requirements so functions can be used as iterators
pt::ptree pNoWP = part;
if(pNoWP.get_optional<int>("index")) pNoWP.put("index", -1);
pNoWP.put("hash", 0);
pNoWP.erase("requirements");
pNoWP.erase("identification");
//Loop over all needed branches and create bool lambda checking the WP criteria
if(part.get_child_optional("identification")){
for(const std::string& idName : NTupleReader::GetInfo(part.get_child("identification"))){
//Get ID branch as iterator
pt::ptree funcID;
funcID.put("branch", idName);
std::shared_ptr<CompiledFunc> cutFunc = this->compileBranchReading(funcID, pNoWP);
bool checkAbs = part.get_optional<bool>("identification." + idName + ".absolute-values") ? true : false;
//Check which operation to do
if(part.get<std::string>("identification." + idName + ".compare") == "=="){
cutFunc->AddCut(checkAbs? &EqualAbs : &Equal, part.get<float>("identification." + idName + ".wp"));
}
else if(part.get<std::string>("identification." + idName + ".compare") == ">="){
cutFunc->AddCut(checkAbs? &BiggerAbs : &Bigger, part.get<float>("identification." + idName + ".wp"));
}
else if(part.get<std::string>("identification." + idName + ".compare") == "<="){
cutFunc->AddCut(checkAbs? &SmallerAbs : &Smaller, part.get<float>("identification." + idName + ".wp"));
}
else throw std::runtime_error(StrUtil::PrettyError(std::experimental::source_location::current(), "Unknown cut operator: '", part.get<std::string>("identification." + idName + ".compare"), "'!"));
cuts.push_back(cutFunc);
}
}
//Loop over all other required cuts as bool lambda
if(part.get_child_optional("requirements")){
for(const std::string& fAlias : NTupleReader::GetInfo(part.get_child("requirements"))){
std::shared_ptr<CompiledFunc> cutFunc;
std::vector<pt::ptree> parts;
std::string fName = NTupleReader::GetName(funcInfo, fAlias);
if(fName == "") throw std::runtime_error(StrUtil::PrettyError(std::experimental::source_location::current(), "Unknown function alias: '", fAlias, "'!"));
pt::ptree fInfo = funcInfo.get_child(fName);
//Loop over all particles needed by the cut
for(const std::string& pAlias : NTupleReader::GetInfo(part.get_child("requirements." + fAlias + ".particles"))){
//Use particle given by the user
if(pAlias == "THIS") parts.push_back(pNoWP);
//Use external defined particle
else{
std::string pInfoPath;
//Check if there are channel specific particles
std::vector<std::string> chanPrefix = NTupleReader::GetInfo(part.get_child(StrUtil::Join(".", "requirements", fAlias, "particles", pAlias)));
if(chanPrefix.at(0) != ""){
for(const std::string& chan : chanPrefix){
if(!StrUtil::Find(inputTree->GetName(), chan).empty()) pInfoPath = StrUtil::Join(".", "requirements", fAlias, "particles", pAlias, chan);
}
}
else pInfoPath = StrUtil::Join(".", "requirements", fAlias, "particles", pAlias);
//Vector with partAlias, part index and part WP
std::vector<std::string> pInfo = NTupleReader::GetInfo(part.get_child(pInfoPath), false);
std::string pName = NTupleReader::GetName(partInfo, pInfo.at(0));
if(pName == "") throw std::runtime_error(StrUtil::PrettyError(std::experimental::source_location::current(), "Unknown particle alias: '", pInfo.at(0), "'!"));
//Particle configuration
parts.push_back(partInfo.get_child(pName));
if(!parts.back().get_optional<bool>("non-vector")) parts.back().put("index", std::atoi(pInfo.at(1).c_str()) - 1);
parts.back().put("name", parts.back().get_optional<std::string>("branch-prefix") ? parts.back().get<std::string>("branch-prefix") : pName);
parts.back().put("hash", std::hash<std::string>()(parts.back().get<std::string>("alias") + pInfo.at(2)));
//Set proper cuts for WP of particles if needed
if(parts.back().get_child_optional("identification") and pInfo.at(2) != ""){
for(const std::string& idName : NTupleReader::GetInfo(parts.back().get_child("identification"))){
std::string wpPath = StrUtil::Join(".", "identification", idName, "WP", pInfo.at(2));
std::string wpPathWithEra = StrUtil::Join(".", "identification", idName, "WP", pInfo.at(2), era);
parts.back().put(StrUtil::Merge("identification.", idName, ".wp"), parts.back().get_optional<float>(wpPathWithEra) ? parts.back().get<float>(wpPathWithEra) : parts.back().get<float>(wpPath));
}
}
else parts.back().erase("identification");
}
}
if(fInfo.get_child_optional("branch")){
cutFunc = this->compileBranchReading(fInfo, pNoWP);
}
else if(fInfo.get_child_optional("need")){
cutFunc = this->compileCustomFunction(fInfo, parts);
}
else throw std::runtime_error(StrUtil::PrettyError(std::experimental::source_location::current(), "Function '", fAlias, "' has neither 'branch' nor 'need' configured!"));
//Check which operation to do
if(part.get<std::string>("requirements." + fAlias + ".compare") == "=="){
cutFunc->AddCut(&Equal, part.get<float>("requirements." + fAlias + ".cut"));
}
else if(part.get<std::string>("requirements." + fAlias + ".compare") == ">="){
cutFunc->AddCut(&Bigger, part.get<float>("requirements." + fAlias + ".cut"));
}
else if(part.get<std::string>("requirements." + fAlias + ".compare") == "<="){
cutFunc->AddCut(&Smaller, part.get<float>("requirements." + fAlias + ".cut"));
}
else throw std::runtime_error(StrUtil::PrettyError(std::experimental::source_location::current(), "Unknown cut operator: '", part.get<std::string>("requirements." + fAlias + ".compare"), "'!"));
cuts.push_back(cutFunc);
}
}
//Bind everything together
bindedFunc = std::make_shared<CompiledFunc>(&NTupleReader::GetEntryWithWP, RUtil::Get<TLeaf>(inputTree.get(), branchName), cuts, part.get<int>("index"), part.get<std::size_t>("hash"), part.get<int>("index") == -1);
}
//Compile vector like branch
else if(part.get_optional<int>("index")){
bindedFunc = std::make_shared<CompiledFunc>(&NTupleReader::GetEntry, RUtil::Get<TLeaf>(inputTree.get(), branchName), part.get<int>("index"), part.get<int>("index") == -1);
}
//Compile non-vector like branch
else{
bindedFunc = std::make_shared<CompiledFunc>(&NTupleReader::GetEntry, RUtil::Get<TLeaf>(inputTree.get(), branchName), -1);
}
return bindedFunc;
}
std::shared_ptr<CompiledFunc> NTupleReader::compileCustomFunction(pt::ptree& func, std::vector<pt::ptree>& parts){
std::shared_ptr<CompiledFunc> bindedFunc;
Particles partValues;
//Loop over all needed subfunctions/particles
for(const std::string& fAlias: NTupleReader::GetInfo(func.get_child("need"))){
//Check if sub function configured
std::string fName = NTupleReader::GetName(funcInfo, fAlias);
if(fName == "") throw std::runtime_error(StrUtil::PrettyError(std::experimental::source_location::current(), "Unknown function alias: '", fAlias, "'!"));
//Loop over all needed particles
std::vector<std::string> pAliases = NTupleReader::GetInfo(func.get_child("need." + fAlias), false);
if(pAliases.size() > parts.size()){
throw std::runtime_error(StrUtil::PrettyError(std::experimental::source_location::current(), "Function '", func.get<std::string>("alias"), "' needs '", pAliases.size(), "' particles, but '", parts.size(), "' are given!"));
}
for(int i = 0; i < pAliases.size(); ++i){
func.put("axis-name", StrUtil::Replace(func.get<std::string>("axis-name"), "[" + pAliases.at(i) + "]", parts.at(i).get<std::string>("axis-name")));
func.put("hist-name", StrUtil::Replace(func.get<std::string>("hist-name"), "[" + pAliases.at(i) + "]", parts.at(i).get<std::string>("hist-name")));
partValues[{pAliases.at(i), fAlias}] = this->compileBranchReading(funcInfo.get_child(fName), parts.at(i));
}
}
//Bind all sub function to the wished function
bindedFunc = std::make_shared<CompiledCustomFunc>(Properties::properties.at(func.get<std::string>("alias")), partValues);
return bindedFunc;
}
void NTupleReader::AddParticle(const std::string& pAlias, const int& idx, const std::string& wp, const std::experimental::source_location& location){
std::string pName = NTupleReader::GetName(partInfo, pAlias);
if(pName != ""){
pt::ptree particle = partInfo.get_child(pName);
//Set neccesary part infos
if(!particle.get_optional<bool>("non-vector")) particle.put("index", idx - 1);
particle.put("name", particle.get_optional<std::string>("branch-prefix") ? particle.get<std::string>("branch-prefix") : pName);
particle.put("hist-name", StrUtil::Replace(particle.get<std::string>("hist-name"), "[WP]", wp));
particle.put("axis-name", StrUtil::Replace(particle.get<std::string>("axis-name"), "[WP]", wp));
particle.put("hash", std::hash<std::string>()(particle.get<std::string>("alias") + wp));
if(idx == 0){
particle.put("axis-name", StrUtil::Replace(particle.get<std::string>("axis-name"), "[I]", ""));
particle.put("hist-name", StrUtil::Replace(particle.get<std::string>("hist-name"), "[I]", ""));
}
else{
particle.put("axis-name", StrUtil::Replace(particle.get<std::string>("axis-name"), "[I]", idx));
particle.put("hist-name", StrUtil::Replace(particle.get<std::string>("hist-name"), "[I]", idx));
}
//Set proper cuts for WP of particles if needed
if(particle.get_child_optional("identification") and wp != ""){
for(const std::string& idName : NTupleReader::GetInfo(particle.get_child("identification"))){
std::string wpPath = StrUtil::Join(".", "identification", idName, "WP", wp);
std::string wpPathWithEra = StrUtil::Join(".", "identification", idName, "WP", wp, era);
particle.put(StrUtil::Merge("identification.", idName, ".wp"), particle.get_optional<float>(wpPathWithEra) ? particle.get<float>(wpPathWithEra) : particle.get<float>(wpPath));
}
}
else particle.erase("identification");
particles.push_back(particle);
}
else throw std::runtime_error(StrUtil::PrettyError(location, "Unknown particle alias: '", pAlias, "'!"));
};
void NTupleReader::AddFunction(const std::string& fAlias, const std::vector<std::string>& values, const std::experimental::source_location& location){
std::string fName = NTupleReader::GetName(funcInfo, fAlias);
//Check if function configured
if(fName != ""){
function.insert(function.end(), funcInfo.get_child(fName).begin(), funcInfo.get_child(fName).end());
for(const std::string& value : values){
function.put("axis-name", StrUtil::Replace(function.get<std::string>("axis-name"), "[V]", value));
function.put("hist-name", StrUtil::Replace(function.get<std::string>("hist-name"), "[V]", value));
function.put("branch", StrUtil::Replace(function.get<std::string>("branch"), "[V]", value));
}
}
else throw std::runtime_error(StrUtil::PrettyError(location, "Unknown function alias: '", fAlias, "'!"));
};
void NTupleReader::AddFunctionByBranchName(const std::string& branchName, const std::experimental::source_location& location){
//Check if function configured
function.put("branch", branchName);
function.put("axis-name", "");
function.put("hist-name", "");
};
void NTupleReader::AddCut(const float& value, const std::string& op, const std::experimental::source_location& location){
function.put("cut-op", op);
function.put("cut-value", value);
}
void NTupleReader::Compile(const std::experimental::source_location& location){
isCompiled = true;
if(function.empty()){
throw std::runtime_error(StrUtil::PrettyError(location, "No function information avaible! Call 'AddFunction' before compiling!"));
}
//Only read out branch value with particle
if(function.get_child_optional("branch") and particles.size() > 0){
func = this->compileBranchReading(function, particles.at(0));
}
//Only read out branch value without particle
else if(function.get_child_optional("branch")){
pt::ptree dummy;
func = this->compileBranchReading(function, dummy);
}
//Compile external functions
else if(function.get_child_optional("need")){
func = this->compileCustomFunction(function, particles);
}
else{
throw std::runtime_error(StrUtil::PrettyError(location, "Function '", function.get<std::string>("alias"), "' has neither 'branch' nor 'need' configured!"));
}
//Check if also cut should be compiled
if(function.get_optional<std::string>("cut-value")){
if(function.get<std::string>("cut-op") == "=="){
func->AddCut(&Equal, function.get<float>("cut-value"));
}
else if(function.get<std::string>("cut-op") == ">="){
func->AddCut(&Bigger, function.get<float>("cut-value"));
}
else if(function.get<std::string>("cut-op") == "<="){
func->AddCut(&Smaller, function.get<float>("cut-value"));
}
else throw std::runtime_error(StrUtil::PrettyError(location, "Unknown cut operator: '", function.get<std::string>("cut-op"), "'!"));
function.put("cut-name", StrUtil::Replace("[] [] []", "[]", function.get<std::string>("axis-name"), function.get<std::string>("cut-op"), function.get<std::string>("cut-value")));
}
}
float NTupleReader::Get(){
if(isCompiled) return func->Get();
else throw std::runtime_error(StrUtil::PrettyError(std::experimental::source_location::current(), "Use the 'Compile' function before calling the 'Get' function!"));
}
bool NTupleReader::GetPassed(){
if(isCompiled) return func->GetPassed();
else throw std::runtime_error(StrUtil::PrettyError(std::experimental::source_location::current(), "Use the 'Compile' function before calling the 'GetPassed' function!"));
}
std::string NTupleReader::GetHistName(){
if(isCompiled) return function.get<std::string>("hist-name");
else throw std::runtime_error(StrUtil::PrettyError(std::experimental::source_location::current(), "Use the 'Compile' function before calling the 'GetHistName' function!"));
}
std::string NTupleReader::GetAxisLabel(){
if(isCompiled) return function.get<std::string>("axis-name");
else throw std::runtime_error(StrUtil::PrettyError(std::experimental::source_location::current(), "Use the 'Compile' function before calling the 'GetAxisLabel' function!"));
}
std::string NTupleReader::GetCutName(){
if(isCompiled) return function.get<std::string>("cut-name");
else throw std::runtime_error(StrUtil::PrettyError(std::experimental::source_location::current(), "Use the 'Compile' function before calling the 'GetCutName' function!"));
}
void NTupleReader::Next(){func->Next();}
void NTupleReader::Reset(){func->Reset();}
////// Custom functions of Properties namespace used by the NTupleReader
float Properties::HT(Particles& parts){
float sum = 0.;
parts.at({"P", "pt"})->Reset();
while(true){
const float& value = parts.at({"P", "pt"})->Get();
if(value == -999.) break;
parts.at({"P", "pt"})->Next();
sum += value;
}
return sum;
}
float Properties::dR(Particles& parts){
return std::sqrt(std::pow(parts.at({"P1", "eta"})->Get() - parts.at({"P2", "eta"})->Get(), 2) + std::pow(parts.at({"P1", "phi"})->Get() - parts.at({"P2", "phi"})->Get(), 2));
}
float Properties::dPhi(Particles& parts){
return std::acos(std::cos(parts.at({"P1", "phi"})->Get())*std::cos(parts.at({"P2", "phi"})->Get()) + std::sin(parts.at({"P1", "phi"})->Get())*std::sin(parts.at({"P2", "phi"})->Get()));
}
float Properties::diCharge(Particles& parts){
return parts.at({"P1", "charge"})->Get() * parts.at({"P2", "charge"})->Get();
}
float Properties::NParticles(Particles& parts){
int count = 0;
parts.at({"P", "pt"})->Reset();
while(true){
if(parts.at({"P", "pt"})->Get() != -999.) ++count;
else break;
parts.at({"P", "pt"})->Next();
}
return count;
}
<file_sep>/Analysis/src/plotterPostfit.cc
#include <ChargedAnalysis/Analysis/include/plotterPostfit.h>
PlotterPostfit::PlotterPostfit() : Plotter(){}
PlotterPostfit::PlotterPostfit(std::string &limitDir, int &mass, std::vector<std::string> &channels) :
Plotter(),
limitDir(limitDir),
mass(mass),
channels(channels){
chanToDir = {{"mu4j", "Muon4J"}, {"mu2j1f", "Muon2J1F"}, {"mu2f", "Muon2F"}, {"e4j", "Ele4J"}, {"e2j1f", "Ele2J1F"}, {"e2f", "Ele2F"}};
for(std::string chan: channels){
backgrounds[chan] = std::vector<TH1F*>();
}
}
void PlotterPostfit::ConfigureHists(){
//Lambda function for sorting Histograms
std::function<bool(TH1F*,TH1F*)> sortFunc = [](TH1F* hist1, TH1F* hist2){return hist1->Integral() < hist2->Integral();};
for(std::string chan: channels){
//Open file with Postfit shapes
TFile* file = TFile::Open((limitDir + "/" + std::to_string(mass) + "/fitshapes.root").c_str());
TDirectory* dir = (TDirectory*)file->Get((chan + "_postfit").c_str());
TList* keys = dir->GetListOfKeys();
//Configure all histograms
for(int i=0; i < keys->GetSize(); i++){
std::string processName = std::string(keys->At(i)->GetName());
TH1F* hist = (TH1F*)dir->Get(processName.c_str());
if(processName == "HPlus"){
hist->SetLineWidth(2);
hist->SetLineColor(kBlack);
hist->SetName(("H^{#pm}_{" + std::to_string(mass) + "}+h_{100}").c_str());
signals[chan] = hist;
}
else if(processName == "TotalBkg"){
hist->SetFillStyle(3354);
hist->SetFillColorAlpha(kBlack, 0.8);
hist->SetMarkerColor(kBlack);
hist->SetName("Bkg. unc.");
errorBand[chan] = hist;
max = max < hist->GetMaximum() ? hist->GetMaximum() : max;
}
else if(processName != "data_obs" and processName != "TotalProcs" and processName != "TotalSig"){
hist->SetFillStyle(1001);
hist->SetFillColor(colors.at(processName));
hist->SetLineColor(colors.at(processName));
hist->SetName(processName.c_str());
backgrounds[chan].push_back(hist);
}
}
std::sort(backgrounds[chan].begin(), backgrounds[chan].end(), sortFunc);
}
}
void PlotterPostfit::Draw(std::vector<std::string> &outdirs){
//Set Style
PUtil::SetStyle();
//Define canvas and pads
TCanvas* canvas = new TCanvas("canvas", "canvas", 1400, 800);
TPad* legendpad = new TPad("legendpad", "legendpad", 0.91, 0.25, 1., 0.9);
TLegend* legend = new TLegend(0.15, 0.2, 0.75, 0.8);
for(unsigned int i=0; i < channels.size(); i++){
canvas->cd();
float padStart = i == 0 ? 0.05 - 0.3*(0.85/6.) + 0.85/6.*i: 0.05 + 0.85/6.*i;
float padEnd= 0.05 + 0.85/6.*(i+1);
//Draw Tpad
TPad* pad = new TPad(("pad_" + channels[i]).c_str(), ("pad_" + channels[i]).c_str(), padStart, .2 , padEnd, 1.);
TPad* pullpad = new TPad("pullpad", "pullpad", padStart, 0.0 , padEnd, .2);
pullpad->SetTopMargin(0.05);
pullpad->SetBottomMargin(0.15);
for(TPad* p: {pad, pullpad}){
p->SetLeftMargin(0.);
p->SetRightMargin(0.);
if(i==0){
p->SetLeftMargin(0.3);
}
}
pad->Draw();
pad->cd();
pad->SetLogy(1);
//Fill THStack;
THStack* stack = new THStack(("channel_" + channels[i]).c_str(), ("stack_" + channels[i]).c_str());
for(TH1F* hist: backgrounds[channels[i]]){
if(i==0){
legend->AddEntry(hist, hist->GetName(), "F");
}
//Fill sum of bkg hist and THStack
stack->Add(hist);
}
stack->Draw("HIST");
stack->SetMinimum(1e-1);
stack->SetMaximum(max*2);
stack->GetXaxis()->SetNdivisions(5);
stack->GetXaxis()->SetTickLength(0.01);
if(i==0){
stack->GetYaxis()->SetLabelSize(0.09);
stack->GetXaxis()->SetLabelSize(0.09);
stack->GetXaxis()->SetLabelOffset(-0.03);
stack->GetYaxis()->SetTitle("Events");
stack->GetYaxis()->SetTitleSize(0.1);
}
else if(i!=0){
stack->GetXaxis()->SetLabelSize(0.12);
stack->GetXaxis()->SetLabelOffset(-0.055);
stack->GetYaxis()->SetLabelSize(0);
stack->GetYaxis()->SetAxisColor(0,0);
}
if(i+1==channels.size()){
stack->GetXaxis()->SetTitleSize(0.12);
stack->GetXaxis()->SetTitle(signals[channels[i]]->GetXaxis()->GetTitle());
stack->GetXaxis()->SetTitleOffset(0.35);
}
errorBand[channels[i]]->Draw("SAME E2");
signals[channels[i]]->Draw("HIST SAME");
if(i==0){
legend->AddEntry(signals[channels[i]], signals[channels[i]]->GetName(), "L");
legend->AddEntry(errorBand[channels[i]], errorBand[channels[i]]->GetName(), "F");
}
TLatex* chanHeader = new TLatex();
chanHeader->SetTextSize(i==0? 0.089 : 0.11);
chanHeader->DrawLatexNDC(i ==0? 0.33 : 0.05, 0.87, PUtil::GetChannelTitle(channels[i]).c_str());
canvas->cd();
pullpad->Draw();
pullpad->cd();
TH1F* pullErrorband = (TH1F*)errorBand[channels[i]]->Clone();
pullErrorband->Divide(errorBand[channels[i]]);
pullErrorband->GetXaxis()->SetNdivisions(5);
pullErrorband->GetYaxis()->SetNdivisions(5);
pullErrorband->GetYaxis()->SetLabelSize(0.15);
pullErrorband->GetXaxis()->SetLabelSize(0.15);
pullErrorband->GetXaxis()->SetTitle("Pull");
pullErrorband->SetMinimum(0.5);
pullErrorband->SetMaximum(1.5);
pullErrorband->SetTitleSize(0., "X");
if(i==0){
pullErrorband->GetYaxis()->SetTitle("Pull");
pullErrorband->GetYaxis()->SetTitleSize(0.17);
pullErrorband->GetYaxis()->SetTitleOffset(0.8);
}
else if(i!=0){
pullErrorband->GetYaxis()->SetLabelSize(0);
pullErrorband->GetYaxis()->SetAxisColor(0,0);
}
pullErrorband->Draw("E2");
}
canvas->cd();
TLatex* cms = new TLatex();
cms->SetTextFont(62);
cms->SetTextSize(0.04);
cms->DrawLatexNDC(0.2, 0.925, "CMS");
TLatex* work = new TLatex();
work->SetTextFont(52);
work->SetTextSize(0.035);
work->DrawLatexNDC(0.25, 0.925, "Work in Progress");
TLatex* lumi = new TLatex();
lumi->SetTextFont(42);
lumi->SetTextSize(0.035);
lumi->DrawLatexNDC(0.72, 0.925, "41.4 fb^{-1} (2017, 13 TeV)");
legendpad->Draw();
legendpad->cd();
legend->SetTextSize(0.15);
legend->Draw();
for(std::string outdir: outdirs){
canvas->SaveAs((outdir + "/postfit_" + std::to_string(mass) + ".pdf").c_str());
canvas->SaveAs((outdir + "/postfit_" + std::to_string(mass) + ".png").c_str());
}
std::cout << "Plotfit plot created for: " << mass << std::endl;
}
<file_sep>/Analysis/src/plottertriggeff.cc
#include <ChargedAnalysis/Analysis/include/plottertriggeff.h>
PlotterTriggEff::PlotterTriggEff() : Plotter(){}
PlotterTriggEff::PlotterTriggEff(std::string &histdir, std::string &total, std::vector<std::string> &passed,std::vector<std::string> &yParam) :
Plotter(histdir),
total(total),
passed(passed),
processes(processes),
yParam(yParam) {
ptNames = {{"ele+4j", "e_pt"}, {"mu+4j", "mu_pt"}};
phiNames = {{"ele+4j", "e_phi"}, {"mu+4j", "mu_phi"}};
etaNames = {{"ele+4j", "e_eta"}, {"mu+4j", "mu_eta"}};
}
void PlotterTriggEff::ConfigureHists(){
bkgEfficiencies = std::vector<std::vector<TGraphAsymmErrors*>>(yParam.size(), std::vector<TGraphAsymmErrors*>(passed.size(), NULL));
dataEfficiencies = std::vector<std::vector<TGraphAsymmErrors*>>(yParam.size(), std::vector<TGraphAsymmErrors*>(passed.size(), NULL));
//Save 2D hist for trigger information
std::vector<TH2F*> bkgTotal(yParam.size(), NULL);
std::vector<std::vector<TH2F*>> bkgPassed(yParam.size(), std::vector<TH2F*>(passed.size(), NULL));
std::vector<TH2F*> dataTotal;
//Loop over all processes
for(std::string process: processes){
std::string filename = histdir + "/" + process + ".root";
TFile* file = TFile::Open(filename.c_str());
for(unsigned int i = 0; i < yParam.size(); i++){
if(Utils::Find<std::string>(process, "Single") != -1. or Utils::Find<std::string>(process, "MET") != -1.){
dataTotal.push_back((TH2F*)file->Get((total + "_VS_" + yParam[i]).c_str()));
for(unsigned int j = 0; j < passed.size(); j++){
TH2F* dataPassed = (TH2F*)file->Get((passed[j] + "_VS_" + yParam[i]).c_str());
TH1F* pass = (TH1F*)dataPassed->ProjectionY()->Clone();
pass->Reset();
pass->Sumw2(kFALSE);
TH1F* total = (TH1F*)dataPassed->ProjectionY()->Clone();
total->Reset();
total->Sumw2(kFALSE);
for(int k = 1; k <= dataPassed->GetYaxis()->GetNbins(); k++){
pass->SetBinContent(k, dataPassed->GetBinContent(2, k));
total->SetBinContent(k,dataTotal[i]->GetBinContent(2, k));
}
TGraphAsymmErrors* dataEff = new TGraphAsymmErrors();
dataEff->Divide(pass, total, "cp");
dataEff->SetMarkerStyle(20);
dataEfficiencies[i][j] = dataEff;
}
}
else{
if(bkgTotal[i] == NULL){
bkgTotal[i] = (TH2F*)file->Get((total + "_VS_" + yParam[i]).c_str());
}
else{
bkgTotal[i]->Add((TH2F*)file->Get((total + "_VS_" + yParam[i]).c_str()));
}
for(unsigned int j = 0; j < passed.size(); j++){
TH2F* pass = (TH2F*)file->Get((passed[j] + "_VS_" + yParam[i]).c_str());
//Merge bkg hist to another
if(bkgPassed[i][j] == NULL){
bkgPassed[i][j] = pass;
}
//Push back hist empty
else{
bkgPassed[i][j]->Add(pass);
}
}
}
}
}
for(unsigned int i = 0; i < yParam.size(); i++){
for(unsigned int j = 0; j < bkgPassed[i].size(); j++){
TH1F* passed = (TH1F*)bkgPassed[i][j]->ProjectionY()->Clone();
passed->Reset();
passed->Sumw2(kFALSE);
TH1F* total = (TH1F*)bkgPassed[i][j]->ProjectionY()->Clone();
total->Reset();
total->Sumw2(kFALSE);
for(int k = 1; k <= bkgPassed[i][j]->GetYaxis()->GetNbins(); k++){
passed->SetBinContent(k, bkgPassed[i][j]->GetBinContent(2, k));
total->SetBinContent(k,bkgTotal[i]->GetBinContent(2, k));
}
TGraphAsymmErrors* bkgEff = new TGraphAsymmErrors();
bkgEff->Divide(passed, total, "cp");
bkgEff->SetMarkerStyle(21);
bkgEff->SetMarkerColor(kBlue);
bkgEff->GetHistogram()->GetXaxis()->SetTitle(passed->GetXaxis()->GetTitle());
bkgEff->GetHistogram()->GetXaxis()->SetTitleSize(0.05);
bkgEff->GetHistogram()->GetYaxis()->SetTitleSize(0.05);
bkgEff->GetHistogram()->GetXaxis()->SetTitleOffset(1.1);
bkgEff->GetHistogram()->GetYaxis()->SetTitle("Efficiency");
bkgEff->GetHistogram()->SetMaximum(1.);
bkgEfficiencies[i][j] = bkgEff;
}
}
}
void PlotterTriggEff::Draw(std::vector<std::string> &outdirs){
TCanvas* canvas = new TCanvas("canvas", "canvas", 1000, 800);
TPad* mainpad = new TPad("mainpad", "mainpad", 0., 0. , 0.95, 1.);
TPad* legendpad = new TPad("legendpad", "legendpad", 0.87, 0.3 , 1., 0.8);
mainpad->SetLeftMargin(0.15);
mainpad->SetRightMargin(0.1);
mainpad->SetBottomMargin(0.12);
mainpad->Draw();
legendpad->Draw();
canvas->cd();
PUtil::DrawHeader(mainpad, "e inclusive", "Work in progress");
for(unsigned int i = 0; i < yParam.size(); i++){
for(unsigned int j = 0; j < passed.size(); j++){
mainpad->Clear();
legendpad->Clear();
legendpad->cd();
TLegend* legend = new TLegend(0.0, 0.0, 1.0, 1.0);
legend->Draw();
mainpad->cd();
legend->AddEntry(bkgEfficiencies[i][j], "MC", "P");
legend->AddEntry(dataEfficiencies[i][j], "data", "P");
bkgEfficiencies[i][j]->Draw("AP");
dataEfficiencies[i][j]->Draw("SAME P");
for(std::string outdir: outdirs){
canvas->SaveAs((outdir + "/" + passed[j] + "_" + yParam[i] + "_Eff.pdf").c_str());
canvas->SaveAs((outdir + "/" + passed[j] + "_" + yParam[i] + "_Eff.png").c_str());
}
}
}
}
<file_sep>/Analysis/include/treeslimmer.h
#ifndef TREESLIMMER
#define TREESLIMMER
#include <string>
#include <vector>
#include <TFile.h>
#include <TTree.h>
#include <TEntryList.h>
#include <ChargedAnalysis/Analysis/include/treefunction.h>
#include <ChargedAnalysis/Analysis/include/treereader.h>
#include <ChargedAnalysis/Utility/include/utils.h>
class TreeSlimmer{
private:
const std::string inputFile;
const std::string inputChannel;
public:
TreeSlimmer(const std::string& inputFile, const std::string& inputChannel);
void DoSlim(const std::string outputFile, const std::string outChannel, const std::vector<std::string>& cuts, const int& start, const int& end);
};
#endif
<file_sep>/Utility/include/rootutil.h
/**
* @file rootutil.h
* @brief Header file for RUtil namespace
*/
#ifndef ROOTUTIL_H
#define ROOTUTIL_H
#include <string>
#include <memory>
#include <experimental/source_location>
#include <ChargedAnalysis/Utility/include/stringutil.h>
#include <TFile.h>
#include <TTree.h>
#include <TBranch.h>
#include <TLeaf.h>
/**
* @brief Utility library to handle getter function for ROOT pointer objects
*/
namespace RUtil{
/**
* @brief Open ROOT TFile with exception handling in READ mode
*
* Example:
* @code
* std::shared_ptr<TFile> f = RUtil::Open("myFile.root");
* @endcode
*
* @param fileName ROOT file name
* @param location Standard library object containing the file positions
* @return Shared ptr TFile opened in READ mode
*/
std::shared_ptr<TFile> Open(const std::string& fileName, const std::experimental::source_location& location = std::experimental::source_location::current());
bool BranchExists(TTree* tree, const std::string& branchName);
/**
* @brief Get object from TFile with exception handling
*
* Example:
* @code
* TH1F* h = RUtil::Get<TH1F>(myFile, "myHist");
* @endcode
*
* @param obj Opened readable TFile
* @param getName Object name to retrieve
* @param location Standard library object containing the file positions
* @return Pointer of the object
*/
template<typename T>
T* Get(TFile* obj, const std::string& getName, const std::experimental::source_location& location = std::experimental::source_location::current()){
//Check if objects is not null pointer
if(obj == nullptr) throw std::runtime_error(StrUtil::PrettyError(location, "TFile is a null pointer!"));
T* out = static_cast<T*>(obj->Get(getName.c_str()));
if(out == nullptr) throw std::runtime_error(StrUtil::PrettyError(location, "Object '", getName, "' in TFile '", obj->GetName(), "' is a null pointer!"));
return out;
}
/**
* @brief Get TLeaf from TTree with exception handling
*
* Example:
* @code
* TLeaf* h = RUtil::Get<TLeaf>(tree, "myLeaf");
* @endcode
*
* @param obj TTree with the wished leaf
* @param getName TLeaf name to retrieve
* @param location Standard library object containing the file positions
* @return Pointer of the TLeaf
*/
template<typename T>
T* Get(TTree* obj, const std::string& getName, const std::experimental::source_location& location = std::experimental::source_location::current()){
//Check if objects is not null pointer
if(obj == nullptr){
throw std::runtime_error(StrUtil::PrettyError(location, "Null pointer is given!"));
}
T* out = obj->GetLeaf(getName.c_str());
if(out == nullptr) throw std::runtime_error(StrUtil::PrettyError(location, "Object '", getName, "' is a null pointer!"));
return out;
}
/**
* @brief Wrapper of the RUtil::Get function to return shared pointer
*
* @param obj TTree with the wished leaf
* @param getName TLeaf name to retrieve
* @param location Standard library object containing the file positions
* @return Return shared pointer of wished pointer
*/
template<typename outType, typename inType>
std::shared_ptr<outType> GetSmart(inType* obj, const std::string& getName, const std::experimental::source_location& location = std::experimental::source_location::current()){
return std::shared_ptr<outType>(RUtil::Get<outType>(obj, getName, location));
}
/**
* @brief Clone ROOT object with exception handling
*
* Example:
* @code
* TH1F* h2 = RUtil::Clone<TH1F>(h1);
* @endcode
*
* @param obj Object to clone
* @param location Standard library object containing the file positions
* @return Return shared pointer of wished pointer
*/
template<typename T>
T* Clone(T* obj, const std::experimental::source_location& location = std::experimental::source_location::current()){
//Check if objects is not null pointer
if(obj == nullptr){
throw std::runtime_error(StrUtil::PrettyError(location, "Null pointer is given!"));
}
return static_cast<T*>(obj->Clone());
}
/**
* @brief Wrapper of the RUtil::Clone function to return shared pointer
*
* @param obj Object to clone
* @param location Standard library object containing the file positions
* @return Return shared pointer of wished pointer
*/
template<typename T>
std::shared_ptr<T> CloneSmart(T* obj, const std::experimental::source_location& location = std::experimental::source_location::current()){
return std::shared_ptr<T>(RUtil::Clone<T>(obj, location));
}
/**
* @brief Get data from given TLeaf with given entry number
*
* @param leaf TLeaf to be readed out
* @param entry Entry number
* @return Return data
*/
template<typename T>
const T GetEntry(TLeaf* leaf, const int& entry){
if(leaf->GetBranch()->GetReadEntry() != entry) leaf->GetBranch()->GetEntry(entry);
return leaf->GetValue();
}
/**
* @brief Get vector data from given TLeaf with given entry number
*
* @param leaf TLeaf to be readed out
* @param entry Entry number
* @return Return vector data
*/
template<typename T>
const std::vector<T> GetVecEntry(TLeaf* leaf, const int& entry){
if(leaf->GetBranch()->GetReadEntry() != entry) leaf->GetBranch()->GetEntry(entry);
std::vector<T> v(leaf->GetLen());
for(int i = 0; i < v.size(); ++i){
v[i] = leaf->GetValue(i);
}
return v;
}
};
#endif
<file_sep>/Analysis/exesrc/writecard.cc
#include <ChargedAnalysis/Utility/include/parser.h>
#include <ChargedAnalysis/Utility/include/datacard.h>
int main(int argc, char* argv[]){
//Parser arguments
Parser parser(argc, argv);
std::vector<std::string> bkgProcesses = parser.GetVector<std::string>("bkg-processes");
std::string sigProcess = parser.GetValue<std::string>("sig-process");
std::string data = parser.GetValue<std::string>("data");
std::vector<std::string> bkgFiles = parser.GetVector<std::string>("bkg-files");
std::vector<std::string> sigFiles = parser.GetVector<std::string>("sig-files");
std::string dataFile = parser.GetValue<std::string>("data-file");
std::string discriminant = parser.GetValue<std::string>("discriminant");
std::string outDir = parser.GetValue<std::string>("out-dir");
std::string channel = parser.GetValue<std::string>("channel");
std::vector<std::string> systematics = parser.GetVector<std::string>("systematics", {""});
//Create datcard
Datacard datacard(outDir, channel, bkgProcesses, bkgFiles, sigProcess, sigFiles, data, dataFile, systematics);
datacard.GetHists(discriminant);
datacard.Write();
}
<file_sep>/Analysis/include/ntuplereader.h
#ifndef NTUPLEREADER_H
#define NTUPLEREADER_H
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <iostream>
#include <vector>
#include <memory>
#include <functional>
#include <string>
#include <experimental/source_location>
#include <TTree.h>
#include <TLeaf.h>
#include <ChargedAnalysis/Utility/include/stringutil.h>
#include <ChargedAnalysis/Utility/include/vectorutil.h>
#include <ChargedAnalysis/Utility/include/rootutil.h>
class CompiledFunc{
private:
float(*func)(TLeaf*, const int&);
float(*funcWithWp)(TLeaf*, std::vector<std::shared_ptr<CompiledFunc>>&, const int&, const std::size_t&);
TLeaf* leaf;
int partIdx;
std::size_t partHash;
std::vector<std::shared_ptr<CompiledFunc>> cuts;
bool(*op)(const float&, const float&);
float comp;
bool isIter;
public:
CompiledFunc(){}
CompiledFunc(float(*func)(TLeaf*, const int&), TLeaf* leaf, const int& partIdx, const bool& isIter = false) :
func(func), leaf(leaf), partIdx(isIter ? 0 : partIdx), cuts({}), isIter(isIter) {}
CompiledFunc(float(*funcWithWp)(TLeaf*, std::vector<std::shared_ptr<CompiledFunc>>&, const int&, const std::size_t&), TLeaf* leaf, std::vector<std::shared_ptr<CompiledFunc>>& cuts, const int& partIdx, const std::size_t& partHash, const bool& isIter = false) :
funcWithWp(funcWithWp), leaf(leaf), cuts(cuts), partIdx(isIter ? 0 : partIdx), partHash(partHash), isIter(isIter) {}
virtual float Get(){
if(cuts.empty()) return (*func)(leaf, partIdx);
else return (*funcWithWp)(leaf, cuts, partIdx, partHash);
}
virtual void AddCut(bool(*op)(const float&, const float&), const float& comp){this->op = op; this->comp = comp;};
virtual bool GetPassed(){return op(Get(), comp);};
virtual void Next(){if(isIter) ++partIdx;}
virtual void Reset(){if(isIter) partIdx = 0;}
};
using Particles = std::map<std::pair<std::string, std::string>, std::shared_ptr<CompiledFunc>>;
class CompiledCustomFunc : public CompiledFunc {
private:
float(*func)(Particles& parts);
Particles parts;
bool(*op)(const float&, const float&);
float comp;
public:
CompiledCustomFunc(float(*func)(Particles& parts), const Particles& parts) : func(func), parts(parts) {}
void AddCut(bool(*op)(const float&, const float&), const float& comp){this->op = op; this->comp = comp;};
float Get(){return (*func)(parts);}
bool GetPassed(){return op(Get(), comp);};
void Next(){for(auto& p : parts) p.second->Next();}
void Reset(){for(auto& p : parts) p.second->Reset();};
};
namespace Properties{
float HT(Particles& parts);
float dR(Particles& parts);
float dPhi(Particles& parts);
float diCharge(Particles& parts);
float NParticles(Particles& parts);
//Register all functions here!
static std::map<std::string, float(*)(Particles&)> properties = {
{"dR", &dR},
{"dphi", &dPhi},
{"N", &NParticles},
{"HT", &HT},
{"dicharge", &diCharge},
};
};
namespace pt = boost::property_tree;
class NTupleReader{
private:
pt::ptree partInfo;
pt::ptree funcInfo;
pt::ptree function;
std::vector<pt::ptree> particles;
std::shared_ptr<TTree> inputTree;
int era;
std::shared_ptr<CompiledFunc> func;
bool isCompiled = false;
inline static int entry = 0;
inline static std::map<std::size_t, std::map<int, int>> idxCache = {};
static float GetEntry(TLeaf* leaf, const int& idx);
static float GetEntryWithWP(TLeaf* leaf, std::vector<std::shared_ptr<CompiledFunc>>& cuts, const int& idx, const std::size_t& hash);
std::shared_ptr<CompiledFunc> compileBranchReading(pt::ptree& func, pt::ptree& part);
std::shared_ptr<CompiledFunc> compileCustomFunction(pt::ptree& func, std::vector<pt::ptree>& parts);
public:
NTupleReader();
NTupleReader(const std::shared_ptr<TTree>& inputTree, const int& era = 2017);
void AddParticle(const std::string& pAlias, const int& idx, const std::string& wp, const std::experimental::source_location& location = std::experimental::source_location::current());
void AddFunction(const std::string& fInfo, const std::vector<std::string>& values = {}, const std::experimental::source_location& location = std::experimental::source_location::current());
void AddFunctionByBranchName(const std::string& branchName, const std::experimental::source_location& location = std::experimental::source_location::current());
void AddCut(const float&, const std::string& op, const std::experimental::source_location& location = std::experimental::source_location::current());
void Compile(const std::experimental::source_location& location = std::experimental::source_location::current());
float Get();
bool GetPassed();
std::string GetHistName();
std::string GetAxisLabel();
std::string GetCutName();
void Next();
void Reset();
static void SetEntry(const int& entry){NTupleReader::entry = entry; idxCache.clear();}
//Helper function to get keys of ptree
static std::vector<std::string> GetInfo(const pt::ptree& node, const bool GetInfo = true){
std::vector<std::string> keys;
for(const std::pair<const std::string, pt::ptree>& p : node){
keys.push_back(GetInfo ? p.first : p.second.get_value<std::string>());
}
return keys;
}
//Helper function to get name of child tree with wished alias in it
static std::string GetName(const pt::ptree& node, const std::string& alias){
for(const std::string& name : NTupleReader::GetInfo(node)){
if(node.get<std::string>(name + ".alias") == alias) return name;
}
return "";
}
};
#endif
<file_sep>/Analysis/src/histmaker.cc
#include <ChargedAnalysis/Analysis/include/histmaker.h>
HistMaker::HistMaker(const std::vector<std::string> ¶meters, const std::vector<std::string> &cutStrings, const std::string& outDir, const std::string &outFile, const std::string &channel, const std::vector<std::string>& systDirs, const std::vector<std::string>& scaleSysts, const std::string& scaleFactors, const int& era):
parameters(parameters),
cutStrings(cutStrings),
outDir(outDir),
outFile(outFile),
channel(channel),
systDirs(systDirs),
scaleSysts(scaleSysts),
scaleFactors(scaleFactors),
era(era){}
void HistMaker::PrepareHists(const std::experimental::source_location& location){
Decoder parser;
if(VUtil::Find(scaleSysts, std::string("")).empty()) scaleSysts.insert(scaleSysts.begin(), "");
for(const std::string& scaleSyst : scaleSysts){
for(const std::string shift : {"Up", "Down"}){
//Skip Down loop for nominal case
if(scaleSyst == "" and shift == "Down") continue;
std::string systName = StrUtil::Merge(scaleSyst, shift);
std::string outName;
//Change outdir for systematic
if(scaleSyst.empty()) outName = StrUtil::Join("/", outDir, outFile);
else{
for(const std::string dir : systDirs){
if(!StrUtil::Find(dir, systName).empty()) outName = StrUtil::Join("/", dir, outFile);
}
}
outFiles.push_back(std::make_shared<TFile>(outName.c_str(), "RECREATE"));
for(const std::string& parameter: parameters){
if(StrUtil::Find(parameter, "h:").empty()) throw std::runtime_error(StrUtil::PrettyError(location, "Missing key 'h:' in parameter '", parameter, "'!"));
//Functor structure and arguments
NTupleReader paramX(inputTree, era), paramY(inputTree, era);
//Read in everything, orders matter
parser.GetParticle(parameter, paramX);
parser.GetFunction(parameter, paramX);
paramX.Compile();
if(!parser.hasYInfo(parameter)){
std::shared_ptr<TH1F> hist1D = std::make_shared<TH1F>();
parser.GetBinning(parameter, hist1D.get());
hist1D->SetDirectory(outFiles.back().get());
hist1D->SetName(paramX.GetHistName().c_str());
hist1D->SetTitle(paramX.GetHistName().c_str());
hist1D->GetXaxis()->SetTitle(paramX.GetAxisLabel().c_str());
if(scaleSyst == "") hists1D.push_back(std::move(hist1D));
else hists1DSyst.push_back(std::move(hist1D));
if(scaleSyst == "") hist1DFunctions.push_back(std::move(paramX));
}
else{
parser.GetParticle(parameter, paramY);
parser.GetFunction(parameter, paramY);
paramY.Compile();
std::shared_ptr<TH2F> hist2D = std::make_shared<TH2F>();
parser.GetBinning(parameter, hist2D.get());
hist2D->SetDirectory(outFiles.back().get());
hist2D->SetName((paramX.GetHistName() + "_VS_" + paramY.GetHistName()).c_str());
hist2D->SetTitle((paramX.GetHistName() + "_VS_" + paramY.GetHistName()).c_str());
hist2D->GetXaxis()->SetTitle(paramX.GetAxisLabel().c_str());
hist2D->GetYaxis()->SetTitle(paramY.GetAxisLabel().c_str());
if(scaleSyst == "") hists2D.push_back(std::move(hist2D));
else hists2DSyst.push_back(std::move(hist2D));
if(scaleSyst == "") hist2DFunctions.push_back({paramX, paramY});
}
}
}
}
for(const std::string& cutString: cutStrings){
//Functor structure and arguments
NTupleReader cut(inputTree, era);
if(!StrUtil::Find(cutString, "n=N").empty()) parser.GetParticle(cutString, cut, &weight);
else parser.GetParticle(cutString, cut);
parser.GetFunction(cutString, cut);
parser.GetCut(cutString, cut);
cut.Compile();
cutFunctions.push_back(cut);
std::cout << "Cut will be applied: '" << cut.GetCutName() << "'" << std::endl;
}
}
void HistMaker::Produce(const std::string& fileName){
//Get input tree
inputFile = RUtil::Open(fileName);
inputTree = RUtil::GetSmart<TTree>(inputFile.get(), channel);
weight = Weighter(inputFile, inputTree, era);
std::cout << "Read file: '" << fileName << "'" << std::endl;
std::cout << "Read tree '" << channel << std::endl;
gROOT->SetBatch(kTRUE);
TH1::SetDefaultSumw2();
//Open output file and set up all histograms/tree and their function to call
PrepareHists();
//Set all branch addresses needed for the event
bool passed = true, isData = true;
//Data driven scale factors
float sf = 1.;
if(!scaleFactors.empty()){
std::string fileName = StrUtil::Split(scaleFactors, "+")[0];
std::string process = StrUtil::Split(scaleFactors, "+")[1];
CSV scaleFactors(fileName, "r", "\t");
std::vector<std::string> processes = scaleFactors.GetColumn("Process");
sf = scaleFactors.Get<float>(VUtil::Find(processes, process).at(0), "Factor");
}
//Cutflow/Event count histogram
std::shared_ptr<TH1F> cutflow = RUtil::GetSmart<TH1F>(inputFile.get(), "cutflow_" + channel);
cutflow->SetName("cutflow"); cutflow->SetTitle("cutflow");
// cutflow->Scale(1./nGen);
std::shared_ptr<TH1F> eventCount = std::make_shared<TH1F>("EventCount", "EventCount", 1, 0, 1);
double wght = 1.;
StopWatch timer;
timer.Start();
timer.SetTimeMark();
for (int i = 0; i < inputTree->GetEntries(); ++i){
if(i % 100000 == 0 and i != 0){
std::cout << "Processed events: " << i << " (" << 100000./(timer.SetTimeMark() - timer.GetTimeMark(i/100000 -1)) << " eve/s)" << std::endl;
}
//Set Entry
NTupleReader::SetEntry(i);
//Check if event passed all cuts
passed = true;
wght = weight.GetBaseWeight(i) * sf;
for(int j=0; j < cutFunctions.size(); j++){
passed *= cutFunctions[j].GetPassed();
if(passed){
cutflow->Fill(cutFunctions[j].GetCutName().c_str(), wght);
}
else break;
}
if(!passed) continue;
wght *= weight.GetPartWeight(i);
//Fill nominal histogram
for(int j=0; j < hist1DFunctions.size(); j++){
hists1D[j]->Fill(hist1DFunctions[j].Get(), wght);
}
for(int j=0; j < hist2DFunctions.size(); j++){
hists2D[j]->Fill(hist2DFunctions[j].first.Get(), hist2DFunctions[j].second.Get(), wght);
}
eventCount->Fill(0., wght);
}
//Write all histograms and delete everything
for(std::shared_ptr<TH1F>& hist: VUtil::Merge(hists1D, hists1DSyst)){
hist->GetDirectory()->cd();
hist->Write();
std::cout << "Saved histogram: '" << hist->GetName() << "' with " << hist->GetEntries() << " entries" << std::endl;
}
for(std::shared_ptr<TH2F>& hist: VUtil::Merge(hists2D, hists2DSyst)){
hist->GetDirectory()->cd();
hist->Write();
std::cout << "Saved histogram: '" << hist->GetName() << "' with " << hist->GetEntries() << " entries" << std::endl;
}
//Write cutflow/eventcount
VUtil::At(outFiles, 0)->cd();
cutflow->Write();
eventCount->Write();
std::cout << "Closed output file: '" << outFile << "'" << std::endl;
std::cout << "Time passed for complete processing: " << timer.GetTime() << " s" << std::endl;
}
<file_sep>/Analysis/src/treeappender.cc
/**
* @file treeappender.cc
* @brief Source file for TreeAppender class, see treeappender.h
*/
#include <ChargedAnalysis/Analysis/include/treeappender.h>
TreeAppender::TreeAppender() {}
TreeAppender::TreeAppender(const std::string& fileName, const std::string& treeName, const int& era, const std::vector<std::string>& appendFunctions) :
fileName(fileName),
treeName(treeName),
era(era),
appendFunctions(appendFunctions){}
void TreeAppender::Append(const std::string& outName){
at::set_num_interop_threads(1);
at::set_num_threads(1);
//Get old Tree
std::shared_ptr<TFile> oldF = RUtil::Open(fileName);
std::shared_ptr<TTree> oldT = RUtil::GetSmart<TTree>(oldF.get(), treeName);
std::cout << "Read file: '" << fileName << "'" << std::endl;
std::cout << "Read tree '" << treeName << "'" << std::endl;
//Get values for new branches
std::map<std::string, TBranch*> branches;
std::vector<std::string> branchNames;
std::map<std::string, float> branchValues;
std::map<std::string, std::vector<float>> values;
std::map<std::string, std::map<std::string, std::vector<float>>(*)(std::shared_ptr<TFile>&, const std::string&, const int&)> expandFunctions = {
{"HTagger", &Extension::HScore},
{"DNN", &Extension::DNNScore},
{"HReco", &Extension::HReconstruction},
};
for(const std::string& function: appendFunctions){
for(const std::pair<std::string, std::vector<float>>& funcValues : expandFunctions.at(function)(oldF, treeName, era)){
oldT->SetBranchStatus(funcValues.first.c_str(), 0);
branchNames.push_back(funcValues.first);
values[funcValues.first] = funcValues.second;
}
}
//Clone Tree
std::shared_ptr<TFile> newF(TFile::Open(outName.c_str(), "RECREATE"));
std::shared_ptr<TTree> newT(oldT->CloneTree(-1, "fast"));
for(const std::string& name : branchNames){
branchValues[name] = -999.;
branches[name] = newT->Branch(name.c_str(), &branchValues[name]);
}
//Fill branches
for(int i=0; i < oldT->GetEntries(); i++){
for(std::string& branchName: branchNames){
branchValues[branchName] = values[branchName][i];
branches[branchName]->Fill();
}
}
newF->cd();
newT->Write();
std::cout << "Sucessfully append branches " << branchNames << " in tree " << treeName << std::endl;
TList* keys(oldF->GetListOfKeys());
for(int i=0; i < keys->GetSize(); i++){
bool skipKey = false;
TObject* obj(oldF->Get(keys->At(i)->GetName()));
if(obj->InheritsFrom(TTree::Class())) continue;
obj->Write();
}
}
<file_sep>/Analysis/exesrc/treeslim.cc
#include <ChargedAnalysis/Utility/include/parser.h>
#include <ChargedAnalysis/Analysis/include/treeslimmer.h>
int main(int argc, char* argv[]){
//Parser arguments
Parser parser(argc, argv);
std::string inName = parser.GetValue<std::string>("input-file");
std::string inChannel = parser.GetValue<std::string>("input-channel");
std::string outFile = parser.GetValue<std::string>("out-file");
std::string outChannel = parser.GetValue<std::string>("out-channel");
std::vector<std::string> cuts = parser.GetVector<std::string>("cuts");
int start = parser.GetValue<int>("event-start");
int end = parser.GetValue<int>("event-end");
//Create output directory if needed
if(!StrUtil::Find(outFile, "/").empty()){
std::filesystem::create_directories(outFile.substr(0, StrUtil::Find(outFile, "/").back()));
}
TreeSlimmer slimmer(inName, inChannel);
slimmer.DoSlim(outFile, outChannel, cuts, start, end);
}
<file_sep>/Analysis/src/plotterLimit.cc
#include <ChargedAnalysis/Analysis/include/plotterLimit.h>
PlotterLimit::PlotterLimit() : Plotter(){}
PlotterLimit::PlotterLimit(const std::vector<std::string> limitFiles, const std::vector<int>& chargedMasses, const std::vector<int>& neutralMasses, const std::string& channel, const std::string& era, const std::vector<float>& xSecs) :
Plotter(),
limitFiles(limitFiles),
chargedMasses(chargedMasses),
neutralMasses(neutralMasses),
channel(channel),
era(era),
xSecs(xSecs){}
void PlotterLimit::ConfigureHists(){
expected = std::make_shared<TH2D>(("Ex" + channel).c_str(), ("Ex" + channel).c_str(), chargedMasses.size(), chargedMasses[0] - 50, chargedMasses.back() + 50, neutralMasses.size() + 1, neutralMasses[0] - 5, neutralMasses.back() + 5);
theory = std::make_shared<TH2D>(("Theo" + channel).c_str(), ("Theo" + channel).c_str(), chargedMasses.size(), chargedMasses[0] - 50, chargedMasses.back() + 50, neutralMasses.size() + 1, neutralMasses[0] - 5, neutralMasses.back() + 5);
for(unsigned int i=0; i < chargedMasses.size(); ++i){
for(unsigned int j=0; j < neutralMasses.size(); ++j){
int mHC = chargedMasses[i], mh = neutralMasses[j];
int idx = MUtil::RowMajIdx({chargedMasses.size(), neutralMasses.size()}, {i, j});
std::shared_ptr<TFile> limitFile = RUtil::Open(limitFiles.at(idx));
std::shared_ptr<TTree> limitTree = RUtil::GetSmart<TTree>(limitFile.get(), "limit");
//Set branch for reading limits
std::vector<double> limitValues;
TLeaf* limitValue = RUtil::Get<TLeaf>(limitTree.get(), "limit");
//Values
for(int k=0; k < 5; k++){
limitValues.push_back(RUtil::GetEntry<double>(limitValue, k) * xSecs[idx]);
}
expected->SetBinContent(i+1, j+1, limitValues[2]);
theory->SetBinContent(i+1, j+1, xSecs[idx]);
if(i == 0 and j == 0){
sigmaOne = std::make_shared<TGraphAsymmErrors>();
sigmaTwo = std::make_shared<TGraphAsymmErrors>();
sigmaOne->SetFillColor(kGreen);
sigmaOne->SetFillStyle(1001);
sigmaTwo->SetFillColor(kYellow);
sigmaTwo->SetFillStyle(1001);
}
sigmaOne->SetPoint(i, mHC, limitValues[2]);
sigmaOne->SetPointEYlow(i, limitValues[2] - limitValues[1]);
sigmaOne->SetPointEYhigh(i, limitValues[3] - limitValues[1]);
sigmaTwo->SetPoint(i, mHC, limitValues[2]);
sigmaTwo->SetPointEYlow(i, limitValues[2] - limitValues[0]);
sigmaTwo->SetPointEYhigh(i, limitValues[4] - limitValues[1]);
}
}
}
void PlotterLimit::Draw(std::vector<std::string>& outdirs){
std::shared_ptr<TCanvas> canvas = std::make_shared<TCanvas>("canvas", "canvas", 1000, 1000);
std::shared_ptr<TPad> mainPad = std::make_shared<TPad>("mainPad", "mainPad", 0., 0. , 1., 1.);
PUtil::SetStyle();
//Draw main pad
PUtil::SetPad(mainPad.get());
mainPad->SetLogy(1);
mainPad->Draw();
mainPad->cd();
//Plot charged Higgs 1D limit in slices of small higgs
for(unsigned int j=0; j < neutralMasses.size(); j++){
int mh = neutralMasses[j];
//Expected/theory hist configuration
std::shared_ptr<TH1D> exHist(expected->ProjectionX("ex", j+1, j+2));
exHist->SetLineWidth(3);
exHist->SetLineColor(kBlack);
std::shared_ptr<TH1D> theoHist(theory->ProjectionX("theo", j+1, j+2));
theoHist->SetLineWidth(3);
theoHist->SetLineStyle(2);
theoHist->SetLineColor(kBlack);
//Frame histo
std::shared_ptr<TH1D> frameHist = RUtil::CloneSmart<TH1D>(exHist.get());
frameHist->Reset();
PUtil::SetHist(mainPad.get(), frameHist.get(), "95% CL Limit on #sigma(pp #rightarrow H^{#pm}h #rightarrow lb#bar{b}b#bar{b}) [pb]");
float min = std::min(theoHist->GetMinimum(), sigmaTwo->GetHistogram()->GetMinimum());
frameHist->GetXaxis()->SetLimits(chargedMasses[0], chargedMasses.back());
frameHist->SetMinimum(min*1e-1);
frameHist->GetXaxis()->SetTitle("m(H^{#pm}) [GeV]");
//Add legend information
std::shared_ptr<TLegend> legend = std::make_shared<TLegend>(0.0, 0.0, 1.0, 1.0);
legend->AddEntry(exHist.get(), "Expected", "L");
legend->AddEntry(theoHist.get(), "Theo. prediction", "L");
legend->AddEntry(sigmaOne.get(), "68% expected", "F");
legend->AddEntry(sigmaTwo.get(), "95% expected", "F");
//Draw everything and save
frameHist->Draw();
sigmaTwo->Draw("SAME 3");
sigmaOne->Draw("SAME 3");
exHist->Draw("C SAME");
theoHist->Draw("C SAME");
gPad->RedrawAxis();
PUtil::DrawHeader(mainPad.get(), channel == "Combined" ? channel : PUtil::GetChannelTitle(channel), "Work in progress", PUtil::GetLumiTitle(era));
PUtil::DrawLegend(mainPad.get(), legend.get(), 2);
for(std::string outdir: outdirs){
canvas->SaveAs(StrUtil::Merge(outdir, "/limit_h", mh, ".pdf").c_str());
canvas->SaveAs(StrUtil::Merge(outdir, "/limit_h", mh, ".png").c_str());
}
mainPad->Clear();
legend->Clear();
}
mainPad->SetLogy(0);
//Draw 2D limit plot
expected->GetXaxis()->SetTitle("m(H^{#pm}) [GeV]");
expected->GetXaxis()->SetLimits(chargedMasses[0], chargedMasses.back());
expected->GetYaxis()->SetLimits(neutralMasses[0], neutralMasses.back() + 10);
PUtil::SetHist(mainPad.get(), expected.get(), "m(h) [GeV]");
expected->Draw("COLZ");
PUtil::DrawHeader(mainPad.get(), channel == "Combined" ? channel : PUtil::GetChannelTitle(channel), "Work in progress", PUtil::GetLumiTitle(era));
for(std::string outdir: outdirs){
canvas->SaveAs(StrUtil::Merge(outdir, "/limit.pdf").c_str());
canvas->SaveAs(StrUtil::Merge(outdir, "/limit.png").c_str());
}
}
<file_sep>/Analysis/include/plotterLimit.h
#ifndef PLOTTERLIMIT_H
#define PLOTTERLIMIT_H
#include <vector>
#include <memory>
#include <map>
#include <TFile.h>
#include <TH2D.h>
#include <TH1D.h>
#include <TGraph.h>
#include <TGraphAsymmErrors.h>
#include <TTree.h>
#include <TCanvas.h>
#include <TLegend.h>
#include <TPad.h>
#include <TLeaf.h>
#include <ChargedAnalysis/Utility/include/stringutil.h>
#include <ChargedAnalysis/Utility/include/vectorutil.h>
#include <ChargedAnalysis/Utility/include/plotutil.h>
#include <ChargedAnalysis/Utility/include/mathutil.h>
#include <ChargedAnalysis/Utility/include/rootutil.h>
#include <ChargedAnalysis/Analysis/include/plotter.h>
class PlotterLimit : public Plotter{
private:
std::vector<std::string> limitFiles;
std::vector<int> chargedMasses, neutralMasses;
std::string channel, era;
std::vector<float> xSecs;
std::shared_ptr<TH2D> expected;
std::shared_ptr<TH2D> theory;
std::shared_ptr<TGraphAsymmErrors> sigmaOne;
std::shared_ptr<TGraphAsymmErrors> sigmaTwo;
public:
PlotterLimit();
PlotterLimit(const std::vector<std::string> limitFiles, const std::vector<int>& chargedMasses, const std::vector<int>& neutralMasses, const std::string& channel, const std::string& era, const std::vector<float>& xSecs);
void ConfigureHists();
void Draw(std::vector<std::string> &outdirs);
};
#endif
<file_sep>/Analysis/src/weighter.cc
#include <ChargedAnalysis/Analysis/include/weighter.h>
Weighter::Weighter(){}
Weighter::Weighter(const std::shared_ptr<TFile>& inputFile, const std::shared_ptr<TTree>& inputTree, const int& era) :
inputFile(inputFile),
inputTree(inputTree),
era(era){
float nGen = 1., xSec = 1., lumi = 1.;
isData = true;
//Read out baseline weights
if(inputFile->GetListOfKeys()->Contains("nGen")){
nGen = RUtil::Get<TH1F>(inputFile.get(), "nGen")->Integral();
}
if(inputFile->GetListOfKeys()->Contains("xSec")){
xSec = RUtil::Get<TH1F>(inputFile.get(), "xSec")->GetBinContent(1);
}
if(inputFile->GetListOfKeys()->Contains("Lumi")){
lumi = RUtil::Get<TH1F>(inputFile.get(), "Lumi")->GetBinContent(1);
}
this->baseWeight = xSec*lumi/nGen;
//Read out pile up histograms
if(inputFile->GetListOfKeys()->Contains("puMC")){
isData = false;
std::shared_ptr<TH1F> puMC = RUtil::GetSmart<TH1F>(inputFile.get(), "puMC");
pileUpWeight = RUtil::CloneSmart<TH1F>(RUtil::Get<TH1F>(inputFile.get(), "pileUp"));
pileUpWeightUp = RUtil::CloneSmart<TH1F>(RUtil::Get<TH1F>(inputFile.get(), "pileUpUp"));
pileUpWeightDown = RUtil::CloneSmart<TH1F>(RUtil::Get<TH1F>(inputFile.get(), "pileUpDown"));
pileUpWeight->Scale(1./pileUpWeight->Integral());
pileUpWeightUp->Scale(1./pileUpWeightUp->Integral());
pileUpWeightDown->Scale(1./pileUpWeightDown->Integral());
puMC->Scale(1./puMC->Integral());
pileUpWeight->Divide(puMC.get());
pileUpWeightUp->Divide(puMC.get());
pileUpWeightDown->Divide(puMC.get());
}
}
double Weighter::GetBJetWeight(const int& entry, TH2F* effB, TH2F* effC, TH2F* effLight, NTupleReader bPt, TLeaf* pt, TLeaf* eta, TLeaf* sf, TLeaf* flavour){
const std::vector<float> scaleFactor = RUtil::GetVecEntry<float>(sf, entry);
const std::vector<int> trueFlav = RUtil::GetVecEntry<int>(flavour, entry);
const std::vector<float> jetPt = RUtil::GetVecEntry<float>(pt, entry);
const std::vector<float> jetEta = RUtil::GetVecEntry<float>(eta, entry);
double wData = 1., wMC = 1.;
bPt.Reset();
for(std::size_t i = 0; i < scaleFactor.size(); ++i){
float eff;
if(std::abs(trueFlav.at(i)) == 5) eff = effB->GetBinContent(effB->FindBin(jetPt.at(i), jetEta.at(i)));
else if(std::abs(trueFlav.at(i)) == 4) eff = effC->GetBinContent(effC->FindBin(jetPt.at(i), jetEta.at(i)));
else eff = effLight->GetBinContent(effLight->FindBin(jetPt.at(i), jetEta.at(i)));
if(eff == 0 or eff == 1) continue;
if(bPt.Get() == jetPt.at(i)){
wData *= scaleFactor.at(i) * eff;
wMC *= eff;
bPt.Next();
}
else{
wData *= 1 - scaleFactor.at(i)*eff;
wMC *= (1 - eff);
}
}
return wData/wMC;
}
void Weighter::AddParticle(const std::string& pAlias, const std::string& wp, const std::experimental::source_location& location){
if(isData) return;
//Read out information of SF branches for wished particle
pt::ptree partInfo;
pt::json_parser::read_json(StrUtil::Merge(std::getenv("CHDIR"), "/ChargedAnalysis/Analysis/data/particle.json"), partInfo);
//Check if sub function configured
std::string pName = NTupleReader::GetName(partInfo, pAlias);
if(pName == "") throw std::runtime_error(StrUtil::PrettyError(std::experimental::source_location::current(), "Unknown particle alias: '", pAlias, "'!"));
if(!partInfo.get_child_optional(pName + ".scale-factors")) return;
for(const std::string& sfName : NTupleReader::GetInfo(partInfo.get_child(pName + ".scale-factors"), false)){
std::string sfWithWP = StrUtil::Replace(sfName, "[WP]", wp);
std::string sfWithWPUpper = StrUtil::Replace(sfName, "[WP]", StrUtil::Capitilize(wp));
std::vector<std::vector<NTupleReader>*> scaleFactors{&sf, &sfUp, &sfDown};
std::vector<std::function<float(const int&)>*> bWeights{&bWeight, &bWeightUp, &bWeightDown};
std::vector<std::string> shift{"", "Up", "Down"};
for(int i = 0; i < 3; ++i){
std::string branchName = RUtil::BranchExists(inputTree.get(), StrUtil::Replace(sfWithWP, "[SHIFT]", shift[i])) ? sfWithWP : sfWithWPUpper;
if(partInfo.get<std::string>(pName + ".alias") != "bj"){
scaleFactors.at(i)->push_back(std::move(NTupleReader(inputTree, era)));
scaleFactors.at(i)->back().AddParticle(pAlias, 0, wp);
scaleFactors.at(i)->back().AddFunctionByBranchName(StrUtil::Replace(branchName, "[SHIFT]", shift[i]));
scaleFactors.at(i)->back().Compile();
}
else{
std::string wpName = StrUtil::Capitilize(wp);
TH2F* effB = RUtil::Clone<TH2F>(RUtil::Get<TH2F>(inputFile.get(), StrUtil::Replace("n@BCSVbTag", "@", wpName)));
effB->Divide(RUtil::Get<TH2F>(inputFile.get(), "nTrueB"));
TH2F* effC = RUtil::Clone<TH2F>(RUtil::Get<TH2F>(inputFile.get(), StrUtil::Replace("n@CCSVbTag", "@", wpName)));
effC->Divide(RUtil::Get<TH2F>(inputFile.get(), "nTrueC"));
TH2F* effLight = RUtil::Clone<TH2F>(RUtil::Get<TH2F>(inputFile.get(), StrUtil::Replace("n@LightCSVbTag", "@", wpName)));
effLight->Divide(RUtil::Get<TH2F>(inputFile.get(), "nTrueLight"));
NTupleReader bPt = NTupleReader(inputTree, era);
bPt.AddParticle("bj", 0, wp);
bPt.AddFunction("pt");
bPt.Compile();
*bWeights[i] = std::bind(&Weighter::GetBJetWeight, std::placeholders::_1, effB, effC, effLight, bPt, RUtil::Get<TLeaf>(inputTree.get(), "Jet_Pt"), RUtil::Get<TLeaf>(inputTree.get(), "Jet_Eta"), RUtil::Get<TLeaf>(inputTree.get(), StrUtil::Replace(branchName, "[SHIFT]", shift[i])), RUtil::Get<TLeaf>(inputTree.get(), "Jet_TrueFlavour"));
}
}
}
}
double Weighter::GetBaseWeight(const std::size_t& entry){
if(isData) return 1.;
double puWeight = 1.;
if(pileUpWeight){
std::size_t bin = RUtil::GetEntry<char>(RUtil::Get<TLeaf>(inputTree.get(), "Misc_TrueInteraction"), entry);
puWeight = pileUpWeight->GetBinContent(pileUpWeight->FindBin(bin));
}
return this->baseWeight*puWeight;
}
double Weighter::GetPartWeight(const std::size_t& entry){
if(isData) return 1.;
double partWeight = 1.;
for(int i = 0; i < sf.size(); ++i){
sf[i].Reset();
while(true){
float weight = sf[i].Get();
sf[i].Next();
if(weight != -999.) partWeight *= weight != 0 ? weight : 1.;
break;
}
}
try{
partWeight *= bWeight(entry);
}
catch(...){}
return partWeight;
}
double Weighter::GetTotalWeight(const std::size_t& entry){
if(isData) return 1.;
return GetBaseWeight(entry) * GetPartWeight(entry);
}
<file_sep>/Utility/src/frame.cc
#include <ChargedAnalysis/Utility/include/frame.h>
Frame::Frame(){
}
Frame::Frame(const std::string& inFile){
//Read file
std::ifstream myFile(inFile, std::ifstream::in);
std::string line;
if(!myFile.is_open()){
throw std::runtime_error("File can not be opened: " + inFile);
}
std::cout << "Read file: " << inFile << std::endl;
//Get header
std::getline(myFile, line);
labels = Utils::SplitString<std::string>(line, "\t");
//Read other columns
while(std::getline(myFile, line)){
std::vector<float> column = Utils::SplitString<float>(line, "\t");
this->AddColumn(column);
}
myFile.close();
}
Frame::Frame(const std::vector<std::string>& inFiles){
for(std::vector<std::string>::const_iterator file = inFiles.begin(); file != inFiles.end(); ++file){
//Read file
std::ifstream myFile(*file, std::ifstream::in);
std::string line;
if(!myFile.is_open()){
throw std::runtime_error("File can not be opened: " + *file);
}
//Get header
std::getline(myFile, line);
if(file == inFiles.begin()){
labels = Utils::SplitString<std::string>(line, "\t");
}
//Read other columns
while(std::getline(myFile, line)){
std::vector<float> column = Utils::SplitString<float>(line, "\t");
this->AddColumn(column);
}
myFile.close();
}
}
void Frame::InitLabels(const std::vector<std::string>& initLabels){
this->labels = initLabels;
}
int Frame::GetNLabels(){return labels.size();}
bool Frame::AddColumn(const std::vector<float>& column){
if(column.size() != labels.size()){
std::cout << "Length of given column (" << column.size() << ") does not match number of avaiable labels (" << labels.size() << ")!";
return false;
}
columns.push_back(column);
return true;
}
float Frame::Get(const std::string& label, const int& index){
int rowIndex = -1.;
if(index >= columns.at(0).size()) throw std::out_of_range(("Index " + std::to_string(index) + "not existing").c_str());
for(int i = 0; i < labels.size(); i++){
if(labels[i] == label){
rowIndex = i;
}
}
if(rowIndex == -1.) throw std::out_of_range(("No label existing: " + label).c_str());
return columns.at(index).at(rowIndex);
}
bool Frame::AddRow(const std::string& label, const std::vector<float>& row){
if(row.size() != columns[0].size()){
std::cout << "Length of given row (" << row.size() << ") does not match number of elements of each row in this Frame (" << columns[0].size() << ")!";
return false;
}
labels.push_back(label);
for(unsigned int i=0; i<row.size(); i++){
columns[i].push_back(row[i]);
}
return true;
}
bool Frame::DoSort(std::vector<float>& column1, std::vector<float>& column2, const int& index, const bool& ascending){
if(ascending){
return column1[index] < column2[index];
}
else{
return column1[index] > column2[index];
}
}
void Frame::Sort(const std::string& label, const bool& ascending){
int rowIndex = std::distance(labels.begin(), std::find(labels.begin(), labels.end(), label));
std::sort(columns.begin(), columns.end(), std::bind(DoSort, std::placeholders::_1, std::placeholders::_2, rowIndex, ascending));
}
void Frame::WriteCSV(const std::string& fileName){
std::ofstream myFile;
myFile.open(fileName);
std::string header;
for(std::string& label: labels){
header+= label + "\t";
}
header.replace(header.end()-1, header.end(), "\n");
myFile << header;
for(std::vector<float>& column: columns){
std::string columnLine;
for(float& value: column){
columnLine+= std::to_string(value) + "\t";
}
columnLine.replace(columnLine.end()-1, columnLine.end(), "\n");
myFile << columnLine;
}
myFile.close();
std::cout << "Merged file: " << fileName << std::endl;
}
<file_sep>/Analysis/include/treeparser.h
#ifndef TREEPARSER
#define TREEPARSER
#include <TH1.h>
#include <ChargedAnalysis/Analysis/include/treefunction.h>
/**
* @brief Class for interpreting strings from which information for TreeFunction class execution
*
* This class interprets custom strings, which will be used to configure instances of the TreeFunction class.
*
* Example for custom strings:
*
* -# __f:n=Pt/p:n=e,i=1,wp=l/h:nxb=20,xl=20,xh=200__ (for producing histograms)
* -# __f:n=N/p:n=j/c:n=bigger,v=3f:n=N/p:n=j/c:n=bigger,v=3__ (for cutting)
*/
class TreeParser{
public:
/**
* @brief Default constructor
*/
TreeParser();
/**
* @brief Extract the 'f:' function key word from custrom string
*
* @param[in] parameter Custom string with TreeFunction configuration
* @param[in] func Treefunction instance by reference, where TreeFunction::SetFunction will be invoked
*/
void GetFunction(const std::string& parameter, TreeFunction& func);
/**
* @brief Extract the 'p:' function key word from custrom string
*
* @param[in] parameter Custom string with TreeFunction configuration
* @param[in] func Treefunction instance by reference, where TreeFunction::SetFunction will be invoked
*/
void GetParticle(const std::string& parameter, TreeFunction& func);
/**
* @brief Extract the 'c:' function key word from custrom string
*
* @param[in] parameter Custom string with TreeFunction configuration
* @param[in] func Treefunction instance by reference, where TreeFunction::SetFunction will be invoked
*/
void GetCut(const std::string& parameter, TreeFunction& func);
/**
* @brief Extract the 'h:' function key word from custrom string
*
* @param[in] parameter Custom string with TreeFunction configuration
* @param[in] hist ROOT histogram, where TH1::SetBinning will be invoked
*/
void GetBinning(const std::string& parameter, TH1* hist);
};
#endif
<file_sep>/Workflow/exesrc/analysis.py
#!/usr/bin/env python3
from taskmanager import TaskManager
from configuration import *
import os
import argparse
import yaml
import copy
import sys
import numpy
from collections import defaultdict as dd
def parser():
parser = argparse.ArgumentParser(description = "Script to handle and execute analysis tasks", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("--task", type=str, choices = ["Plot", "HTagger", "Append", "Limit", "DNN", "Slim", "Merge", "Estimate"])
parser.add_argument("--config", type=str)
parser.add_argument("--era", nargs='+', default = [""])
parser.add_argument('--dry-run', default=False, action='store_true')
parser.add_argument("--run-again", type=str)
return parser.parse_args()
def taskReturner(taskName, config):
tasks = {
"Append": lambda : append(config),
"HTagger": lambda : htagger(config),
"DNN": lambda : dnn(config),
"Plot": lambda : plot(config),
"Limit": lambda : limit(config),
"Slim": lambda : slim(config),
"Merge": lambda: mergeskim(config),
"Estimate": lambda : estimate(config),
}
return tasks[taskName]
def plot(config):
tasks = []
for channel in config["channels"]:
for era in config["era"]:
processes = sorted(config["processes"] + config.get("data", {}).get(channel, []))
for process in processes:
for syst in config["shape-systs"].get("all", []) + config["shape-systs"].get(channel, []):
for shift in ["Up", "Down"]:
treeread(tasks, config, channel, era, process, syst, shift)
mergeHists(tasks, config, channel, era, process, syst, shift)
plotting(tasks, config, channel, era, processes)
eventCount(tasks, config, channel, era, processes)
return tasks
def mergeskim(config):
tasks = []
for channel in config["channels"]:
for era in config["era"]:
for syst in config["shape-systs"].get("all", []) + config["shape-systs"].get(channel, []):
for shift in ["Up", "Down"]:
mergeSkim(tasks, config, channel, era, syst, shift)
if "dCache" in config:
tmpTask, mergeTasks = [t for t in tasks if "tmp" in t["dir"]], [t for t in tasks if "merged" in t["dir"]]
sendToDCache(mergeTasks, config, os.environ["CHDIR"])
tasks = tmpTask + mergeTasks
return tasks
def slim(config):
tasks = []
for outChannel, inChannel in config["channels"].items():
for era in config["era"]:
for syst in config["shape-systs"].get("all", []) + config["shape-systs"].get(inChannel, []):
for shift in ["Up", "Down"]:
treeslim(tasks, config, inChannel, outChannel, era, syst, shift)
mergeFiles(tasks, config, inChannel, outChannel, era, syst, shift)
if "dCache" in config:
tmpTask, mergeTasks = [t for t in tasks if "unmerged" in t["dir"]], [t for t in tasks if not "unmerged" in t["dir"]]
sendToDCache(mergeTasks, config, os.environ["CHDIR"])
tasks = tmpTask + mergeTasks
return tasks
def dnn(config):
tasks = []
for channel in config["channels"]:
for era in config["era"]:
for evType in ["Even", "Odd"]:
c = copy.deepcopy(config)
DNN(tasks, config, channel, era, evType)
return tasks
def append(config):
tasks = []
for channel in config["channels"]:
for era in config["era"]:
for syst in config["shape-systs"].get("all", []) + config["shape-systs"].get(channel, []):
for shift in ["Up", "Down"]:
treeappend(tasks, config, channel, era, syst, shift)
if "dCache" in config:
sendToDCache(tasks, config, os.environ["CHDIR"])
return tasks
def estimate(config):
tasks = []
for channel in config["channels"]:
for era in config["era"]:
for mass in config["charged-masses"]:
for process in config["estimate-process"]:
c = copy.deepcopy(config)
c["dir"] = "{}/{}-Region".format(config["dir"], process).replace("{MHC}", str(mass))
c.setdefault("cuts", {}).setdefault(channel, config["estimate-process"][process].get(channel, []) + config["estimate-process"][process].get("all", []))
c["cuts"] = {key: [cut.format_map(dd(str, {"MHC": mass})) for cut in c["cuts"][key]] for key in c["cuts"]}
processes = config["processes"] + config["data"][channel]
for procc in processes:
treeread(tasks, c, channel, era, procc, "", "", postFix = "{}_{}".format(process, str(mass)))
mergeHists(tasks, c, channel, era, procc, "", "", postFix = "{}_{}".format(process, str(mass)))
plotting(tasks, c, channel, era, processes, postFix = "{}_{}".format(process, str(mass)))
eventCount(tasks, c, channel, era, processes, postFix = "{}_{}".format(process, str(mass)))
bkgEstimation(tasks, config, channel, era, str(mass))
return tasks
def limit(config):
tasks = []
for era in config["era"]:
for channel in config["channels"]:
for mHPlus in config["charged-masses"]:
for mH in config["neutral-masses"]:
conf = copy.deepcopy(config)
conf["parameters"][channel] = [param.replace("{MHC}", str(mHPlus)) for param in config["parameters"][channel]]
conf["signal"] = config["signal"].format_map(dd(str, {"MHC": mHPlus, "MH": mH}))
conf["discriminant"] = config["discriminant"].format_map(dd(str, {"MHC": mHPlus, "MH": mH}))
conf["dir"] = config["dir"].replace("{MHC}", str(mHPlus)).replace("{MH}", str(mH))
processes = conf["backgrounds"] + [conf["signal"]] + conf["data"][channel]
for procc in processes:
treeread(tasks, conf, channel, era, procc, "", "", postFix = "{}_{}".format(mHPlus, mH))
mergeHists(tasks, conf, channel, era, procc, "", "", postFix = "{}_{}".format(mHPlus, mH))
plotting(tasks, conf, channel, era, processes, postFix = "{}_{}".format(mHPlus, mH))
datacard(tasks, conf, channel, era, processes, mHPlus, mH)
limits(tasks, conf, channel, era, mHPlus, mH)
conf = copy.deepcopy(config)
conf["dir"] = config["dir"].replace("{MHC}", "").replace("{MH}", "")
plotlimit(tasks, conf, channel, era)
for mHPlus in config["charged-masses"]:
for mH in config["neutral-masses"]:
conf = copy.deepcopy(config)
conf["dir"] = config["dir"].replace("{MHC}", str(mHPlus)).replace("{MH}", str(mH))
for era in config["era"]:
mergeDataCards(tasks, conf, {"Combined": config["channels"]}, era, mHPlus, mH)
limits(tasks, conf, "Combined", era, mHPlus, mH)
for channel in config["channels"]:
mergeDataCards(tasks, conf, channel, {"RunII": config["era"]}, mHPlus, mH)
limits(tasks, conf, channel, "RunII", mHPlus, mH)
mergeDataCards(tasks, conf, {"Combined": config["channels"]}, {"RunII": config["era"]}, mHPlus, mH)
limits(tasks, conf, "Combined", "RunII", mHPlus, mH)
config["dir"] = config["dir"].replace("{MHC}", "").replace("{MH}", "")
for era in config["era"]:
plotlimit(tasks, config, "Combined", era)
for channel in config["channels"]:
plotlimit(tasks, config, channel, "RunII")
plotlimit(tasks, config, "Combined", "RunII")
return tasks
def main():
args = parser()
tasks = []
taskDir = ""
##Read general config and update with given config
if args.config:
confDir = "{}/ChargedAnalysis/Workflow/config/".format(os.environ["CHDIR"])
config = yaml.load(open("{}/general.yaml".format(confDir), "r"), Loader=yaml.Loader)
config.update(yaml.load(open("{}/{}.yaml".format(confDir, args.config), "r"), Loader=yaml.Loader))
taskDir = "{}/Results/{}/{}".format(os.environ["CHDIR"], args.task, config["dir"].split("/")[0])
os.makedirs(taskDir, exist_ok = True)
with open("{}/config.yaml".format(taskDir), "w") as conf:
yaml.dump(config, conf, default_flow_style=False, indent=4)
config["dir"] = "{}/Results/{}/{}".format(os.environ["CHDIR"], args.task, config["dir"])
config["era"] = args.era
##Configure and get the tasks
tasks = taskReturner(args.task, config)()
elif args.run_again:
taskDir = "/".join(args.run_again.split("/")[:-1])
##Run the manager
manager = TaskManager(tasks = tasks, existingFlow = args.run_again, dir = taskDir)
manager.run(args.dry_run)
if __name__=="__main__":
main()
<file_sep>/Analysis/exesrc/treeread.cc
#include <ChargedAnalysis/Utility/include/parser.h>
#include <ChargedAnalysis/Analysis/include/treereader.h>
int main(int argc, char* argv[]){
//Parser arguments
Parser parser(argc, argv);
std::string fileName = parser.GetValue<std::string>("filename");
std::vector<std::string> parameters = parser.GetVector<std::string>("parameters");
std::vector<std::string> cuts = parser.GetVector<std::string>("cuts", {});
std::string outDir = parser.GetValue<std::string>("out-dir");
std::string outFile = parser.GetValue<std::string>("out-file");
std::string channel = parser.GetValue<std::string>("channel");
std::string cleanJet = parser.GetValue<std::string>("clean-jet", "");
std::vector<std::string> scaleDirs = parser.GetVector<std::string>("syst-dirs", {});
std::vector<std::string> scaleSysts = parser.GetVector<std::string>("scale-syst", {""});
std::string scaleFactors = parser.GetValue<std::string>("scale-factors", "");
int era = parser.GetValue<int>("era", 2017);
//Create treereader instance
TreeReader reader(parameters, cuts, outDir, outFile, channel, scaleDirs, scaleSysts, scaleFactors, era);
reader.EventLoop(fileName, cleanJet);
}
<file_sep>/Utility/src/csv.cc
#include <ChargedAnalysis/Utility/include/csv.h>
CSV::CSV(const std::string& fileName, const std::string& fileMode, const std::string& delim, const std::experimental::source_location& location) :
CSV(fileName, fileMode, {}, delim, location)
{}
CSV::CSV(const std::string& fileName, const std::string& fileMode, const std::vector<std::string>& colNames, const std::string& delim, const std::experimental::source_location& location):
mode(fileMode),
delim(delim),
colNames(colNames) {
//Translate given file mode into std::fstream file modes
std::map<std::string, std::ios_base::openmode> modes = {
{"r", std::ios_base::in},
{"w", std::ios_base::out},
{"rw", std::ios_base::in | std::ios_base::out | std::ios_base::app},
{"w+", std::ios_base::out | std::ios_base::trunc}
};
if(!modes.count(fileMode)){
throw std::runtime_error(StrUtil::PrettyError(location, "Invalid file mode: '", fileMode, "'!"));
}
//Create directory if not already there
if(StrUtil::Split(fileName, "/").size() > 1){
std::string dir;
for(const std::string s : VUtil::Slice(StrUtil::Split(fileName, "/"), 0, -1)){
dir += s + "/";
}
if(!std::filesystem::exists(dir)) std::filesystem::create_directories(dir);
}
//Open file
file.open(fileName, modes[fileMode]);
if(!file.is_open()){
throw std::runtime_error(StrUtil::PrettyError(location, "Could not open file: '", fileName, "'!"));
}
//Save in read mode for each line length of line for later read out
if(!StrUtil::Find(fileMode, "r").empty()){
std::string line;
//Read out header (which is assumed to exist)
std::getline(file, line);
this->colNames = StrUtil::Split(line, delim);
linePos.push_back(line.size() + 1);
//Read line lenghts for data in file
while (std::getline(file, line)){
linePos.push_back(line.size() + linePos.back() + 1);
}
linePos.pop_back();
}
//Write header in write mode
if(fileMode == "w" or fileMode == "w+"){
file.clear();
if(colNames.empty()){
throw std::runtime_error(StrUtil::PrettyError(location, "No column names for write mode are given!"));
}
std::size_t lineSize = 0;
for(const std::string name : VUtil::Slice(colNames, 0, -1)){
file << name << delim;
lineSize += name.size() + delim.size();
}
file << colNames.back() << std::endl;
linePos.push_back(lineSize + colNames.back().size() + 1);
}
}
<file_sep>/Utility/src/extension.cc
/**
* @file extension.cc
* @brief Source file for Extension name space, see extension.h
*/
#include <ChargedAnalysis/Utility/include/extension.h>
std::map<std::string, std::vector<float>> Extension::HScore(std::shared_ptr<TFile>& file, const std::string& channel, const int& era){
//Set values with default values
std::map<std::string, std::vector<float>> values;
std::vector<std::string> branchNames;
if(Utils::Find<std::string>(channel, "2FJ") == -1.) branchNames = {"ML_HTagFJ1"};
else branchNames = {"HTag_FJ1", "HTag_FJ2"};
//Path with DNN infos
std::string dnnPath = std::string(std::getenv("CHDIR")) + "/DNN";
int nEntries = file->Get<TTree>(channel.c_str())->GetEntries();
for(const std::string& branchName: branchNames){
values[branchName] = std::vector<float>(nEntries, -999.);
}
for(int i = 0; i < branchNames.size(); i++){
//Take time
Utils::RunTime timer;
std::unique_ptr<Frame> hyperParam = std::make_unique<Frame>(dnnPath + "/Tagger/HyperOpt/hyperparameter.csv");
//Tagger
torch::Device device(torch::kCPU);
std::vector<std::shared_ptr<HTagger>> tagger(2, std::make_shared<HTagger>(4, hyperParam->Get("nHidden", 0), hyperParam->Get("nConvFilter", 0), hyperParam->Get("kernelSize", 0), hyperParam->Get("dropOut", 0), device));
torch::load(tagger[0], StrUtil::Join("/", std::getenv("CHDIR"), "DNN/Tagger/Even", era, "htagger.pt"));
torch::load(tagger[1], StrUtil::Join("/", std::getenv("CHDIR"), "DNN/Tagger/Odd", era, "htagger.pt"));
tagger[0]->eval();
tagger[1]->eval();
torch::NoGradGuard no_grad;
std::shared_ptr<TTree> tree(static_cast<TTree*>(file->Get<TTree>(channel.c_str())->Clone()));
//Get data set
HTagDataset data = HTagDataset(file, tree, {}, "", i, device, true);
std::vector<int> entries;
//Set tree parser and tree functions
TreeParser parser;
std::vector<TreeFunction> functions;
TreeFunction evNr(file, channel);
evNr.SetFunction<Axis::X>("EvNr");
for(int i = 0; i < nEntries; i++){entries.push_back(i);}
std::vector<int>::iterator entry = entries.begin();
int batchSize = nEntries > 2500 ? 2500 : nEntries;
int counter = 0;
while(entry != entries.end()){
//For right indexing
std::vector<int> evenIndex, oddIndex;
//Put signal + background in one vector and split by even or odd numbered event
std::vector<HTensor> evenTensors;
std::vector<HTensor> oddTensors;
for(int k = 0; k < batchSize; k++){
if(*entry % 1000 == 0 and *entry != 0){
std::cout << "Processed events: " << *entry << " (" << *entry/timer.Time() << " eve/s)" << std::endl;
}
HTensor tensor = data.get(*entry);
if(int(evNr.Get<Axis::X>()) % 2 == 0){
evenTensors.push_back(tensor);
evenIndex.push_back(counter);
}
else{
oddTensors.push_back(tensor);
oddIndex.push_back(counter);
}
counter++;
++entry;
if(entry == entries.end()) break;
}
//Predictio
HTensor even, odd;
torch::Tensor evenPredict, oddPredict;
if(evenTensors.size() != 0){
even = HTagDataset::PadAndMerge(evenTensors);
evenPredict = tagger[1]->forward(even.charged, even.neutral, even.SV);
}
if(oddTensors.size() != 0){
odd = HTagDataset::PadAndMerge(oddTensors);
oddPredict = tagger[0]->forward(odd.charged, odd.neutral, odd.SV);
}
//Put all predictions back in order again
for(int j = 0; j < evenTensors.size(); j++){
values[branchNames[i]].at(evenIndex.at(j)) = evenTensors.size() != 1 ? evenPredict[j].item<float>() : evenPredict.item<float>();
}
for(int j = 0; j < oddTensors.size(); j++){
values[branchNames[i]].at(oddIndex.at(j)) = oddTensors.size() != 1 ? oddPredict[j].item<float>() : oddPredict.item<float>();
}
}
}
return values;
}
std::map<std::string, std::vector<float>> Extension::DNNScore(std::shared_ptr<TFile>& file, const std::string& channel, const int& era){
//Set values with default values
std::map<std::string, std::vector<float>> values;
//Take time
Utils::RunTime timer;
std::shared_ptr<TTree> tree = RUtil::CloneSmart<TTree>(RUtil::Get<TTree>(file.get(), channel));
int nEntries = tree->GetEntries();
//Path with DNN infos
std::string dnnPath = std::string(std::getenv("CHDIR")) + "/Results/DNN/";
//Set tree parser and tree functions
Decoder parser;
std::vector<NTupleReader> functions;
TLeaf* evNr = RUtil::Get<TLeaf>(tree.get(), "Misc_eventNumber");
//Read txt with parameter used in the trainind and set tree function
std::ifstream params(StrUtil::Join("/", dnnPath, "Main", channel, era, "Even/parameter.txt"));
std::string parameter;
while(getline(params, parameter)){
NTupleReader func(tree, era);
parser.GetParticle(parameter, func);
parser.GetFunction(parameter, func);
func.Compile();
functions.push_back(func);
}
params.close();
//Get classes
std::ifstream clsFile(StrUtil::Join("/", dnnPath, "Main", channel, era, "Even/classes.txt"));
std::string cls;
std::vector<std::string> classes;
while(getline(clsFile, cls)){
classes.push_back(cls);
}
classes.push_back("HPlus");
clsFile.close();
//Get classes
std::ifstream massFile(StrUtil::Join("/", dnnPath, "Main", channel, era, "Even/masses.txt"));
std::string mass;
std::vector<int> masses;
while(getline(massFile, mass)){
masses.push_back(std::atoi(mass.c_str()));
}
massFile.close();
//Define branch names
std::vector<std::string> branchNames;
for(int& mass : masses){
for(std::string& cls : classes){
branchNames.push_back(StrUtil::Merge("DNN_", cls, mass));
values[branchNames.back()] = std::vector<float>(nEntries, -999.);
}
}
for(int& mass : masses){
branchNames.push_back(StrUtil::Merge("DNN_Class", mass));
values[branchNames.back()] = std::vector<float>(nEntries, -999.);
}
//Frame with optimized hyperparameter
std::unique_ptr<Frame> hyperParam = std::make_unique<Frame>(StrUtil::Join("/", dnnPath, "HyperOpt", channel, era, "hyperparameter.csv"));
//Get/load model and set to evaluation mode
torch::Device device(torch::kCPU);
std::vector<std::shared_ptr<DNNModel>> model(2, std::make_shared<DNNModel>(functions.size(), hyperParam->Get("n-nodes", 0), hyperParam->Get("n-layers", 0), hyperParam->Get("drop-out", 0), true, classes.size(), device));
model[0]->eval();
model[1]->eval();
model[0]->Print();
torch::load(model[0], StrUtil::Join("/", dnnPath, "Main", channel, era, "Even/model.pt"));
torch::load(model[1], StrUtil::Join("/", dnnPath, "Main", channel, era, "Odd/model.pt"));
torch::NoGradGuard no_grad;
std::vector<int> entries;
for(int i = 0; i < nEntries; i++){entries.push_back(i);}
std::vector<int>::iterator entry = entries.begin();
int batchSize = nEntries > 2500 ? 2500 : nEntries;
int counter = 0;
while(entry != entries.end()){
//For right indexing
std::vector<int> evenIndex, oddIndex;
//Put signal + background in one vector and split by even or odd numbered event
std::vector<torch::Tensor> evenTensors;
std::vector<torch::Tensor> oddTensors;
for(int j = 0; j < batchSize; j++){
if(*entry % 1000 == 0 and *entry != 0){
std::cout << "Processed events: " << *entry << " (" << *entry/timer.Time() << " eve/s)" << std::endl;
}
NTupleReader::SetEntry(*entry);
//Fill event class with particle content
std::vector<float> paramValues;
for(int i=0; i < functions.size(); ++i){
paramValues.push_back(functions[i].Get());
}
if(int(1/RUtil::GetEntry<float>(evNr, *entry)*10e10) % 2 == 0){
evenTensors.push_back(torch::from_blob(paramValues.data(), {1, paramValues.size()}).clone().to(device));
evenIndex.push_back(counter);
}
else{
oddTensors.push_back(torch::from_blob(paramValues.data(), {1, paramValues.size()}).clone().to(device));
oddIndex.push_back(counter);
}
counter++;
++entry;
if(entry == entries.end()) break;
}
for(int i = 0; i < masses.size(); ++i){
//Prediction
torch::Tensor even, odd;
torch::Tensor evenPredict, oddPredict;
if(evenTensors.size() != 0){
even = torch::cat(evenTensors, 0);
evenPredict = model[1]->forward(even, masses[i]*torch::ones({evenTensors.size(), 1}), true);
}
if(oddTensors.size() != 0){
odd = torch::cat(oddTensors, 0);
oddPredict = model[0]->forward(odd, masses[i]*torch::ones({oddTensors.size(), 1}), true);
}
//Put all predictions back in order again
for(int j = 0; j < evenTensors.size(); ++j){
for(int k = 0; k < classes.size(); ++k){
values[branchNames[k + i*classes.size()]].at(evenIndex.at(j)) = evenTensors.size() != 1 ? evenPredict.index({j, k}).item<float>() : evenPredict[k].item<float>();
}
values[StrUtil::Merge("DNN_Class", masses.at(i))].at(evenIndex.at(j)) = torch::argmax(evenPredict[j]).item<int>();
}
for(int j = 0; j < oddTensors.size(); ++j){
for(int k = 0; k < classes.size(); ++k){
values[branchNames[k + i*classes.size()]].at(oddIndex.at(j)) = oddTensors.size() != 1 ? oddPredict.index({j, k}).item<float>() : oddPredict[k].item<float>();
}
values[StrUtil::Merge("DNN_Class", masses.at(i))].at(oddIndex.at(j)) = torch::argmax(oddPredict[j]).item<int>();
}
}
}
return values;
}
std::map<std::string, std::vector<float>> Extension::HReconstruction(std::shared_ptr<TFile>& file, const std::string& channel, const int& era){
typedef ROOT::Math::LorentzVector<ROOT::Math::PtEtaPhiM4D<double>> PolarLV;
typedef ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double>> CartLV;
typedef std::vector<std::pair<PolarLV, PolarLV>> hCandVec;
//Set values with default values
std::map<std::string, std::vector<float>> values;
std::vector<std::string> branchNames = {"W_Mass", "W_Pt", "W_Phi", "H1_Pt", "H1_Eta", "H1_Phi", "H1_Mass", "H2_Pt", "H2_Eta", "H2_Phi", "H2_Mass", "HPlus_Pt", "HPlus_Mass", "HPlus_Phi"};
int nEntries = file->Get<TTree>(channel.c_str())->GetEntries();
for(const std::string& branchName: branchNames){
values[branchName] = std::vector<float>(nEntries, -999.);
}
std::string lepName = Utils::Find<std::string>(channel, "Muon") != -1. ? "mu" : "e";
float lepMass = Utils::Find<std::string>(channel, "Muon") != - 1. ? 0.10565: 0.000510;
TreeFunction LepPt(file, channel), LepEta(file, channel), LepPhi(file, channel);
LepPt.SetP1<Axis::X>(lepName, 1); LepEta.SetP1<Axis::X>(lepName, 1); LepPhi.SetP1<Axis::X>(lepName, 1);
LepPt.SetFunction<Axis::X>("Pt"); LepEta.SetFunction<Axis::X>("Eta"); LepPhi.SetFunction<Axis::X>("Phi");
TreeFunction METPt(file, channel), METPhi(file, channel);
METPt.SetP1<Axis::X>("met"); METPhi.SetP1<Axis::X>("met");
METPt.SetFunction<Axis::X>("Pt"); METPhi.SetFunction<Axis::X>("Phi");
TreeFunction nJet(file, channel), nFatJet(file, channel);
nJet.SetP1<Axis::X>("j"); nFatJet.SetP1<Axis::X>("fj");
nJet.SetFunction<Axis::X>("N"); nFatJet.SetFunction<Axis::X>("N");
TreeFunction JetPt(file, channel), JetEta(file, channel), JetPhi(file, channel), JetMass(file, channel);
JetPt.SetP1<Axis::X>("j"); JetEta.SetP1<Axis::X>("j"); JetPhi.SetP1<Axis::X>("j"); JetMass.SetP1<Axis::X>("j");
JetPt.SetFunction<Axis::X>("Pt"); JetEta.SetFunction<Axis::X>("Eta"); JetPhi.SetFunction<Axis::X>("Phi"); JetMass.SetFunction<Axis::X>("Mass");
TreeFunction FatJetPt(file, channel), FatJetEta(file, channel), FatJetPhi(file, channel), FatJetMass(file, channel);
FatJetPt.SetP1<Axis::X>("fj"); FatJetEta.SetP1<Axis::X>("fj"); FatJetPhi.SetP1<Axis::X>("fj"); FatJetMass.SetP1<Axis::X>("fj");
FatJetPt.SetFunction<Axis::X>("Pt"); FatJetEta.SetFunction<Axis::X>("Eta"); FatJetPhi.SetFunction<Axis::X>("Phi"); FatJetMass.SetFunction<Axis::X>("Mass");
float pXNu, pYNu, pXLep, pYLep, pZLep, mW;
for(int i = 0; i < nEntries; i++){
TreeFunction::SetEntry(i);
PolarLV LepLV(LepPt.Get<Axis::X>(), LepEta.Get<Axis::X>(), LepPhi.Get<Axis::X>(), lepMass);
PolarLV W = LepLV + PolarLV(METPt.Get<Axis::X>(), 0, METPhi.Get<Axis::X>(), 0);
values["W_Mass"][i] = W.M();
values["W_Pt"][i] = W.Pt();
values["W_Phi"][i] = W.Phi();
std::vector<PolarLV> jets;
std::vector<PolarLV> fatJets;
for(unsigned int k = 0; k < nJet.Get<Axis::X>(); k++){
JetPt.SetP1<Axis::X>("j", k+1); JetEta.SetP1<Axis::X>("j", k+1); JetPhi.SetP1<Axis::X>("j", k+1); JetMass.SetP1<Axis::X>("j", k+1);
jets.push_back(PolarLV(JetPt.Get<Axis::X>(), JetEta.Get<Axis::X>(), JetPhi.Get<Axis::X>(), JetMass.Get<Axis::X>()));
}
for(unsigned int k = 0; k < nFatJet.Get<Axis::X>(); k++){
FatJetPt.SetP1<Axis::X>("fj", k+1); FatJetEta.SetP1<Axis::X>("fj", k+1); FatJetPhi.SetP1<Axis::X>("fj", k+1); FatJetMass.SetP1<Axis::X>("fj", k+1);
fatJets.push_back(PolarLV(FatJetPt.Get<Axis::X>(), FatJetEta.Get<Axis::X>(), FatJetPhi.Get<Axis::X>(), FatJetMass.Get<Axis::X>()));
}
//Intermediate step to save all possible combinations of two jets from jet collection
std::vector<std::pair<int, int>> combi;
for(unsigned int k = 0; k < jets.size(); k++){
for(unsigned int j = 0; j < k; j++){
combi.push_back({k, j});
}
}
//Vector of candPairs
hCandVec hCands;
//If 4 jets and no fat jets
if(jets.size() >= 4){
//Construct all pairs of possible jet pairs
for(unsigned int k = 0; k < combi.size(); k++){
for(unsigned int j = 0; j < k; j++){
//Check if not same jet in both pair
std::set<int> check = {combi[k].first, combi[k].second, combi[j].first, combi[j].second};
if(check.size() == 4){
hCands.push_back({jets[combi[k].first] + jets[combi[k].second], jets[combi[j].first] + jets[combi[j].second]});
}
}
}
}
//If 2 jets and one fat jet
else if(jets.size() >= 2 and fatJets.size() == 1){
for(std::pair<int, int> jetIndex: combi){
hCands.push_back({fatJets[0], jets[jetIndex.first] + jets[jetIndex.second]});
}
}
//If 2 fat jets
else if(fatJets.size() == 2){
hCands.push_back({fatJets[0], fatJets[1]});
}
//If not right jet configuration is given
else continue;
//Sort candPairs for mass diff of jet pairs, where index 0 is the best pair
std::function<bool(std::pair<PolarLV, PolarLV>, std::pair<PolarLV, PolarLV>)> sortFunc = [&](std::pair<PolarLV, PolarLV> cands1, std::pair<PolarLV, PolarLV> cands2){
return ROOT::Math::VectorUtil::DeltaR(cands1.first, cands1.second) > ROOT::Math::VectorUtil::DeltaR(cands2.first, cands2.second);
};
std::sort(hCands.begin(), hCands.end(), sortFunc);
PolarLV Hc1 = hCands[0].first + W;
PolarLV Hc2 = hCands[0].second + W;
if(ROOT::Math::VectorUtil::DeltaPhi(hCands[0].first, Hc1) < ROOT::Math::VectorUtil::DeltaPhi(hCands[0].second, Hc2)){
values["H1_Pt"][i] = hCands[0].first.Pt();
values["H1_Eta"][i] = hCands[0].first.Eta();
values["H1_Phi"][i] = hCands[0].first.Phi();
values["H1_Mass"][i] = hCands[0].first.M();
values["H2_Pt"][i] = hCands[0].second.Pt();
values["H2_Eta"][i] = hCands[0].second.Eta();
values["H2_Phi"][i] = hCands[0].second.Phi();
values["H2_Mass"][i] = hCands[0].second.M();
values["HPlus_Mass"][i] = Hc1.M();
values["HPlus_Pt"][i] = Hc1.Pt();
values["HPlus_Phi"][i] = Hc1.Phi();
}
else{
values["H1_Pt"][i] = hCands[0].second.Pt();
values["H1_Eta"][i] = hCands[0].second.Eta();
values["H1_Phi"][i] = hCands[0].second.Phi();
values["H1_Mass"][i] = hCands[0].second.M();
values["H2_Pt"][i] = hCands[0].first.Pt();
values["H2_Eta"][i] = hCands[0].first.Eta();
values["H2_Phi"][i] = hCands[0].first.Phi();
values["H2_Mass"][i] = hCands[0].first.M();
values["HPlus_Mass"][i] = Hc2.M();
values["HPlus_Phi"][i] = Hc2.Phi();
values["HPlus_Pt"][i] = Hc2.Pt();
}
}
return values;
}
<file_sep>/Utility/include/parser.h
#ifndef PARSER_H
#define PARSER_H
#include <vector>
#include <string>
#include <map>
#include <iostream>
#include <sstream>
class Parser{
private:
std::map<std::string, std::vector<std::string>> options;
public:
Parser(int argc, char** argv);
template <typename T>
T GetValue(const std::string& option);
template <typename T>
T GetValue(const std::string& option, const T& defaultValue);
template <typename T>
std::vector<T> GetVector(const std::string& option);
template <typename T>
std::vector<T> GetVector(const std::string& option, const std::vector<T>& defaultValue);
};
#endif
<file_sep>/Analysis/exesrc/plotlimit.cc
#include <string>
#include <vector>
#include <ChargedAnalysis/Analysis/include/plotterLimit.h>
#include <ChargedAnalysis/Utility/include/parser.h>
int main(int argc, char* argv[]){
//Parser arguments
Parser parser(argc, argv);
std::vector<int> chargedMasses = parser.GetVector<int>("charged-masses");
std::vector<int> neutralMasses = parser.GetVector<int>("neutral-masses");
std::string era = parser.GetValue<std::string>("era");
std::string channel = parser.GetValue<std::string>("channel");
std::vector<std::string> limitFiles = parser.GetVector<std::string>("limit-files");
std::vector<std::string> outDirs = parser.GetVector<std::string>("out-dirs");
std::vector<float> xSecs = parser.GetVector<float>("x-secs");
//Call and run Plotter1D class
PlotterLimit plotter(limitFiles, chargedMasses, neutralMasses, channel, era, xSecs);
plotter.ConfigureHists();
plotter.Draw(outDirs);
}
<file_sep>/Analysis/exesrc/treeappend.cc
#include <ChargedAnalysis/Analysis/include/treeappender.h>
#include <ChargedAnalysis/Utility/include/parser.h>
#include <ChargedAnalysis/Utility/include/rootutil.h>
#include <torch/torch.h>
int main(int argc, char* argv[]){
//Parser arguments
Parser parser(argc, argv);
std::string fileName = parser.GetValue<std::string>("out-file");
std::string treeName = parser.GetValue<std::string>("tree-name");
int era = parser.GetValue<int>("era");
std::vector<std::string> functions = parser.GetVector<std::string>("functions");
std::string tmpFile = "tmp_" + std::to_string(getpid()) + ".root";
TreeAppender appender(fileName, treeName, era, functions);
appender.Append(tmpFile);
if(RUtil::Open(tmpFile)) std::system(("mv -vf " + tmpFile + " " + fileName).c_str());
}
<file_sep>/Utility/include/frame.h
#ifndef FRAME_H
#define FRAME_H
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <functional>
#include <fstream>
#include <exception>
#include <ChargedAnalysis/Utility/include/utils.h>
class Frame{
private:
std::vector<std::string> labels;
std::vector<std::vector<float>> columns;
static bool DoSort(std::vector<float>& column1, std::vector<float>& column2, const int& index, const bool& ascending);
public:
Frame();
Frame(const std::string& inFile);
Frame(const std::vector<std::string>& inFiles);
float Get(const std::string& label, const int& index);
void InitLabels(const std::vector<std::string>& initLabels);
int GetNLabels();
bool AddRow(const std::string& label, const std::vector<float>& row);
bool AddColumn(const std::vector<float>& column);
void Sort(const std::string& label, const bool& ascending=false);
void WriteCSV(const std::string& fileName);
};
#endif
<file_sep>/Analysis/include/treefunction.h
#ifndef TREEFUNCTION_H
#define TREEFUNCTION_H
#include <string>
#include <vector>
#include <map>
#include <iostream>
#include <cctype>
#include <tuple>
#include <memory>
#include <TLeaf.h>
#include <TTree.h>
#include <TFile.h>
#include <TH2F.h>
#include <ChargedAnalysis/Utility/include/utils.h>
#include <ChargedAnalysis/Utility/include/stringutil.h>
#include <ChargedAnalysis/Utility/include/vectorutil.h>
#include <ChargedAnalysis/Utility/include/rootutil.h>
#include <ChargedAnalysis/Utility/include/mathutil.h>
enum class Axis{X, Y};
class TreeFunction{
private:
enum Particle{VACUUM, ELECTRON = 11, MUON = 13, BJET = 6, BSUBJET, JET, FATJET, SUBJET, MET = 12, HIGGS = 25, CHAREDHIGGS = 37, W = 24, TRACK};
enum WP{NONE, LOOSE, MEDIUM, TIGHT, NOTCLEAN = -10};
enum Comparison{BIGGER, SMALLER, EQUAL, DIVISIBLE, NOTDIVISIBLE};
enum Systematic{NOMINAL, BTAG, SUBBTAG, MUTRIGG, MUID, MUISO, ELERECO, ELEID};
enum Shift{NON, UP, DOWN};
void(TreeFunction::*funcPtr)();
std::string inputValue;
std::shared_ptr<TFile> inputFile;
TTree* inputTree;
int era;
bool useSyst;
std::vector<Systematic> systematics;
//Define another TreeFunction if wants to make 2D distributions
std::shared_ptr<TreeFunction> yFunction;
Comparison comp;
float compValue;
float value;
float weight;
std::vector<float> systWeights;
std::string partLabel1 = "", partLabel2 = "", partName1 = "", partName2 = "", wpName1 = "", wpName2 = "";
std::string name, axisLabel, cutLabel;
inline static int entry = 0;
std::map<std::string, std::tuple<void(TreeFunction::*)(), std::string>> funcInfo;
std::map<std::string, std::tuple<Particle, std::string, std::string, std::string>> partInfo;
std::map<std::string, std::tuple<WP, std::string>> wpInfo;
std::map<std::string, std::tuple<Comparison, std::string>> comparisons;
std::map<std::string, Systematic> systInfo;
//General TLeafes
std::vector<TLeaf*> quantities;
//Particle specific
TLeaf* particleID;
TLeaf* motherID;
TLeaf* nPart1;
TLeaf* nPart2;
TLeaf* ID;
TLeaf* Isolation;
TLeaf* BScore;
TLeaf* TrueFlavour;
std::map<Systematic, TLeaf*> scaleFactors, scaleFactorsUp, scaleFactorsDown;
//BTag Histo
TH2F* effB;
TH2F* effC;
TH2F* effLight;
//B Cut values
std::map<int, float> looseBCut = {{2016, 0.2217}, {2017, 0.1522}, {2018, 0.1241}};
std::map<int, float> mediumBCut = {{2016, 0.6321}, {2017, 0.4941}, {2018, 0.4184}};
std::map<int, float> tightBCut = {{2016, 0.8953}, {2017, 0.8001}, {2018, 0.7527}};
//Particle information
Particle part1 = VACUUM, part2 = VACUUM;
WP wp1 = NONE, wp2 = NONE;
int idx1 = -1., idx2 = -1., genMother1 = -1., genMother2 = -1., realIdx1, realIdx2;
WP whichWP(const Particle& part, const int& idx);
int whichIndex(TLeaf* nPart, const Particle& part, const int& idx, const WP& wp, const int& genMother = -1.);
bool isCleanJet(const int& idx);
Particle cleanPart = VACUUM; WP cleanedWP = NONE;
TLeaf* cleanPhi;
TLeaf* cleanEta;
TLeaf* jetPhi;
TLeaf* jetEta;
//TreeFunction to get wished values
void Pt();
void Mt();
void Phi();
void Eta();
void Mass();
void DeltaR();
void DeltaPhi();
void JetSubtiness();
void EventNumber();
void HT();
void NParticle();
void HTag();
void DNNClass();
void DNN();
void DeepAK();
void DeepAKClass();
void Count();
public:
TreeFunction(std::shared_ptr<TFile>& inputFile, const std::string& treeName, const int& era = 2017, const bool& useSyst = false);
~TreeFunction();
//Setter function
template<Axis A>
void SetP1(const std::string& part, const int& idx = 0, const std::string& wp = "", const int& genMother = -1.);
template<Axis A>
void SetP2(const std::string& part, const int& idx = 0, const std::string& wp = "", const int& genMother = -1.);
template<Axis A>
void SetFunction(const std::string& funcName, const std::string& inputValue = "");
template<Axis A>
void SetCleanJet(const std::string& part, const std::string& wp);
void SetSystematics(const std::vector<std::string>& systNames);
void SetCut(const std::string& comp, const float& compValue);
//Getter function
template<Axis A>
const float Get();
template<Axis A>
const std::string GetAxisLabel();
template<Axis A>
const std::string GetName();
const float GetWeight(const Systematic syst = NOMINAL, const Shift& shift = NON);
const std::vector<float> GetSystWeight();
const bool GetPassed();
const std::string GetCutLabel();
//Set y axis
void SetYAxis();
const bool hasYAxis();
//Static function for global configuration of all instances
static void SetEntry(const int& entry);
};
#endif A_
<file_sep>/Utility/exesrc/mergeCSV.cc
#include <ChargedAnalysis/Utility/include/parser.h>
#include <ChargedAnalysis/Utility/include/frame.h>
int main(int argc, char* argv[]){
//Extract informations of command line
Parser parser(argc, argv);
std::vector<std::string> inFiles = parser.GetVector<std::string>("input");
std::string outName = parser.GetValue<std::string>("output");
Frame frame(inFiles);
frame.WriteCSV(outName);
}
<file_sep>/Utility/include/datacard.h
#ifndef DATACARD_H
#define DATACARD_H
#include <vector>
#include <string>
#include <utility>
#include <map>
#include <fstream>
#include <iomanip>
#include <TFile.h>
#include <TH1F.h>
#include <ChargedAnalysis/Utility/include/stringutil.h>
#include <ChargedAnalysis/Utility/include/rootutil.h>
class Datacard {
private:
std::string outDir, channel, data, dataFile, sigProcess;
std::vector<std::string> bkgProcesses, bkgFiles, sigFiles, systematics;
std::map<std::string, float> rates; //Key : process
public:
Datacard();
Datacard(const std::string& outDir, const std::string& channel, const std::vector<std::string>& bkgProcesses, const std::vector<std::string>& bkgFiles, const std::string& sigProcess, const std::vector<std::string>& sigFiles, const std::string& data, const std::string& dataFile, const std::vector<std::string>& systematics);
void GetHists(const std::string& discriminant);
void Write();
};
#endif
<file_sep>/Analysis/include/plotter.h
#ifndef PLOTTER_H
#define PLOTTER_H
#include <string>
#include <map>
#include <vector>
#include <iostream>
#include <TLatex.h>
#include <TGaxis.h>
#include <TError.h>
#include <TGraph.h>
#include <TROOT.h>
#include <TLegend.h>
#include <TLegendEntry.h>
#include <TCanvas.h>
#include <TStyle.h>
#include <TH1.h>
#include <TH2F.h>
#include <TPad.h>
#include <ChargedAnalysis/Utility/include/plotutil.h>
class Plotter{
protected:
std::map<std::string, int> colors;
std::string histdir;
public:
Plotter();
Plotter(const std::string& histdir);
virtual void ConfigureHists() = 0;
virtual void Draw(std::vector<std::string> &outdirs) = 0;
};
#endif
<file_sep>/Analysis/exesrc/compareDAK8vsHTag.cc
#include <string>
#include <TFile.h>
#include <TCanvas.h>
#include <TGraph.h>
#include <ChargedAnalysis/Utility/include/plotutil.h>
#include <ChargedAnalysis/Analysis/include/treefunction.h>
#include <ChargedAnalysis/Utility/include/utils.h>
#include <ChargedAnalysis/Utility/include/stringutil.h>
int main(){
for(const std::string& channel: {"Ele2J1FJ", "Muon2J1FJ", "Ele2FJ", "Muon2FJ"}){
std::shared_ptr<TFile> bkgFile = std::make_shared<TFile>(StrUtil::Replace("@/Skim/Channels/@/TTToSemiLeptonic_TuneCP5_PSweights_13TeV-powheg-pythia8/merged/TTToSemiLeptonic_TuneCP5_PSweights_13TeV-powheg-pythia8.root", "@", std::getenv("CHDIR"), channel).c_str(), "READ");
std::vector<float> predDeepAK;
std::vector<float> predHTagAK;
std::vector<int> truth;
TreeFunction bkgDeepAK(bkgFile, channel);
TreeFunction bkgHTag(bkgFile, channel);
bkgDeepAK.SetP1<Axis::X>("fj", 1, "");
bkgDeepAK.SetFunction<Axis::X>("DAK8", "top");
bkgHTag.SetP1<Axis::X>("fj", 1, "");
bkgHTag.SetFunction<Axis::X>("HTag");
for(int i = 0; i < bkgFile->Get<TTree>(channel.c_str())->GetEntries(); i++){
TreeFunction::SetEntry(i);
predDeepAK.push_back(bkgDeepAK.Get<Axis::X>());
predHTagAK.push_back(bkgHTag.Get<Axis::X>());
truth.push_back(0);
}
for(const std::string& mass : {"200", "400", "600"}){
std::shared_ptr<TFile> sigFile = std::make_shared<TFile>(StrUtil::Replace("@/Skim/Channels/@/HPlusAndH_ToWHH_ToL4B_@_100/merged/HPlusAndH_ToWHH_ToL4B_@_100.root", "@", std::getenv("CHDIR"), channel, mass, mass).c_str(), "READ");
TreeFunction sigDeepAK(sigFile, channel);
TreeFunction sigHTag(sigFile, channel);
sigDeepAK.SetP1<Axis::X>("fj", 1, "");
sigDeepAK.SetFunction<Axis::X>("DAK8", "top");
sigHTag.SetP1<Axis::X>("fj", 1, "");
sigHTag.SetFunction<Axis::X>("HTag");
for(int i = 0; i < sigFile->Get<TTree>(channel.c_str())->GetEntries(); i++){
TreeFunction::SetEntry(i);
predDeepAK.push_back(sigDeepAK.Get<Axis::X>());
predHTagAK.push_back(sigHTag.Get<Axis::X>());
truth.push_back(1);
}
PUtil::SetStyle();
TCanvas* canvas = new TCanvas("canvas", "canvas", 1000, 1000);
TGraph* deepAKROC = Utils::GetROC(predDeepAK, truth);
TGraph* HTagROC = Utils::GetROC(predHTagAK, truth);
TLegend* legend = new TLegend(0., 0., 1, 1);
legend->AddEntry(deepAKROC, "DeepAK8", "P");
legend->AddEntry(HTagROC, "Higgs Tagger", "P");
deepAKROC->SetMarkerStyle(21);
deepAKROC->SetMarkerColor(kBlack);
HTagROC->SetMarkerStyle(22);
HTagROC->SetMarkerColor(kViolet);
PUtil::SetPad(canvas);
PUtil::SetHist(canvas, deepAKROC->GetHistogram(), "p(True positive)");
deepAKROC->GetHistogram()->GetXaxis()->SetTitle("p(False positive)");
deepAKROC->GetHistogram()->SetMaximum(1.2);
deepAKROC->Draw("AP");
HTagROC->Draw("P SAME");
PUtil::DrawHeader(canvas, "", "Work in progress");
PUtil::DrawLegend(canvas, legend, 2);
canvas->SaveAs(StrUtil::Replace("DeepAKvsHTag_@_@.pdf", "@", mass, channel).c_str());
delete deepAKROC; delete HTagROC; delete legend; delete canvas;
predDeepAK.erase(predDeepAK.begin() + bkgFile->Get<TTree>(channel.c_str())->GetEntries());
predHTagAK.erase(predHTagAK.begin() + bkgFile->Get<TTree>(channel.c_str())->GetEntries());
truth.erase(truth.begin() + bkgFile->Get<TTree>(channel.c_str())->GetEntries());
}
}
}
<file_sep>/Analysis/include/plottertriggeff.h
#ifndef PLOTTERTRIGGEFF_H
#define PLOTTERTRIGGEFF_H
#include <TH1.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TFile.h>
#include <TCanvas.h>
#include <TPad.h>
#include <TLegend.h>
#include <TGraphAsymmErrors.h>
#include <TEfficiency.h>
#include <ChargedAnalysis/Analysis/include/plotter.h>
#include <ChargedAnalysis/Utility/include/utils.h>
class PlotterTriggEff : public Plotter{
private:
std::string total;
std::vector<std::string> passed;
std::vector<std::string> processes;
std::vector<std::string> yParam;
std::map<std::string, std::string> ptNames;
std::map<std::string, std::string> phiNames;
std::map<std::string, std::string> etaNames;
std::vector<std::vector<TGraphAsymmErrors*>> bkgEfficiencies;
std::vector<std::vector<TGraphAsymmErrors*>> dataEfficiencies;
public:
PlotterTriggEff();
PlotterTriggEff(std::string &histdir, std::string &total, std::vector<std::string> &passed, std::vector<std::string> &yParam);
void ConfigureHists();
void Draw(std::vector<std::string> &outdirs);
};
#endif
<file_sep>/Utility/src/plotutil.cc
#include <ChargedAnalysis/Utility/include/plotutil.h>
void PUtil::SetStyle(){
//Style options
TGaxis::SetExponentOffset(-0.07, 0.0035, "y");
gStyle->SetLegendBorderSize(0);
gStyle->SetFillStyle(0);
gStyle->SetOptStat(0);
gStyle->SetOptTitle(0);
gROOT->SetBatch();
gErrorIgnoreLevel = kWarning;
}
void PUtil::SetPad(TPad* pad, const bool& isRatio){
float bottonMargin = 120./(pad->GetWw() * pad->GetWNDC());
float leftMargin = 160./(pad->GetWw() * pad->GetWNDC());
float rightMargin = 80./(pad->GetWw() * pad->GetWNDC());
//Pad options
pad->SetLeftMargin(leftMargin);
pad->SetRightMargin(rightMargin);
if(!isRatio) pad->SetBottomMargin(bottonMargin);
}
void PUtil::SetHist(TPad* pad, TH1* frameHist, const std::string& yLabel, const bool& isRatio){
float padWidth = pad->GetWw() * pad->GetWNDC();
float padHeight = pad->GetWh() * pad->GetHNDC();
float labelSize = 40.;
float labelDistance = 10.;
float tickSize = 40.;
//Hist options
frameHist->GetXaxis()->SetTitleSize(isRatio ? 0 : labelSize/padHeight);
frameHist->GetXaxis()->SetTitleOffset(1. + 0.25);
frameHist->GetXaxis()->SetLabelSize(isRatio ? 0 : labelSize/padHeight);
frameHist->GetXaxis()->SetLabelOffset(isRatio ? 0 : labelDistance/padHeight);
frameHist->GetXaxis()->SetTickLength(tickSize/padHeight);
if(!frameHist->InheritsFrom(TH2F::Class())) frameHist->GetYaxis()->SetTitle(yLabel.c_str());
frameHist->GetYaxis()->SetTitleSize(labelSize/padHeight);
frameHist->GetYaxis()->SetLabelOffset(labelDistance/padWidth);
frameHist->GetYaxis()->SetLabelSize(labelSize/padHeight);
frameHist->GetYaxis()->SetTickLength(tickSize/padWidth);
frameHist->GetYaxis()->SetMaxDigits(3);
if(isRatio) frameHist->GetYaxis()->SetNdivisions(3, 6, 0);
if(isRatio) frameHist->GetYaxis()->SetTitleOffset(0.42);
}
void PUtil::DrawHeader(TPad* pad, const std::string& titleText, const std::string& cmsText, const std::string& lumiText){
pad->cd();
float padWidth = pad->GetWw() * pad->GetWNDC();
float padHeight = pad->GetWh() * pad->GetHNDC();
float textSize = padHeight > padWidth ? 30./padWidth : 30./padHeight;
TLatex* channelLine = new TLatex();
channelLine->SetTextFont(42);
channelLine->SetTextSize(textSize);
channelLine->DrawLatexNDC(0.17, 0.91, titleText.c_str());
TLatex* cmsLine = new TLatex();
cmsLine->SetTextFont(62);
cmsLine->SetTextSize(textSize);
cmsLine->DrawLatexNDC(0.33, 0.91, "CMS");
TLatex* cmsTextLine = new TLatex();
cmsTextLine->SetTextFont(52);
cmsTextLine->SetTextSize(textSize);
cmsTextLine->DrawLatexNDC(0.4, 0.91, cmsText.c_str());
//CMS Work in Progres and Lumi information
TLatex* lumiLine = new TLatex();
lumiLine->SetTextFont(42);
lumiLine->SetTextSize(textSize);
lumiLine->DrawLatexNDC(0.64, 0.91, lumiText.c_str());
}
void PUtil::DrawRatio(TCanvas* canvas, TPad* mainPad, TH1F* num, TH1F* dem, const std::string& yLabel){
//Resize Canvas
canvas->cd();
canvas->SetCanvasSize(canvas->GetWindowWidth(), 1.2*canvas->GetWindowHeight());
mainPad->SetPad(0., 0.2, 1., 1.);
//Set up ratio pad
TPad* ratioPad = new TPad("ratioPad", "ratioPad", 0., 0. , 1., 0.2);
PUtil::SetPad(ratioPad, true);
ratioPad->Draw();
ratioPad->cd();
//Draw ratio histogram
TH1F* ratio = (TH1F*)num->Clone();
PUtil::SetHist(ratioPad, ratio, yLabel, true);
ratio->Divide(dem);
ratio->SetMinimum(0.5);
ratio->SetMaximum(1.5);
ratio->Draw();
//Draw uncertainty band
TH1F* uncertainty = (TH1F*)dem->Clone();
uncertainty->Divide(dem);
uncertainty->SetFillStyle(3354);
uncertainty->SetFillColorAlpha(kBlack, 0.8);
uncertainty->SetMarkerColor(kBlack);
uncertainty->Draw("SAME E2");
}
void PUtil::DrawLegend(TPad* pad, TLegend* legend, const int& nColumns){
pad->cd();
float max = 0;
for(TObject* hist : *(pad->GetListOfPrimitives())){
float maxHist = hist->InheritsFrom(TH1::Class()) ? static_cast<TH1*>(hist)->GetMaximum() : hist->InheritsFrom(TGraph::Class()) ? static_cast<TGraph*>(hist)->GetHistogram()->GetMaximum() : 0;
max = max < maxHist ? maxHist : max;
}
float leftMargin = pad->GetLeftMargin();
float rightMargin = pad->GetRightMargin();
float topMargin = pad->GetTopMargin();
TObject* frame = pad->GetListOfPrimitives()->At(0);
if(frame->InheritsFrom(TH1::Class())){
static_cast<TH1*>(frame)->SetMaximum(pad->GetLogy() ? max*std::pow(10, nColumns) : max*(1 + nColumns*0.1));
}
else if(frame->InheritsFrom(TGraph::Class())){
static_cast<TGraph*>(frame)->GetHistogram()->SetMaximum(pad->GetLogy() ? max*std::pow(10, nColumns) : max*(1 + nColumns*0.1));
}
//Draw Legend and legend pad
TPad* legendPad = new TPad("legendPad", "legendPad", 1.05*leftMargin, 1-1.05*topMargin-nColumns*0.05, 1-1.05*rightMargin, 1-1.05*topMargin);
legendPad->Draw();
legendPad->cd();
float padWidth = legendPad->GetWw() * legendPad->GetWNDC();
float padHeight = legendPad->GetWh() * legendPad->GetHNDC();
float textSize = padHeight > padWidth ? 20./padWidth : 20./padHeight;
for(int i=0; i < legend->GetListOfPrimitives()->GetSize(); i++){
((TLegendEntry*)legend->GetListOfPrimitives()->At(i))->SetTextSize(textSize);
}
legend->SetNColumns(nColumns);
legend->Draw();
}
void PUtil::DrawShapes(TCanvas* canvas, TH1* bkg, TH1* sig){
TH1* s = (TH1*)sig->Clone(); s->Scale(1./s->Integral());
TH1* b = nullptr;
if(bkg != nullptr){
b = (TH1*)bkg->Clone(); b->Scale(1./b->Integral());
}
TLegend* l = new TLegend(0., 0., 1, 1);
PUtil::SetPad(canvas);
PUtil::SetHist(canvas, s, "Normalized events");
canvas->Draw();
//Draw Legend and legend pad
s->SetLineColor(kBlue+1);
s->SetFillStyle(3335);
s->SetFillColor(kBlue);
s->SetLineWidth(4);
l->AddEntry(s, "Sig", "F");
s->Draw("HIST");
if(b != nullptr){
b->SetLineColor(kRed+1);
b->SetFillStyle(3353);
b->SetFillColor(kRed);
b->SetLineWidth(4);
l->AddEntry(b, "Bkg", "F");
b->Draw("HIST SAME");
}
PUtil::DrawLegend(canvas, l, 2);
}
void PUtil::DrawConfusion(const std::vector<long>& trueLabel, const std::vector<long>& predLabel, const std::vector<std::string>& classNames, const std::string& outDir){
int nClasses = classNames.size();
//Set canvas/hist
std::shared_ptr<TCanvas> canvas = std::make_shared<TCanvas>("c", "c", 1000, 1000);
std::shared_ptr<TH2F> confusion = std::make_shared<TH2F>("h", "h", nClasses, 0, nClasses, nClasses, 0, nClasses);
std::shared_ptr<TH2F> confusionNormed = RUtil::CloneSmart<TH2F>(confusion.get());
//Set alphanumeric labels
for(int i = 0; i < classNames.size(); ++i){
confusionNormed->GetXaxis()->SetBinLabel(i + 1, classNames.at(i).c_str());
confusionNormed->GetYaxis()->SetBinLabel(classNames.size() - i, classNames.at(i).c_str());
}
//Style stuff
PUtil::SetStyle();
PUtil::SetPad(canvas.get());
PUtil::SetHist(canvas.get(), confusionNormed.get(), "");
gStyle->SetPaintTextFormat("4.3f");
confusionNormed->SetMarkerSize(2);
confusionNormed->GetXaxis()->SetTitle("Predicted label");
confusionNormed->GetYaxis()->SetTitle("True label");
//Fill confusion matrix
for(int i = 0; i < trueLabel.size(); ++i){
confusion->Fill(predLabel.at(i), trueLabel.at(i));
}
//Normalize
for(int i = 0; i < nClasses; ++i){
float nTotal = 0.;
for(int j = 0; j < nClasses; ++j){
nTotal += confusion->GetBinContent(j + 1, nClasses - i);
}
for(int j = 0; j < nClasses; ++j){
confusionNormed->SetBinContent(j + 1, i + 1, confusion->GetBinContent(j + 1, nClasses - i)/nTotal);
}
}
//Draw and save
confusionNormed->Draw("COL");
confusionNormed->Draw("TEXT SAME");
canvas->SaveAs((outDir + "/confusion.pdf").c_str());
}
std::string PUtil::GetChannelTitle(const std::string& channel){
std::map<std::string, std::string> channelTitle = {
{"EleIncl", "e incl."},
{"MuonIncl", "#mu incl."},
{"Ele4J", "e + 4j"},
{"Muon4J", "#mu + 4j"},
{"Ele2J1FJ", "e + 2j + 1fj"},
{"Muon2J1FJ", "#mu + 2j + 1fj"},
{"Ele2FJ", "e + 2fj"},
{"Muon2FJ", "#mu + 2fj"},
};
return VUtil::At(channelTitle, channel);
}
std::string PUtil::GetLumiTitle(const std::string& lumi){
std::map<std::string, std::string> lumiTitle = {
{"2016", "35.92 fb^{-1} (2016, 13 TeV)"},
{"2017", "41.53 fb^{-1} (2017, 13 TeV)"},
{"2018", "59.74 fb^{-1} (2018, 13 TeV)"},
{"RunII", "137.19 fb^{-1} (RunII, 13 TeV)"},
};
return VUtil::At(lumiTitle, lumi);
}
<file_sep>/Analysis/include/treereader.h
#ifndef TREEREADER_H
#define TREEREADER_H
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <fstream>
#include <memory>
#include <filesystem>
#include <TROOT.h>
#include <TFile.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TTree.h>
#include <TChain.h>
#include <ChargedAnalysis/Utility/include/utils.h>
#include <ChargedAnalysis/Utility/include/frame.h>
#include <ChargedAnalysis/Utility/include/csv.h>
#include <ChargedAnalysis/Utility/include/stringutil.h>
#include <ChargedAnalysis/Utility/include/rootutil.h>
#include <ChargedAnalysis/Utility/include/mathutil.h>
#include <ChargedAnalysis/Analysis/include/treeparser.h>
#include <ChargedAnalysis/Analysis/include/treefunction.h>
class TreeReader {
private:
std::vector<std::string> parameters;
std::vector<std::string> cutStrings;
std::string outDir;
std::string outFile;
std::string channel;
std::vector<std::string> systDirs;
std::vector<std::string> scaleSysts;
std::string scaleFactors;
int era;
std::shared_ptr<TFile> inputFile;
std::shared_ptr<TTree> inputTree;
std::vector<std::shared_ptr<TH1F>> hists1D;
std::vector<std::shared_ptr<TH2F>> hists2D;
std::vector<std::shared_ptr<TH1F>> hists1DSyst;
std::vector<std::shared_ptr<TH2F>> hists2DSyst;
std::shared_ptr<TTree> outTree;
std::shared_ptr<Frame> frame;
std::vector<std::shared_ptr<TFile>> outFiles;
std::vector<TreeFunction> hist1DFunctions;
std::vector<TreeFunction> hist2DFunctions;
std::vector<TreeFunction> cutFunctions;
std::vector<TreeFunction> treeFunctions;
std::vector<TreeFunction> CSVFunctions;
std::vector<std::string> branchNames;
std::vector<std::string> CSVNames;
std::vector<float> treeValues;
int nGen = 1, nTrue = 0;
float lumi = 1., xSec = 1.;
void PrepareLoop();
public:
TreeReader();
TreeReader(const std::vector<std::string> ¶meters, const std::vector<std::string> &cutStrings, const std::string& outDir, const std::string &outFile, const std::string &channel, const std::vector<std::string>& systDirs, const std::vector<std::string>& scaleSysts, const std::string& scaleFactors, const int& era = 2017);
void EventLoop(const std::string& fileName, const std::string& cleanJet);
};
#endif
<file_sep>/Utility/src/rootutil.cc
#include <ChargedAnalysis/Utility/include/rootutil.h>
std::shared_ptr<TFile> RUtil::Open(const std::string& fileName, const std::experimental::source_location& location){
std::shared_ptr<TFile> file(TFile::Open(fileName.c_str(), "READ"));
//Check if file is not null pointer
if(file == nullptr){
throw std::runtime_error(StrUtil::PrettyError(location, "ROOT file not existing: ", fileName));
}
//Check if file is not zombie
if(file->IsZombie()){
throw std::runtime_error(StrUtil::PrettyError(location, "ROOT file is Zombie: ", fileName));
}
return file;
}
bool RUtil::BranchExists(TTree* tree, const std::string& branchName){
if(tree->GetListOfBranches()->FindObject(branchName.c_str())) return true;
return false;
}
<file_sep>/Analysis/src/plotter1D.cc
#include <ChargedAnalysis/Analysis/include/plotter1D.h>
Plotter1D::Plotter1D() : Plotter(){}
Plotter1D::Plotter1D(const std::string& channel, const std::string& era, const std::vector<std::string>& bkgProcesses, const std::vector<std::string>& bkgFiles, const std::vector<std::string>& sigProcesses, const std::vector<std::string>& sigFiles, const std::string& data, const std::string& dataFile) :
Plotter(),
channel(channel),
era(era),
bkgProcesses(bkgProcesses),
bkgFiles(bkgFiles),
sigProcesses(sigProcesses),
sigFiles(sigFiles),
dataProcess(data),
dataFile(dataFile){}
void Plotter1D::ConfigureHists(){
//Read out parameter
std::shared_ptr<TFile> f = RUtil::Open(VUtil::Merge(sigFiles, bkgFiles).at(0));
for(int i = 0; i < f->GetListOfKeys()->GetSize(); ++i){
if(f->Get(f->GetListOfKeys()->At(i)->GetName())->InheritsFrom(TH1F::Class())){
parameters.push_back(f->GetListOfKeys()->At(i)->GetName());
}
}
for(std::size_t i = 0; i < bkgProcesses.size(); ++i){
std::shared_ptr<TFile> file = RUtil::Open(bkgFiles.at(i));
for(std::string& param: parameters){
std::shared_ptr<TH1F> hist = RUtil::GetSmart<TH1F>(file.get(), param);
//Set Style
hist->SetFillStyle(1001);
hist->SetFillColor(colors.at(bkgProcesses.at(i)));
hist->SetLineColor(colors.at(bkgProcesses.at(i)));
hist->SetName(bkgProcesses.at(i).c_str());
hist->SetDirectory(0);
background[param].push_back(hist);
//Total bkg sum
if(bkgSum.count(param)) bkgSum[param]->Add(hist.get());
else{
bkgSum[param] = RUtil::CloneSmart(hist.get());
bkgSum[param]->SetDirectory(0);
}
}
}
for(std::size_t i = 0; i < sigProcesses.size(); ++i){
std::shared_ptr<TFile> file = RUtil::Open(sigFiles.at(i));
for(std::string& param: parameters){
std::shared_ptr<TH1F> hist = RUtil::GetSmart<TH1F>(file.get(), param);
std::vector<std::string> s = StrUtil::Split(sigProcesses.at(i), "_");
hist->SetLineWidth(1 + 3*signal[param].size());
hist->SetLineColor(kBlack);
hist->SetName(StrUtil::Replace("H^{#pm}_{[M]} + h_{[M]}", "[M]", s.at(0).substr(5), s.at(1).substr(1)).c_str());
hist->SetDirectory(0);
signal[param].push_back(hist);
}
}
if(dataProcess != ""){
std::shared_ptr<TFile> file = RUtil::Open(dataFile);
for(std::string& param: parameters){
std::shared_ptr<TH1F> hist = RUtil::GetSmart<TH1F>(file.get(), param);
hist->SetMarkerStyle(20);
hist->SetName("data");
hist->SetDirectory(0);
data[param] = hist;
}
}
}
void Plotter1D::Draw(std::vector<std::string> &outdirs){
//Set overall style
PUtil::SetStyle();
for(std::string& param: parameters){
//All canvases/pads
std::shared_ptr<TCanvas> canvas = std::make_shared<TCanvas>("canvas", "canvas", 1000, 1000);
std::shared_ptr<TPad> mainPad = std::make_shared<TPad>("mainPad", "mainPad", 0., 0. , 1., 1.);
//Draw main pad
PUtil::SetPad(mainPad.get());
mainPad->Draw();
//Sort histograms by integral and fill to HStack
std::shared_ptr<THStack> allBkgs = std::make_shared<THStack>();
std::shared_ptr<TH1F> statUnc;
if(background.count(param)){
std::sort(background[param].begin(), background[param].end(), [&](std::shared_ptr<TH1F> h1, std::shared_ptr<TH1F> h2){return h1->Integral() < h2->Integral();});
for(std::shared_ptr<TH1F>& hist: background[param]){allBkgs->Add(hist.get());}
statUnc = RUtil::CloneSmart(bkgSum[param].get());
statUnc->SetFillStyle(3354);
statUnc->SetFillColorAlpha(kBlack, 0.8);
statUnc->SetMarkerColor(kBlack);
}
//Rerverse sort histograms by integral and fill to Legend
std::shared_ptr<TLegend> legend = std::make_shared<TLegend>(0., 0., 1, 1);
if(data.count(param)) legend->AddEntry(data[param].get(), data[param]->GetName(), "EP");
if(background.count(param)){
std::sort(background[param].begin(), background[param].end(), [&](std::shared_ptr<TH1F> h1, std::shared_ptr<TH1F> h2){return h1->Integral() > h2->Integral();});
for(std::shared_ptr<TH1F>& hist: background[param]){legend->AddEntry(hist.get(), hist->GetName(), "F");}
legend->AddEntry(statUnc.get(), "Stat. unc.", "F");
}
if(signal.count(param)){
for(std::shared_ptr<TH1F>& hist: signal[param]){legend->AddEntry(hist.get(), hist->GetName(), "L");}
}
//Frame hist
std::shared_ptr<TH1F> frame = bkgSum.count(param) ? RUtil::CloneSmart(bkgSum[param].get()) : data.count(param) ? RUtil::CloneSmart(data[param].get()) : RUtil::CloneSmart(signal[param][0].get());
frame->Reset();
PUtil::SetHist(mainPad.get(), frame.get(), "Events");
//Draw ratio
if(bkgSum.count(param) and data.count(param)){
PUtil::DrawRatio(canvas.get(), mainPad.get(), data[param].get(), bkgSum[param].get(), "Data/Pred");
}
for(int isLog=0; isLog < 2; isLog++){
mainPad->cd();
mainPad->Clear();
mainPad->SetLogy(isLog);
int nLegendColumns = std::ceil((legend->GetNRows())/5.);
frame->SetMinimum(isLog ? 1e-1 : 0);
frame->Draw();
//Draw Title
PUtil::DrawHeader(mainPad.get(), PUtil::GetChannelTitle(channel), "Work in progress", PUtil::GetLumiTitle(era));
//Draw data and MC
if(background.count(param)){
allBkgs->Draw("HIST SAME");
statUnc->Draw("SAME E2");
}
if(data.count(param)) data[param]->Draw("E SAME");
if(signal.count(param)){
for(std::shared_ptr<TH1F>& hist: signal[param]){hist->Draw("HIST SAME");}
}
//Redraw axis
gPad->RedrawAxis();
//Draw Legend
PUtil::DrawLegend(mainPad.get(), legend.get(), 5);
//Save everything
std::string extension = isLog ? "_log" : "";
for(std::string outdir: outdirs){
std::system(("mkdir -p " + outdir).c_str());
canvas->SaveAs((outdir + "/" + param + extension + ".pdf").c_str());
canvas->SaveAs((outdir + "/" + param + extension + ".png").c_str());
std::cout << "Saved plot: '" + outdir + "/" + param + extension + ".pdf'" << std::endl;
}
}
//Draw shape plots if signal is there
if(signal.count(param) and param != "cutflow" and param != "EventCount"){
for(std::shared_ptr<TH1F>& hist: signal[param]){
std::shared_ptr<TCanvas> c = std::make_shared<TCanvas>("canvasSig", "canvasSig", 1000, 1000);
PUtil::DrawShapes(c.get(), statUnc.get(), hist.get());
PUtil::DrawHeader(c.get(), PUtil::GetChannelTitle(channel), "Work in progress", PUtil::GetLumiTitle(era));
std::string mass = std::string(hist->GetName()).substr(std::string(hist->GetName()).find("H^{#pm}_{") + 9, 3);
for(std::string outdir: outdirs){
c->SaveAs((outdir + "/" + param + "_" + mass + "_shape.pdf").c_str());
c->SaveAs((outdir + "/" + param + "_" + mass + "_shape.png").c_str());
std::cout << "Saved plot: '" + outdir + "/" + param + "_" + mass + "_shape.pdf'" << std::endl;
}
}
}
}
}
<file_sep>/Analysis/include/histmaker.h
#ifndef HISTMAKER_H
#define HISTMAKER_H
#include <vector>
#include <string>
#include <memory>
#include <experimental/source_location>
#include <TROOT.h>
#include <TFile.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TTree.h>
#include <ChargedAnalysis/Analysis/include/ntuplereader.h>
#include <ChargedAnalysis/Analysis/include/weighter.h>
#include <ChargedAnalysis/Analysis/include/decoder.h>
#include <ChargedAnalysis/Utility/include/csv.h>
#include <ChargedAnalysis/Utility/include/stopwatch.h>
#include <ChargedAnalysis/Utility/include/stringutil.h>
#include <ChargedAnalysis/Utility/include/rootutil.h>
#include <ChargedAnalysis/Utility/include/vectorutil.h>
class HistMaker {
private:
std::vector<std::string> parameters, cutStrings;
std::string outDir, outFile, channel;
std::vector<std::string> systDirs, scaleSysts;
std::string scaleFactors;
int era;
std::shared_ptr<TFile> inputFile;
std::shared_ptr<TTree> inputTree;
std::vector<std::shared_ptr<TH1F>> hists1D, hists1DSyst;
std::vector<std::shared_ptr<TH2F>> hists2D, hists2DSyst;
std::vector<std::shared_ptr<TFile>> outFiles;
std::vector<NTupleReader> hist1DFunctions, cutFunctions;
std::vector<std::pair<NTupleReader, NTupleReader>> hist2DFunctions;
Weighter weight;
void PrepareHists(const std::experimental::source_location& location = std::experimental::source_location::current());
public:
HistMaker();
HistMaker(const std::vector<std::string>& parameters, const std::vector<std::string>& cutStrings, const std::string& outDir, const std::string& outFile, const std::string& channel, const std::vector<std::string>& systDirs, const std::vector<std::string>& scaleSysts, const std::string& scaleFactors, const int& era = 2017);
void Produce(const std::string& fileName);
};
#endif
<file_sep>/Network/include/dnndataset.h
#ifndef DNNDATASET_H
#define DNNDATASET_H
#include <torch/torch.h>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <ChargedAnalysis/Analysis/include/ntuplereader.h>
#include <ChargedAnalysis/Analysis/include/decoder.h>
/**
* @brief Structure with pytorch Tensors of event kinematics for mass-parametrized DNN
*/
struct DNNTensor{
torch::Tensor input; //!< Tensor with kinematic input
torch::Tensor label; //!< Label to check if Signal or not (isSignal = 1, isBackground = 0)
};
/**
* @brief Custom pytorch dataset class for the input for the Higgs tagger
*/
class DNNDataset : public torch::data::datasets::Dataset<DNNDataset, DNNTensor>{
private:
int nEntries = 0;
std::vector<int> trueIndex;
std::vector<NTupleReader> functions;
std::vector<NTupleReader> cuts;
torch::Device device;
int classLabel;
public:
/**
* @brief Constructor for DNNDataset
* @param files Vector with CSV file names
* @param device Pytorch class for usage of CPU/GPU
* @param isSignal Boolean to check if files are signal files
*/
DNNDataset(std::shared_ptr<TTree>& tree, const std::vector<std::string>& parameters, const std::vector<std::string>& cuts, const int& era, const bool& isEven, torch::Device& device, const int& classLabel);
/**
* @brief Function to get number of events in the dataset
*/
torch::optional<size_t> size() const;
/**
* @brief Getter function to get event of the data set
* @param index Index of event in the data set
* @return Returns corresponding DNNDataset
*/
DNNTensor get(size_t index);
int GetClass(){return classLabel;}
/**
* @brief Static function to merge several DNNTensor instances
* @param tensors Vector with DNNTensors
* @return Returns Merged DNNTensor
*/
static DNNTensor Merge(std::vector<DNNTensor>& tensors);
};
#endif
<file_sep>/Analysis/exesrc/plot.cc
#include <string>
#include <vector>
#include <ChargedAnalysis/Utility/include/parser.h>
#include <ChargedAnalysis/Analysis/include/plotter1D.h>
#include <ChargedAnalysis/Analysis/include/plotter2D.h>
int main(int argc, char *argv[]){
//Parser arguments
Parser parser(argc, argv);
std::string era = parser.GetValue<std::string>("era", "2017");
std::string channel = parser.GetValue<std::string>("channel");
std::vector<std::string> bkgProcesses = parser.GetVector<std::string>("bkg-processes", {});
std::vector<std::string> bkgFiles = parser.GetVector<std::string>("bkg-files", {});
std::vector<std::string> sigProcesses = parser.GetVector<std::string>("sig-processes", {});
std::vector<std::string> sigFiles = parser.GetVector<std::string>("sig-files", {});
std::string data = parser.GetValue<std::string>("data", "");
std::string dataFile = parser.GetValue<std::string>("data-file", "");
std::vector<std::string> outDirs = parser.GetVector<std::string>("out-dirs");
//Call and run plotter class
Plotter1D plotter1D(channel, era, bkgProcesses, bkgFiles, sigProcesses, sigFiles, data, dataFile);
plotter1D.ConfigureHists();
plotter1D.Draw(outDirs);
// Plotter2D plotter2D(histDir, channel, processes, era);
// plotter2D.ConfigureHists();
// plotter2D.Draw(outDirs);
}
<file_sep>/Analysis/src/plotter.cc
#include <ChargedAnalysis/Analysis/include/plotter.h>
Plotter::Plotter() : Plotter("") {}
Plotter::Plotter(const std::string& histdir):
histdir(histdir),
colors({
{"DYJ", kRed + -7},
{"DYqq", kRed + -4},
{"TT1L", kYellow -7},
{"TT2L", kYellow +4},
{"TTHad", kYellow +8},
{"TTV", kOrange +2},
{"T", kGreen + 2},
{"WJ", kCyan + 2},
{"QCD", kBlue -3},
{"VV", kViolet -3},
})
{}
<file_sep>/Utility/include/utils.h
#ifndef UTILS_H
#define UTILS_H
#include <vector>
#include <string>
#include <sstream>
#include <iterator>
#include <iostream>
#include <chrono>
#include <algorithm>
#include <map>
#include <TGraph.h>
#include <TH1F.h>
#include <TCanvas.h>
#include <TLatex.h>
#include <torch/torch.h>
#include <ChargedAnalysis/Utility/include/plotutil.h>
namespace Utils{
//Function for splitting string delimited by white space
template <typename T>
std::vector<T> SplitString(const std::string& splitString, const std::string& delimeter);
//Joins vector of strings together
std::string Join(const std::string& delimeter, const std::vector<std::string> strings);
//Replaces symbol in string like python string format
template <typename T>
std::string Format(const std::string& label, const std::string& initial, const T& replace, const bool& ignoreMissing=false);
//Merge two vectors
template <typename T>
std::vector<T> Merge(const std::vector<T>& vec1, const std::vector<T>& vec2);
//Find string in vector
template <typename T>
int Find(const std::string& string, const T& itemToFind);
//Find string in vector
template <typename T>
T* CheckNull(T* ptr, const char* function = __builtin_FUNCTION(), const char* file = __builtin_FILE(), int line = __builtin_LINE()){
if(ptr != nullptr) return ptr;
else{
throw std::runtime_error("Null pointer returned: " + std::string(function) + " method in " + std::string(file) + ":" + std::to_string(line));
}
};
//Find string in vector
template <typename T>
int Find(const std::string& string, const T& itemToFind);
//Check if zero, if yes, return 1.
float CheckZero(const float& input);
//Function for displaying progress
void ProgressBar(const int& progress, const std::string& process);
//Struct for measure executing time
class RunTime{
//Measure execution time
private:
std::chrono::steady_clock::time_point start;
std::chrono::steady_clock::time_point end;
public:
RunTime();
float Time();
};
//Send file to dCache with symlinking
void CopyToCache(const std::string inFile, const std::string outPath);
unsigned int BitCount(unsigned int num);
//Return TGraph with ROC curve
TGraph* GetROC(const std::vector<float>& pred, const std::vector<int>& target, const int& nPoints = 200);
void DrawScore(const torch::Tensor pred, const torch::Tensor truth, const std::string& scorePath);
};
#endif
<file_sep>/Analysis/src/plotter2D.cc
#include <ChargedAnalysis/Analysis/include/plotter2D.h>
Plotter2D::Plotter2D() : Plotter(){}
Plotter2D::Plotter2D(std::string &histdir, std::string &channel, std::vector<std::string> &processes, const std::string& era) :
Plotter(histdir),
channel(channel),
processes(processes),
era(era){}
void Plotter2D::ConfigureHists(){
for(std::string process: processes){
std::string fileName = histdir + "/" + process + "/merged/" + process + ".root";
TFile* file = TFile::Open(fileName.c_str());
std::cout << "Read histograms from file: '" + fileName + "'" << std::endl;
if(parameters.empty()){
for(int i = 0; i < file->GetListOfKeys()->GetSize(); i++){
if(file->Get(file->GetListOfKeys()->At(i)->GetName())->InheritsFrom(TH2F::Class())){
parameters.push_back(file->GetListOfKeys()->At(i)->GetName());
}
}
}
for(std::string& param: parameters){
TH2F* hist = file->Get<TH2F>(param.c_str());
if(Utils::Find<std::string>(process, "HPlus") != -1.){
std::vector<std::string> massStrings = Utils::SplitString<std::string>(process, "_");
hist->SetName(("H^{#pm}_{" + massStrings[0].substr(5,7) + "}+h_{" + massStrings[1].substr(1,3) + "}").c_str());
signal[param].push_back(hist);
}
else{
hist->SetName(process.c_str());
background[param].push_back(hist);
}
}
}
}
void Plotter2D::Draw(std::vector<std::string> &outdirs){
PUtil::SetStyle();
//Save pairs of XY parameters to avoid redundant plots
for(std::string& param: parameters){
TCanvas *canvas = new TCanvas("canvas2D", "canvas2D", 1000, 1000);
TPad* mainPad = new TPad("mainpad", "mainpad", 0., 0. , 1., 1.);
for(std::string outdir: outdirs) std::system(("mkdir -p " + outdir).c_str());
//Draw main pad
PUtil::SetPad(mainPad);
mainPad->SetRightMargin(0.15);
mainPad->Draw();
mainPad->cd();
if(background.count(param)){
TH2F* bkgSum = (TH2F*)background[param][0]->Clone();
bkgSum->Clear();
for(TH2F* hist: background[param]){
bkgSum->Add(hist);
}
PUtil::SetHist(mainPad, bkgSum);
bkgSum->DrawNormalized("CONT4Z");
PUtil::DrawHeader(mainPad, PUtil::GetChannelTitle(channel), "Work in progress");
for(std::string outdir: outdirs){
canvas->SaveAs((outdir + "/" + param + "_bkg.pdf").c_str());
canvas->SaveAs((outdir + "/" + param + "_bkg.png").c_str());
std::cout << "Saved plot: '" + outdir + "/" + param + "_bkg.pdf'" << std::endl;
}
}
if(signal.count(param)){
for(TH2F* hist: signal[param]){
mainPad->Clear();
PUtil::SetHist(mainPad, hist);
std::string mass = std::string(hist->GetName()).substr(std::string(hist->GetName()).find("H^{#pm}_{") + 9, 3);
hist->DrawNormalized("CONT4Z");
PUtil::DrawHeader(mainPad, PUtil::GetChannelTitle(channel), "Work in progress", PUtil::GetLumiTitle(era));
for(std::string outdir: outdirs){
canvas->SaveAs((outdir + "/" + param + "_" + mass + "_sig.pdf").c_str());
canvas->SaveAs((outdir + "/" + param + "_" + mass + "_sig.png").c_str());
std::cout << "Saved plot: '" + outdir + "/" + param + "_" + mass + "_sig.pdf'" << std::endl;
}
}
}
delete mainPad;
delete canvas;
}
}
<file_sep>/Utility/include/csv.h
#ifndef CSV_H
#define CSV_H
#include <fstream>
#include <vector>
#include <string>
#include <map>
#include <filesystem>
#include <experimental/source_location>
#include <ChargedAnalysis/Utility/include/stringutil.h>
#include <ChargedAnalysis/Utility/include/vectorutil.h>
class CSV{
private:
std::string mode;
std::string delim;
std::fstream file;
std::vector<std::size_t> linePos;
std::vector<std::string> colNames;
std::size_t rowIdx;
std::vector<std::string> currentRow;
public:
CSV(const std::string& fileName, const std::string& fileMode, const std::string& delim = ",", const std::experimental::source_location& location = std::experimental::source_location::current());
CSV(const std::string& fileName, const std::string& fileMode, const std::vector<std::string>& colNames, const std::string& delim = ",", const std::experimental::source_location& location = std::experimental::source_location::current());
template<typename T = std::string>
T Get(const std::size_t& row, const std::size_t& column, const std::experimental::source_location& location = std::experimental::source_location::current()){
if(StrUtil::Find(mode, "r").empty()){
throw std::runtime_error(StrUtil::PrettyError(location, "Can not read in '", mode, "' filemode!"));
}
if(row >= linePos.size()){
throw std::runtime_error(StrUtil::PrettyError(location, "Line number '", row, " too large with '", linePos.size() ,"'number of lines in file!"));
}
if(column >= colNames.size()){
throw std::runtime_error(StrUtil::PrettyError(location, "Column number '", column, " too large with '", colNames.size() ,"'number of columns in file!"));
}
T out;
//Check if current row is read out, return column direcly
if(rowIdx == row){
std::stringstream s;
s << currentRow.at(column);
s >> out;
return out;
}
//Seek file position and read out line
file.clear();
file.seekg(linePos.at(row));
std::string line;
std::getline(file, line);
//Get vector with splitted row and return column idx of vector
rowIdx = row;
currentRow = StrUtil::Split(line, delim);
std::stringstream s;
s << currentRow.at(column);
s >> out;
return out;
}
template<typename T = std::string>
T Get(const std::size_t& row, const std::string& columnName, const std::experimental::source_location& location = std::experimental::source_location::current()){
std::size_t column;
//Try to find column number
try{
column = VUtil::Find(colNames, columnName).at(0);
}
catch(std::out_of_range){
throw std::runtime_error(StrUtil::PrettyError(location, "Unknown column name '", columnName, "'!"));
}
//Call get function with row/column number
return Get<T>(row, column, location);
}
template<typename T = std::string>
std::vector<T> GetColumn(const std::size_t& column, const std::experimental::source_location& location = std::experimental::source_location::current()){
if(StrUtil::Find(mode, "r").empty()){
throw std::runtime_error(StrUtil::PrettyError(location, "Can not read in '", mode, "' filemode!"));
}
std::vector<T> out;
//Read out all rows and extract column info
for(int i = 0; i < linePos.size(); ++i){
out.push_back(Get<T>(i, column, location));
}
return out;
}
template<typename T = std::string>
std::vector<T> GetColumn(const std::string& columnName, const std::experimental::source_location& location = std::experimental::source_location::current()){
std::size_t column;
//Try to find column number
try{
column = VUtil::Find(colNames, columnName).at(0);
}
catch(std::out_of_range){
throw std::runtime_error(StrUtil::PrettyError(location, "Unknown column name '", columnName, "'!"));
}
return GetColumn<T>(column, location);
}
template <typename... T>
void WriteRow(T&&... data){
//Jump to end of file
file.clear();
file.seekp(0, std::ios::end);
//Append data
std::stringstream stream;
((stream << std::forward<T>(data) << delim), ...);
std::string result = stream.str();
result.replace(result.size() - 1, 1, "\n");
file << result;
//Update file information
linePos.push_back(linePos.back() + result.size());
}
};
#endif
<file_sep>/Analysis/src/decoder.cc
#include <ChargedAnalysis/Analysis/include/decoder.h>
Decoder::Decoder(){}
bool Decoder::hasYInfo(const std::string& parameter){
return !StrUtil::Find(parameter, "ax=y").empty();
}
void Decoder::GetFunction(const std::string& parameter, NTupleReader& reader, const std::experimental::source_location& location){
if(StrUtil::Find(parameter, "f:").empty()) throw std::runtime_error(StrUtil::PrettyError(location, "No function key 'f:' in '", parameter, "'!"));
std::vector<std::string> lines = StrUtil::Split(parameter, "/");
lines.erase(std::remove_if(lines.begin(), lines.end(), [&](std::string l){return StrUtil::Find(l, "f:").empty();}), lines.end());
for(const std::string& line : lines){
std::string funcName; std::vector<std::string> values;
std::string funcLine = line.substr(line.find("f:")+2);
for(std::string& funcParam: StrUtil::Split(funcLine, ",")){
std::vector<std::string> fInfo = StrUtil::Split(funcParam, "=");
if(fInfo[0] == "n") funcName = fInfo[1];
else if(fInfo[0] == "v") values.push_back(fInfo[1]);
else throw std::runtime_error(StrUtil::PrettyError(location, "Invalid key '", fInfo[0], "' in parameter '", parameter, "'"));
}
reader.AddFunction(funcName, values);
}
}
void Decoder::GetParticle(const std::string& parameter, NTupleReader& reader, Weighter*
weight, const std::experimental::source_location& location){
std::vector<std::string> lines = StrUtil::Split(parameter, "/");
lines.erase(std::remove_if(lines.begin(), lines.end(), [&](std::string l){return StrUtil::Find(l, "p:").empty();}), lines.end());
for(const std::string line : lines){
std::string partLine = line.substr(line.find("p:")+2);
std::string part = ""; std::string wp = ""; int idx = 0;
for(const std::string& partParam: StrUtil::Split(partLine, ",")){
std::vector<std::string> pInfo = StrUtil::Split(partParam, "=");
if(pInfo[0] == "n") part = pInfo[1];
else if (pInfo[0] == "wp") wp = pInfo[1];
else if (pInfo[0] == "i") idx = std::atoi(pInfo[1].c_str());
else throw std::runtime_error(StrUtil::PrettyError(location, "Invalid key '", pInfo[0], "' in parameter '", parameter, "'"));
}
reader.AddParticle(part, idx, wp);
if(weight != nullptr) weight->AddParticle(part, wp);
}
}
void Decoder::GetBinning(const std::string& parameter, TH1* hist, const std::experimental::source_location& location){
if(StrUtil::Find(parameter, "h:").empty()) throw std::runtime_error(StrUtil::PrettyError(location, "No function key 'h:' in '", parameter, "'!"));
std::string histLine = parameter.substr(parameter.find("h:")+2, parameter.substr(parameter.find("h:")).find("/")-2);
int xBins = 30, yBins = -1.;
float xlow = 0, xhigh = 1, ylow = 0, yhigh = 1;
for(std::string& histParam: StrUtil::Split(histLine, ",")){
std::vector<std::string> hInfo = StrUtil::Split(histParam, "=");
if(hInfo[0] == "nxb") xBins = std::stof(hInfo[1]);
else if(hInfo[0] == "xl") xlow = std::stof(hInfo[1]);
else if(hInfo[0] == "xh") xhigh = std::stof(hInfo[1]);
else if(hInfo[0] == "nyb") yBins = std::stof(hInfo[1]);
else if(hInfo[0] == "yl") ylow = std::stof(hInfo[1]);
else if(hInfo[0] == "yh") yhigh = std::stof(hInfo[1]);
else throw std::runtime_error(StrUtil::PrettyError(location, "Invalid key '", hInfo[0], "' in parameter '", parameter, "'"));
}
if(yBins == -1.) hist->SetBins(xBins, xlow, xhigh);
else hist->SetBins(xBins, xlow, xhigh, yBins, ylow, yhigh);
}
void Decoder::GetCut(const std::string& parameter, NTupleReader& reader, const std::experimental::source_location& location){
if(StrUtil::Find(parameter, "c:").empty()) throw std::runtime_error(StrUtil::PrettyError(location, "No function key 'c:' in '", parameter, "'!"));
std::string comp; float compValue = -999.;
std::map<std::string, std::string> compMap = {{"equal", "=="}, {"bigger", ">="}, {"smaller", "<="}};
std::string cutLine = parameter.substr(parameter.find("c:")+2, parameter.substr(parameter.find("c:")).find("/")-2);
for(std::string& cutParam: StrUtil::Split(cutLine, ",")){
std::vector<std::string> cInfo = StrUtil::Split(cutParam, "=");
if(cInfo[0] == "n") comp = cInfo[1];
else if(cInfo[0] == "v") compValue = std::stof(cInfo[1]);
else throw std::runtime_error(StrUtil::PrettyError(location, "Invalid key '", cInfo[0], "' in parameter '", parameter, "'"));
}
reader.AddCut(compValue, VUtil::At(compMap,comp));
}
<file_sep>/Analysis/include/plotter2D.h
#ifndef PLOTTER2D_H
#define PLOTTER2D_H
#include <TCanvas.h>
#include <TFile.h>
#include <TH2F.h>
#include <ChargedAnalysis/Analysis/include/plotter.h>
#include <ChargedAnalysis/Utility/include/utils.h>
class Plotter2D : public Plotter{
private:
std::map<std::string, std::vector<TH2F*>> background;
std::map<std::string, std::vector<TH2F*>> signal;
std::map<std::string, TH2F*> data;
std::string channel;
std::vector<std::string> processes;
std::vector<std::string> parameters;
std::string era;
public:
Plotter2D();
Plotter2D(std::string &histdir, std::string &channel, std::vector<std::string> &processes, const std::string& era);
void ConfigureHists();
void Draw(std::vector<std::string> &outdirs);
};
#endif
<file_sep>/Analysis/include/plotterPostfit.h
#ifndef PLOTTERPOSTFIT_H
#define PLOTTERPOSTFIT_H
#include <ChargedAnalysis/Analysis/include/plotter.h>
#include <functional>
#include <vector>
#include <map>
#include <TROOT.h>
#include <TFile.h>
#include <THStack.h>
#include <TH1F.h>
#include <TCanvas.h>
#include <TLegend.h>
#include <TPad.h>
#include <TLegend.h>
class PlotterPostfit : public Plotter{
private:
std::string limitDir;
int mass;
std::vector<std::string> channels;
int max = 0;
std::map<std::string, TH1F*> errorBand;
std::map<std::string, std::vector<TH1F*>> backgrounds;
std::map<std::string, TH1F*> signals;
std::map<std::string, std::string> chanToDir;
public:
PlotterPostfit();
PlotterPostfit(std::string &limitDir, int &mass, std::vector<std::string> &channels);
void ConfigureHists();
void Draw(std::vector<std::string> &outdirs);
};
#endif
<file_sep>/Analysis/include/weighter.h
#ifndef WEIGHTER_H
#define WEIGHTER_H
#include <vector>
#include <string>
#include <memory>
#include <functional>
#include <TFile.h>
#include <TTree.h>
#include <TH1F.h>
#include <TLeaf.h>
#include <TH2F.h>
#include <ChargedAnalysis/Analysis/include/ntuplereader.h>
#include <ChargedAnalysis/Utility/include/rootutil.h>
#include <ChargedAnalysis/Utility/include/stringutil.h>
namespace pt = boost::property_tree;
class Weighter{
private:
std::shared_ptr<TFile> inputFile;
std::shared_ptr<TTree> inputTree;
int era;
bool isData;
double baseWeight = 1., partWeight = 1.;
std::shared_ptr<TH1F> pileUpWeight, pileUpWeightUp, pileUpWeightDown;
std::vector<NTupleReader> sf, sfUp, sfDown;
std::function<float(const int&)> bWeight, bWeightUp, bWeightDown;
static double GetBJetWeight(const int& entry, TH2F* effB, TH2F* effC, TH2F* effLight, NTupleReader bPt, TLeaf* pt, TLeaf* eta, TLeaf* sf, TLeaf* flavour);
public:
Weighter();
Weighter(const std::shared_ptr<TFile>& inputFile, const std::shared_ptr<TTree>& inputTree, const int& era = 2017);
void AddParticle(const std::string& partName, const std::string& wp, const std::experimental::source_location& location = std::experimental::source_location::current());
double GetBaseWeight(const std::size_t& entry);
double GetPartWeight(const std::size_t& entry);
double GetTotalWeight(const std::size_t& entry);
};
#endif
<file_sep>/Network/src/dnndataset.cc
/**
* @file dnndataset.cc
* @brief Source file for DNNDataset class, see dnndataset.h
*/
#include <ChargedAnalysis/Network/include/dnndataset.h>
DNNDataset::DNNDataset(std::shared_ptr<TTree>& tree, const std::vector<std::string>& parameters, const std::vector<std::string>& cutNames, const int& era, const bool& isEven, torch::Device& device, const int& classLabel) :
device(device),
classLabel(classLabel){
Decoder parser;
for(const std::string& parameter: parameters){
//Functor structure and arguments
NTupleReader function(tree, era);
//Read in everything, orders matter
parser.GetParticle(parameter, function);
parser.GetFunction(parameter, function);
function.Compile();
functions.push_back(function);
}
for(const std::string& cutName: cutNames){
//Functor structure and arguments
NTupleReader cut(tree, era);
//Read in everything, orders matter
parser.GetParticle(cutName, cut);
parser.GetFunction(cutName, cut);
parser.GetCut(cutName, cut);
cut.Compile();
cuts.push_back(cut);
}
TLeaf* evNr = RUtil::Get<TLeaf>(tree.get(), "Misc_eventNumber");
for(int i = 0; i < tree->GetEntries(); ++i){
NTupleReader::SetEntry(i);
if(int(1/RUtil::GetEntry<float>(evNr, i)*10e10) % 2 == isEven) continue;
bool passed=true;
for(NTupleReader& cut : cuts){
passed = passed && cut.GetPassed();
if(!passed) break;
}
if(passed){
trueIndex.push_back(i);
nEntries++;
}
}
}
torch::optional<size_t> DNNDataset::size() const {
return nEntries;
}
DNNTensor DNNDataset::get(size_t index){
int entry = trueIndex[index];
NTupleReader::SetEntry(entry);
std::vector<float> paramValues;
for(NTupleReader& func : functions){
paramValues.push_back(func.Get());
}
return {torch::from_blob(paramValues.data(), {1, paramValues.size()}).clone().to(device), torch::tensor({classLabel}).to(device)};
}
DNNTensor DNNDataset::Merge(std::vector<DNNTensor>& tensors){
std::vector<torch::Tensor> input, label;
for(DNNTensor& tensor: tensors){
input.push_back(tensor.input);
label.push_back(tensor.label);
}
return {torch::cat(input, 0), torch::cat(label, 0)};
}
<file_sep>/Analysis/exesrc/plotpostfit.cc
#include <string>
#include <vector>
#include <ChargedAnalysis/Analysis/include/plotterPostfit.h>
#include <ChargedAnalysis/Utility/include/parser.h>
int main(int argc, char* argv[]){
//Parser arguments
Parser parser(argc, argv);
int mass = parser.GetValue<int>("mass");
std::string limitDir = parser.GetValue<std::string>("limit-dir");
std::vector<std::string> channels = parser.GetVector<std::string>("channels");
std::vector<std::string> outDirs = parser.GetVector<std::string>("out-dirs");
//Call and run Plotter1D class
PlotterPostfit plotter(limitDir, mass, channels);
plotter.ConfigureHists();
plotter.Draw(outDirs);
}
|
d5295a3f74444506c8fcaaa58279bdcc1ac31707
|
[
"Python",
"C++"
] | 57
|
Python
|
wywdiablo/ChargedAnalysis
|
f447bf9fcd4089ecf30f6adb712f6f5a2d831bec
|
eb5f8e2b9bcdb66db23a2578a5dd3fb6eb57d88e
|
refs/heads/master
|
<file_sep> ymaps.ready(init);
function init(){
var myMap = new ymaps.Map("map", {
center: [55.76, 37.64],
controls: ['fullscreenControl'],
zoom: 15,
});
var zoomControl = new ymaps.control.ZoomControl(
{ options: {
layout: 'round#zoomLayout'
}
});
myMap.controls.add(zoomControl);
var geolocationControl = new ymaps.control.GeolocationControl({
options: {
layout: 'round#buttonLayout'
}
});
myMap.controls.add(geolocationControl);
var listItems = [
new ymaps.control.ListBoxItem({
data: {
content: 'Wi-Fi в парках',
name: '(id >= 10000 && id <20000)'
}
}),
new ymaps.control.ListBoxItem({
data: {
content: 'Городской Wi-Fi',
name: '(id >= 20000 && id <30000)'
}
}),
new ymaps.control.ListBoxItem({
data: {
content: 'Wi-Fi в библиотеках',
name: '(id >= 30000 && id <40000)'
}
}),
new ymaps.control.ListBoxItem({
data: {
content: 'Wi-Fi в кинотеатрах',
name: '(id >= 40000 && id <50000)'
}
}),
new ymaps.control.ListBoxItem({
data: {
content: 'Wi-Fi в культурных центрах',
name: '(id >= 50000 && id <60000)'
}
}),
],
myListBox = new ymaps.control.ListBox({
data: {
content: 'Выбрать wifi'
},
items: listItems
});
myListBox.events.add(['select','deselect'], function (e) {
var item = e.get('target');
if (item != myListBox) {
var filterstr = 'id == 0||';
for (var i = 0; i < 5; i++) {
if(myListBox.get(i).isSelected()){
filterstr = filterstr + myListBox.get(i).data.get('name') + '||';
};
}
filterstr = filterstr.substring(0, filterstr.length - 2);
WIFi.setFilter(filterstr);
myMap.geoObjects.add(WIFi);
console.log(filterstr);
}
});
myMap.controls.add(myListBox, {float:'right'});
var WIFiJson;
var WIFi = new ymaps.ObjectManager();
$.ajaxSetup({async: false});
$.getJSON('https://apidata.mos.ru/v1/datasets/861/features?api_key=e9e6d9ed289cb211befa06fe4ac5e13f', function (json) {
$.each(json["features"], function(key, val){
val["geometry"]["type"]="Circle";
val["geometry"]["coordinates"]=[val["geometry"]["coordinates"][1], val["geometry"]["coordinates"][0]];
val["geometry"]["radius"]=val["properties"]["Attributes"]["CoverageArea"];
val["id"]=key+10000;
val["options"]=[];
val["options"]["fillColor"] = "ff16fd99";
val["options"]["strokeColor"] = "ff16fd";
val["properties"]["balloonContent"]= "<b>"+ val["properties"]["Attributes"]["Name"] + " - " + val["properties"]["Attributes"]["WiFiName"] + "<br>Адрес:</b> " + val["properties"]["Attributes"]["ParkName"] ;
});
WIFiJson = json;
});
$.getJSON('https://apidata.mos.ru/v1/datasets/2756/features?api_key=e9e6d9ed289cb211befa06fe4ac5e13f', function (json) {
$.each(json["features"], function(key, val){
val["geometry"]["type"]="Circle";
val["geometry"]["coordinates"]=[val["geometry"]["coordinates"][1], val["geometry"]["coordinates"][0]];
val["geometry"]["radius"]=val["properties"]["Attributes"]["CoverageArea"];
val["id"]=key+20000;
val["options"]=[];
val["options"]["fillColor"] = "964b0099";
val["options"]["strokeColor"] = "964b00";
val["properties"]["balloonContent"]="<b>"+ val["properties"]["Attributes"]["Name"] + " - " + val["properties"]["Attributes"]["WiFiName"] + "<br>Адрес: </b>" + val["properties"]["Attributes"]["Location"] ;
WIFiJson.features.push(val);
});
});
$.getJSON('https://apidata.mos.ru/v1/datasets/60788/features?api_key=e9e6d9ed289cb211befa06fe4ac5e13f', function (json) {
$.each(json["features"], function(key, val){
val["geometry"]["type"]="Circle";
val["geometry"]["coordinates"]=[val["geometry"]["coordinates"][1], val["geometry"]["coordinates"][0]];
val["geometry"]["radius"]=val["properties"]["Attributes"]["CoverageArea"];
val["id"]=key+30000;
val["options"]=[];
val["options"]["fillColor"] = "f009";
val["options"]["strokeColor"] = "f00";
val["properties"]["balloonContent"]="<b>"+val["properties"]["Attributes"]["WiFiName"] + "<br>Адрес: </b>" + val["properties"]["Attributes"]["Address"] + "<br>" + val["properties"]["Attributes"]["LibraryName"] + "<br><b>Кол-во точек доступа: </b>" + val["properties"]["Attributes"]["NumberOfAccessPoints"];
WIFiJson.features.push(val);
});
});
$.getJSON('https://apidata.mos.ru/v1/datasets/60789/features?api_key=e9e6d9ed289cb211befa06fe4ac5e13f', function (json) {
$.each(json["features"], function(key, val){
val["geometry"]["type"]="Circle";
val["geometry"]["coordinates"]=[val["geometry"]["coordinates"][1], val["geometry"]["coordinates"][0]];
val["geometry"]["radius"]=val["properties"]["Attributes"]["CoverageArea"];
val["id"]=key+40000;
val["options"]=[];
val["options"]["fillColor"] = "18ff0099";
val["options"]["strokeColor"] = "18ff00";
val["properties"]["balloonContent"]="<b>"+val["properties"]["Attributes"]["WiFiName"] + "<br>Адрес: </b>" + val["properties"]["Attributes"]["Address"] + "<br>" + val["properties"]["Attributes"]["CinemaName"] + "<br><b>Кол-во точек доступа: </b>" + val["properties"]["Attributes"]["NumberOfAccessPoints"];
WIFiJson.features.push(val);
});
});
$.getJSON('https://apidata.mos.ru/v1/datasets/60790/features?api_key=e9e6d9ed289cb211befa06fe4ac5e13f', function (json) {
$.each(json["features"], function(key, val){
val["geometry"]["type"]="Circle";
val["geometry"]["coordinates"]=[val["geometry"]["coordinates"][1], val["geometry"]["coordinates"][0]];
val["geometry"]["radius"]=val["properties"]["Attributes"]["CoverageArea"];
val["id"]=key+50000;
val["properties"]["balloonContent"]="<b>"+val["properties"]["Attributes"]["WiFiName"] + "<br>Адрес: </b>" + val["properties"]["Attributes"]["Address"] + "<br>" + val["properties"]["Attributes"]["CulturalCenterName"] + "<br><b>Кол-во точек доступа: </b>" + val["properties"]["Attributes"]["NumberOfAccessPoints"];
WIFiJson.features.push(val);
});
console.log(WIFiJson);
});
$.ajaxSetup({async: true});
WIFi.add(WIFiJson);
WIFi.setFilter('id == 0');
myMap.geoObjects.add(WIFi);
}
|
d1f74a7aa04080a33a672d74d640f8de1f8e2f2f
|
[
"JavaScript"
] | 1
|
JavaScript
|
MindofGhost/moscowifi
|
a2189eb113a8b14808643b8d90e9bb66df61888a
|
72e3ae2c619070a66a3c8fc292ad529af9876ae8
|
refs/heads/master
|
<repo_name>xiaoqi1310/demo<file_sep>/demo/src/main/java/com/kylin/josn/JOSNTest.java
package com.kylin.josn;
public class JOSNTest {
public static void main(String[] args) {
}
}
|
291b4abaffc9bdb2b5bc71b4cbda57ff82415345
|
[
"Java"
] | 1
|
Java
|
xiaoqi1310/demo
|
f502f69c52110f56652f1ff84b196071cc77cb91
|
da12ca4d6848c4c436a7dbd0624e33d89b47fe12
|
refs/heads/master
|
<file_sep># H2-DiningPhilsophers
Teamwork with Tobias(TGPGamez)
<file_sep>using System.Threading;
namespace H2_DiningPhilsophers.Lib
{
public class DiningManager
{
public DiningManager()
{
Forks = new Fork[]
{
new Fork("F1"),
new Fork("F2"),
new Fork("F3"),
new Fork("F4"),
new Fork("F5"),
};
Philosophers = new Philosopher[]
{
new Philosopher("P1", Forks[0], Forks[1]),
new Philosopher("P2", Forks[1], Forks[2]),
new Philosopher("P3", Forks[1], Forks[2]),
new Philosopher("P4", Forks[3], Forks[4]),
new Philosopher("P5", Forks[4], Forks[0]),
};
}
public Fork[] Forks { get; private set; }
public Philosopher[] Philosophers { get; private set; }
public void StartDining()
{
for (int i = 0; i < Philosophers.Length; i++)
{
Thread thread = new Thread(Philosophers[i].TakeFork);
thread.Start();
}
}
}
}
<file_sep>namespace H2_DiningPhilsophers.Lib
{
public enum PhilosopherState
{
Eating,
Thinking,
Waiting,
}
}
<file_sep>using System;
using H2_DiningPhilsophers.Lib;
class Program
{
static void Main(string[] args)
{
DiningManager manager = new DiningManager();
foreach (Philosopher philosopher in manager.Philosophers)
{
philosopher.PhilosopherStateChanged += OnPhilosopherStateChanged;
philosopher.PhilosopherDoneEating += OnPhilosopherDoneEating;
}
manager.StartDining();
}
private static void OnPhilosopherDoneEating(Philosopher philosopher)
{
Console.WriteLine(philosopher.Name + " is now done eating");
}
static void OnPhilosopherStateChanged(Philosopher philosopher)
{
switch (philosopher.State)
{
case PhilosopherState.Eating:
Console.WriteLine(philosopher.Name + " is now eating with " + philosopher.LeftFork.Name + " and " + philosopher.RightFork.Name);
break;
case PhilosopherState.Thinking:
Console.WriteLine(philosopher.Name + " is thinking...");
break;
case PhilosopherState.Waiting:
Console.WriteLine(philosopher.Name + " is waiting...");
break;
default:
break;
}
}
}
<file_sep>using System;
using System.Threading;
namespace H2_DiningPhilsophers.Lib
{
public delegate void PhilosopherEvent(Philosopher philosopher);
public class Philosopher
{
public Philosopher(string name, Fork leftFork, Fork rightFork)
{
Name = name;
LeftFork = leftFork;
RightFork = rightFork;
_state = PhilosopherState.Waiting;
}
private PhilosopherState _state;
private static Random rng = new Random();
public Fork LeftFork { get; private set; }
public Fork RightFork { get; private set; }
public string Name { get; private set; }
public PhilosopherState State
{
get => _state;
private set
{
PhilosopherStateChanged.Invoke(this);
_state = value;
}
}
public PhilosopherEvent PhilosopherStateChanged { get; set; }
public PhilosopherEvent PhilosopherDoneEating { get; set; }
public void TakeFork()
{
while (true)
{
if (Monitor.TryEnter(RightFork))
{
if (Monitor.TryEnter(LeftFork))
{
BeginEating();
Monitor.Pulse(RightFork);
Monitor.Pulse(LeftFork);
Monitor.Exit(RightFork);
Monitor.Exit(LeftFork);
State = PhilosopherState.Thinking;
}
else
{
Monitor.Exit(RightFork);
}
}
if (State == PhilosopherState.Thinking)
{
Thread.Sleep(rng.Next(1000, 4000));
State = PhilosopherState.Waiting;
}
}
}
private void BeginEating()
{
State = PhilosopherState.Eating;
Thread.Sleep(rng.Next(1500, 3000));
PhilosopherDoneEating.Invoke(this);
}
}
}
|
233de83645625e9326eb11e0b641fa96e352f8f3
|
[
"Markdown",
"C#"
] | 5
|
Markdown
|
jonash871j/H2-DiningPhilsophers
|
3cc07ee5181d6dc0ca83b555c33e08c8b1d0013a
|
23e7ae9120ae340efddbd00b3380de7a4de6bbf0
|
refs/heads/master
|
<repo_name>hex-ci/babel-fastcgi<file_sep>/README.md
# babel-fastcgi
Compiling JavaScript with Babel on the fastcgi server.
<file_sep>/server.js
"use strict";
var fastcgi = require('fastcgi-server');
var fs = require('fs');
var babel = require("babel-core");
fastcgi.createServer(function(req,res) {
// console.log(req.params)
var filename = req.params.DOCUMENT_ROOT + req.params.SCRIPT_NAME;
var status = 200;
if (fs.existsSync(filename)) {
var code = fs.readFileSync(filename);
var content = '';
try {
var result = babel.transform(code, {
"presets": ["es2015"]
});
content = result.code;
status = 200;
}
catch (e) {
content = 'console.log(' + JSON.stringify(e) + ');';
status = 200;
}
// console.log(result);
res.writeHead(status, {'Content-Type': 'application/javascript'});
res.end(content);
}
else {
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('Meeh :-(');
}
}).listen("/tmp/fastcgi.sock");
|
39fc0ae5de94543a8c33efb24231b131d253727e
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
hex-ci/babel-fastcgi
|
88b2e9d1f64a5e1f548ca60d3e785f2702bd88a1
|
c7c09b4af9cb32e5212dd6ee306d8c463b3aa839
|
refs/heads/master
|
<repo_name>nklnkv/project-lvl1-s316<file_sep>/src/games/even.js
import randomNumber from '../helpers';
const EVEN_FACTOR = 2;
const description = 'Answer "yes" if number even otherwise answer "no".\n';
const makeTask = () => {
const questionedNumber = randomNumber();
return {
question: questionedNumber,
answer: questionedNumber,
};
};
const check = (userAnswer, number) => {
const isEven = number % EVEN_FACTOR === 0;
return {
isWin: ((isEven && userAnswer === 'yes') || (!isEven && userAnswer === 'no')),
rightAnswer: isEven ? 'yes' : 'no',
};
};
export {
description,
makeTask,
check,
};
<file_sep>/src/games/calc.js
import randomNumber from '../helpers';
const OPERATORS = ['+', '-', '*'];
const FUNCTIONS = {
'+': (a, b) => a + b,
'-': (a, b) => a - b,
'*': (a, b) => a * b,
};
const description = 'What is the result of the expressionr?\n';
const makeTask = (iteration) => {
const operator = OPERATORS[iteration % 3];
const firstNumber = randomNumber();
const secondNumber = randomNumber();
return {
question: `${firstNumber} ${operator} ${secondNumber}`,
answer: FUNCTIONS[operator](firstNumber, secondNumber),
};
};
const check = (userAnswer, number) => {
const result = {
isWin: parseInt(userAnswer, 10) === number,
rightAnswer: number,
};
return result;
};
export {
description,
makeTask,
check,
};
<file_sep>/README.md
# project-lvl1-s316
[](https://codeclimate.com/github/nklnkv/project-lvl1-s316/maintainability)
[](https://codeclimate.com/github/nklnkv/project-lvl1-s316/test_coverage)
[](https://travis-ci.org/nklnkv/project-lvl1-s316)
<file_sep>/src/helpers.js
const MAX_NUMBER = 100;
const randomNumber = () => Math.floor(Math.random() * MAX_NUMBER);
export default randomNumber;
|
99b42cd1d79fcada96c3cd224b5b76574c06c2ed
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
nklnkv/project-lvl1-s316
|
9b8749ccde866028873f5e53b5907d848e232cd4
|
a1714da6cfc15775392752009fea189771692809
|
refs/heads/master
|
<file_sep># zsh_custom
ZSH aliases customizations
<file_sep>alias gc-='gcloud'
alias gc-c='gcloud config'
alias gc-cl='gcloud config list'
alias gc-cc='gcloud config configurations'
alias gc-ccl='gcloud config configurations list'
alias gc-cca='gcloud config configurations activate'
alias gc-c='gcloud compute'
alias gc-c-l='gcloud compute list'
alias gc-c-c='gcloud compute create'
alias gc-c-n='gcloud compute networks'
alias gc-c-nl='gcloud compute networks list'
alias gc-c-nc='gcloud compute networks create'
alias gc-c-ns='gcloud compute networks subnets'
alias gc-c-nsl='gcloud compute networks subnets list'
alias gc-c-nsc='gcloud compute networks subnets create'
alias gc-dc='gcloud container clusters'
alias gc-dcl='gcloud container clusters list'
alias gc-d='gcloud container' #d for containers as d in docker
|
1b2bdb525564d62d66d6728921775eab5c8ec891
|
[
"Markdown",
"Shell"
] | 2
|
Markdown
|
hrudayanath/zsh_custom
|
1e3cea02df7a0ab0ff4109958f7d497cfe88ef8c
|
b28384dcb3eafa220fb01cdc10d70d26e2aa641c
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
__author__ = 'alexeyymanikin'
import re
import dns.resolver
import MySQLdb
import pprint
from helpers.helpers import get_mysql_connection
from config.main import MAX_AS_NUMBER
class AsInet(object):
def __init__(self):
"""
:return:
"""
self.resolver = dns.resolver.Resolver()
self.resolver.timeout = 1
self.resolver.lifetime = 1
self.re_plus = re.compile('\s+')
self.re_all = re.compile('\s*')
self.connection = get_mysql_connection()
def __del__(self):
"""
Подчисщаем за собой все
:return:
"""
self.connection.close()
def parsing_as(self, show_log=False, max_as=MAX_AS_NUMBER):
"""
парсим названия AS
:type show_log: bool
:type max_as: int
:return:
"""
for i in range(1, max_as):
self.update_as(i, show_log=show_log)
def _get_asn_description(self, number):
"""
:type number: int
:return:
"""
answers = self.resolver.query('AS' + str(number) + '.asn.cymru.com', 'TXT')
asn_name = re.sub(r'"', '', answers[0].to_text())
list_as_info = asn_name.split('|')
try:
description = re.sub(self.re_plus, ' ', list_as_info[4])
except IndexError:
description = ''
try:
date_register = re.sub(self.re_all, '', list_as_info[3])
except IndexError:
date_register = ''
try:
country = re.sub(self.re_plus, '', list_as_info[1])
except IndexError:
country = ''
return {'AS': re.sub(self.re_plus, ' ', list_as_info[0]),
'COUNTRY': country,
'ORGANIZATION': re.sub(self.re_plus, ' ', list_as_info[2]),
'DATE_REGISTER': date_register,
'DESCRIPTION': description}
def update_as(self, number, show_log=False):
"""
Обновляем информацию об AS в базе данных
:type number: int
:return:
"""
try:
as_info = self._get_asn_description(number)
except:
as_info = {'AS': number,
'COUNTRY': '',
'ORGANIZATION': '',
'DATE_REGISTER': '',
'DESCRIPTION': ''}
if show_log:
print "AS Number %s" % number
pprint.pprint(as_info)
cursor = self.connection.cursor(MySQLdb.cursors.DictCursor)
try:
cursor.execute("SELECT COUNT(*) as count FROM as_list WHERE id = %s" % str(number))
except:
self.connection = get_mysql_connection()
cursor = self.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT COUNT(*) as count FROM as_list WHERE id = %s" % str(number))
count = cursor.fetchone()
if as_info['DATE_REGISTER'] == '':
as_info['DATE_REGISTER'] = '2001-01-01'
if as_info['COUNTRY'] == '':
as_info['COUNTRY'] = 'undef'
if as_info['ORGANIZATION'] == '':
as_info['ORGANIZATION'] = 'undef'
if count['count'] == 0:
cursor.execute(
"""INSERT INTO as_list(id,
descriptions,
country,
date_register,
organization_register)
VALUE(%s, %s, %s, %s, %s)""", (str(number),
as_info['DESCRIPTION'],
as_info['COUNTRY'],
as_info['DATE_REGISTER'],
as_info['ORGANIZATION']))
else:
cursor.execute(
"""UPDATE as_list SET
descriptions = %s,
country = %s,
date_register = %s,
organization_register = %s
WHERE id = %s""", (as_info['DESCRIPTION'],
as_info['COUNTRY'],
as_info['DATE_REGISTER'],
as_info['ORGANIZATION'],
str(number)))
self.connection.commit()
return True
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
__author__ = '<NAME>'
from helpers.helpers import get_mysql_connection
from config.main import START_YEAR, START_MONTH, START_DAY, PREFIX_LIST
import datetime
import MySQLdb
class Statistic(object):
# cname_count_statistic
# a_count_statistic
# registrant_count_statistic
# ns_count_statistic
# mx_count_statistic
# as_count_statistic
# domain_count_statistic
def __init__(self):
"""
:return:
"""
self.connection = get_mysql_connection()
def get_date_after_without_statistic(self, table_prefix):
"""
получить последнию дату без агригации данных
:type table_prefix: unicode
:rtype: date
"""
today = datetime.date.today()
date = datetime.date(START_YEAR, START_MONTH, START_DAY)
cursor = self.connection.cursor(MySQLdb.cursors.DictCursor)
while date <= today:
sql = "SELECT count(*) as count FROM %s_count_statistic WHERE date = '%s'" % (table_prefix, date)
cursor.execute(sql)
result = cursor.fetchone()
if result['count'] == 0:
return date
date += datetime.timedelta(days=1)
def _update_domain_count_per_zone(self, date, today, zone):
"""
:type date: date
:type today: date
:type zone: unicode
:return:
"""
cursor = self.connection.cursor(MySQLdb.cursors.DictCursor)
while date <= today:
sql_insert = ""
sql = """SELECT count(*) as count FROM domain_history
WHERE tld = '%s' AND date_start <= '%s' AND date_end >= '%s'
ORDER BY count(*) desc""" % (zone, date, date)
cursor.execute(sql)
data = cursor.fetchall()
for row in data:
sql_insert_date = " ('%s','%s','%s')" % (date, zone, row['count'])
if len(sql_insert) > 5:
sql_insert += ", " + sql_insert_date
else:
sql_insert += sql_insert_date
sql = "INSERT INTO domain_count_statistic(`date`, `tld`, `count`) VALUE " + sql_insert
cursor.execute(sql)
self.connection.commit()
date += datetime.timedelta(days=1)
def update_domain_count_statistic(self):
"""
Обновление статистики по количеству доменов системам
:return:
"""
today = datetime.date.today()
date = self.get_date_after_without_statistic('domain')
for prefix in PREFIX_LIST:
self._update_domain_count_per_zone(date, today, prefix)
def _update_as_count_per_zone(self, date, today, zone):
"""
:type date: date
:type today: date
:type zone: unicode
:return:
"""
cursor = self.connection.cursor(MySQLdb.cursors.DictCursor)
while date <= today:
sql_insert = ""
as_array = {}
for i in range(1, 5):
sql = """SELECT asn%s as as_number, count(*) as count FROM domain_history
WHERE delegated = 'Y' AND tld = '%s' AND date_start <= '%s' AND date_end >= '%s'
GROUP BY asn%s
HAVING count(*) > 50
ORDER BY count(*) desc""" % (i, zone, date, date, i)
cursor.execute(sql)
data = cursor.fetchall()
for row in data:
if row['as_number'] == None:
asn = 0
else:
asn = row['as_number']
if asn in as_array:
as_array[asn] += row['count']
else:
as_array[asn] = row['count']
for key in as_array:
sql_insert_date = " ('%s','%s','%s', '%s')" % (date, zone, key, as_array[key])
if len(sql_insert) > 5:
sql_insert += ", " + sql_insert_date
else:
sql_insert += sql_insert_date
sql = "INSERT INTO as_count_statistic(`date`, `tld`, `asn`, `count`) VALUE " + sql_insert
cursor.execute(sql)
self.connection.commit()
date += datetime.timedelta(days=1)
def update_as_count_statistic(self):
"""
Обновление статистики по автономным системам
:return:
"""
today = datetime.date.today()
date = self.get_date_after_without_statistic('as')
for prefix in PREFIX_LIST:
self._update_as_count_per_zone(date, today, prefix)
def _update_mx_count_per_zone(self, date, today, zone):
"""
:type date: date
:type today: date
:type zone: unicode
:return:
"""
cursor = self.connection.cursor(MySQLdb.cursors.DictCursor)
while date <= today:
sql_insert = ""
mx_array = {}
for i in range(1, 5):
sql = """SELECT mx%s as mx, count(*) as count FROM domain_history
WHERE delegated = 'Y' AND tld = '%s' AND date_start <= '%s' AND date_end >= '%s'
GROUP BY mx%s
HAVING count(*) > 50
ORDER BY count(*) desc""" % (i, zone, date, date, i)
cursor.execute(sql)
data = cursor.fetchall()
for row in data:
if row['mx'] in mx_array:
mx_array[row['mx']] += row['count']
else:
mx_array[row['mx']] = row['count']
for key in mx_array:
sql_insert_date = " ('%s','%s','%s', '%s')" % (date, zone, key, mx_array[key])
if len(sql_insert) > 5:
sql_insert += ", " + sql_insert_date
else:
sql_insert += sql_insert_date
sql = "INSERT INTO mx_count_statistic(`date`, `tld`, `mx`, `count`) VALUE " + sql_insert
cursor.execute(sql)
self.connection.commit()
date += datetime.timedelta(days=1)
def update_mx_count_statistic(self):
"""
Обновлене статистики по MX серверам
:return:
"""
today = datetime.date.today()
date = self.get_date_after_without_statistic('mx')
for prefix in PREFIX_LIST:
self._update_mx_count_per_zone(date, today, prefix)
def _update_ns_count_per_zone(self, date, today, zone):
"""
:type date: date
:type today: date
:type zone: unicode
:return:
"""
cursor = self.connection.cursor(MySQLdb.cursors.DictCursor)
while date <= today:
sql_insert = ""
ns_array = {}
for i in range(1, 5):
sql = """SELECT ns%s as ns, count(*) as count FROM domain_history
WHERE delegated = 'Y' AND tld = '%s' AND date_start <= '%s' AND date_end >= '%s'
GROUP BY ns%s
HAVING count(*) > 50
ORDER BY count(*) desc""" % (i, zone, date, date, i)
cursor.execute(sql)
data = cursor.fetchall()
for row in data:
if row['ns'] in ns_array:
ns_array[row['ns']] += row['count']
else:
ns_array[row['ns']] = row['count']
for key in ns_array:
sql_insert_date = " ('%s','%s','%s', '%s')" % (date, zone, key, ns_array[key])
if len(sql_insert) > 5:
sql_insert += ", " + sql_insert_date
else:
sql_insert += sql_insert_date
sql = "INSERT INTO ns_count_statistic(`date`, `tld`, `ns`, `count`) VALUE " + sql_insert
cursor.execute(sql)
self.connection.commit()
date += datetime.timedelta(days=1)
def update_ns_count_statistic(self):
"""
Обновлене статистики по NS серверам
:return:
"""
today = datetime.date.today()
date = self.get_date_after_without_statistic('ns')
for prefix in PREFIX_LIST:
self._update_ns_count_per_zone(date, today, prefix)
def _update_registrant_count_per_zone(self, date, today, zone):
"""
:type date: date
:type today: date
:type zone: unicode
:return:
"""
cursor = self.connection.cursor(MySQLdb.cursors.DictCursor)
while date <= today:
sql_insert = ""
sql = """SELECT registrant as registrant, count(*) as count FROM domain_history
WHERE tld = '%s' AND date_start <= '%s' AND date_end >= '%s'
GROUP BY registrant
HAVING count(*) > 50
ORDER BY count(*) desc""" % (zone, date, date)
cursor.execute(sql)
data = cursor.fetchall()
for row in data:
sql_insert_date = " ('%s','%s','%s','%s')" % (date, row['registrant'], zone, row['count'])
if len(sql_insert) > 5:
sql_insert += ", " + sql_insert_date
else:
sql_insert += sql_insert_date
sql = "INSERT INTO registrant_count_statistic(`date`, `registrant`, `tld`, `count`) VALUE " + sql_insert
cursor.execute(sql)
self.connection.commit()
date += datetime.timedelta(days=1)
def update_registrant_count_statistic(self):
"""
Обновлене статистики по Регистраторам
:return:
"""
today = datetime.date.today()
date = self.get_date_after_without_statistic('registrant')
for prefix in PREFIX_LIST:
self._update_registrant_count_per_zone(date, today, prefix)
def _update_a_count_per_zone(self, date, today, zone):
"""
:type date: date
:type today: date
:type zone: unicode
:return:
"""
cursor = self.connection.cursor(MySQLdb.cursors.DictCursor)
while date <= today:
sql_insert = ""
a_array = {}
asn_array = {}
for i in range(1, 5):
sql = """SELECT a%s as a, asn%s as asn, count(*) as count FROM domain_history
WHERE delegated = 'Y' AND tld = '%s' AND date_start <= '%s' AND date_end >= '%s'
GROUP BY a%s
HAVING count(*) > 50
ORDER BY count(*) desc""" % (i, i, zone, date, date, i)
cursor.execute(sql)
data = cursor.fetchall()
for row in data:
if row['a'] in a_array:
a_array[row['a']] += row['count']
else:
a_array[row['a']] = row['count']
for row in data:
if row['asn'] is None:
asn = 0
else:
asn = row['asn']
asn_array[row['a']] = asn
for key in a_array:
if key in asn_array:
asn = asn_array[key]
else:
asn = 0
sql_insert_date = " ('%s','%s','%s', '%s', '%s')" % (date, zone, key, a_array[key], asn)
if len(sql_insert) > 5:
sql_insert += ", " + sql_insert_date
else:
sql_insert += sql_insert_date
sql = "INSERT INTO a_count_statistic(`date`, `tld`, `a`, `count`, `asn`) VALUE " + sql_insert
cursor.execute(sql)
self.connection.commit()
date += datetime.timedelta(days=1)
def update_a_count_statistic(self):
"""
Обновлене статистики по A записям
:return:
"""
today = datetime.date.today()
date = self.get_date_after_without_statistic('a')
for prefix in PREFIX_LIST:
self._update_a_count_per_zone(date, today, prefix)
def _update_cname_count_per_zone(self, date, today, zone):
"""
:type date: date
:type today: date
:type zone: unicode
:return:
"""
cursor = self.connection.cursor(MySQLdb.cursors.DictCursor)
while date <= today:
sql_insert = ""
sql = """SELECT cname as cname, count(*) as count FROM domain_history
WHERE tld = '%s' AND date_start <= '%s' AND date_end >= '%s'
GROUP BY cname
HAVING count(*) > 50
ORDER BY count(*) desc""" % (zone, date, date)
cursor.execute(sql)
data = cursor.fetchall()
for row in data:
sql_insert_date = " ('%s','%s','%s','%s')" % (date, row['cname'], zone, row['count'])
if len(sql_insert) > 5:
sql_insert += ", " + sql_insert_date
else:
sql_insert += sql_insert_date
sql = "INSERT INTO cname_count_statistic(`date`, `cname`, `tld`, `count`) VALUE " + sql_insert
cursor.execute(sql)
self.connection.commit()
date += datetime.timedelta(days=1)
def cname_count_statistic(self):
"""
Обновлене статистики по CNAME записям
:return:
"""
today = datetime.date.today()
date = self.get_date_after_without_statistic('cname')
for prefix in PREFIX_LIST:
self._update_a_count_per_zone(date, today, prefix)
def update_all_statistic(self):
"""
Обновление всех статистик
:return:
"""
self.update_a_count_statistic()
self.update_as_count_statistic()
self.update_domain_count_statistic()
self.update_mx_count_statistic()
self.update_ns_count_statistic()
self.update_registrant_count_statistic()
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
__author__ = '<NAME>'
from helpers.helpers import get_mysql_connection
import datetime
import MySQLdb
class Screenshoter(object):
def __init__(self):
pass<file_sep>#!/usr/bin/env bash
set -e
mv /dev/log /dev/log.orig || true
ln -sf /syslog/log /dev/log || true
chmod 644 /etc/resolv.conf /etc/hosts* /etc/localtime || true
( cd /dev && chmod 666 full null random tty urandom zero ) || true
chmod 711 / /etc /var/log || true
chmod 700 /usr/bin/gcc* /usr/bin/g++* /usr/bin/ld /usr/bin/make || true
mount -o remount,hidepid=2 /proc || true
mount -o remount,size=50% /dev/shm || true
if ! find /home/mysql/ -maxdepth 0 -empty | xargs -r false; then
exec mysqld --verbose --external-locking --delay-key-write=0 --query-cache-size=0
fi
if find /home/mysql/ -maxdepth 0 -empty | xargs -r false; then
echo "Create base"
mkdir /home/mysql || true
chmod 777 /home/mysql || true
mysql_install_db --basedir=/usr || true
mysqld --verbose --external-locking --delay-key-write=0 --query-cache-size=0 &
sleep 10
echo "create database domain_statistic;" | mysql mysql;
echo "GRANT ALL PRIVILEGES ON domain_statistic.* TO domain_statistic@% IDENTIFIED BY 'domain_statisticdomain_statistic';" | mysql mysql;
echo "FLUSH PRIVILEGES;" | mysql mysql;
cat /root/structure.sql | mysql domain_statistic;
MYPASSWD=<PASSWORD>
mysqladmin -u root password $MYPASSWD;
echo "[client]" > /root/.my.cnf;
echo "password=$<PASSWORD>" >> /root/.my.cnf;
fi
# EOF
<file_sep>DROP TABLE IF EXISTS `as_list`;
CREATE TABLE `as_list` (
`id` int(11) NOT NULL,
`descriptions` varchar(255) DEFAULT NULL COMMENT 'Full as descriptions',
`country` varchar(45) DEFAULT NULL COMMENT 'Country',
`date_register` datetime DEFAULT NULL COMMENT 'Date create',
`organization_register` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `domain`;
CREATE TABLE `domain` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`domain_name` varchar(256) DEFAULT NULL,
`registrant` varchar(64) DEFAULT NULL,
`tld` varchar(32) DEFAULT NULL,
`register_date` datetime DEFAULT NULL,
`register_date_end` datetime DEFAULT NULL,
`free_date` datetime DEFAULT NULL,
`delegated` enum('Y','N') DEFAULT NULL,
`a1` varchar(16) DEFAULT NULL,
`a2` varchar(16) DEFAULT NULL,
`a3` varchar(16) DEFAULT NULL,
`a4` varchar(16) DEFAULT NULL,
`ns1` varchar(45) DEFAULT NULL,
`ns2` varchar(45) DEFAULT NULL,
`ns3` varchar(45) DEFAULT NULL,
`ns4` varchar(45) DEFAULT NULL,
`mx1` varchar(70) DEFAULT NULL,
`mx2` varchar(70) DEFAULT NULL,
`mx3` varchar(70) DEFAULT NULL,
`mx4` varchar(70) DEFAULT NULL,
`txt` varchar(255) DEFAULT NULL,
`asn1` int(11) DEFAULT NULL,
`asn2` int(11) DEFAULT NULL,
`asn3` int(11) DEFAULT NULL,
`asn4` int(11) DEFAULT NULL,
`aaaa1` varchar(55) DEFAULT NULL,
`aaaa2` varchar(55) DEFAULT NULL,
`aaaa3` varchar(55) DEFAULT NULL,
`aaaa4` varchar(55) DEFAULT NULL,
`cname` varchar(55) DEFAULT NULL,
`nserrors` varchar(100) DEFAULT NULL,
`load_today` enum('Y','N') DEFAULT 'Y',
`last_update` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `domain_name` (`domain_name`(100)),
KEY `registrant` (`registrant`),
KEY `deligated` (`delegated`),
KEY `load_today` (`load_today`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
DELIMITER ;;
DROP TRIGGER IF EXISTS `domain_statistic`.`domain_AFTER_INSERT`;
CREATE TRIGGER `domain_statistic`.`domain_AFTER_INSERT` AFTER INSERT ON `domain` FOR EACH ROW
BEGIN
INSERT INTO domain_history(domain_id,date_start, date_end, domain_name,
registrant, tld, register_date, register_date_end,
free_date, delegated, a1, a2,
a3, a4, mx1, mx2,
mx3, mx4, ns1, ns2,
ns3, ns4, txt, asn1,
asn2, asn3, asn4, aaaa1,
aaaa2, aaaa3, aaaa4, cname,
nserrors)
VALUE(NEW.id, NOW(), '2099-01-01', NEW.domain_name,
NEW.registrant, NEW.tld, NEW.register_date, NEW.register_date_end,
NEW.free_date, NEW.delegated, NEW.a1, NEW.a2,
NEW.a3, NEW.a4, NEW.mx1, NEW.mx2,
NEW.mx3, NEW.mx4, NEW.ns1, NEW.ns2,
NEW.ns3, NEW.ns4, NEW.txt, NEW.asn1,
NEW.asn2, NEW.asn3, NEW.asn4, NEW.aaaa1,
NEW.aaaa2, NEW.aaaa3, NEW.aaaa4, NEW.cname,
NEW.nserrors);
END ;;
DELIMITER ;
DELIMITER ;;
DROP TRIGGER IF EXISTS `domain_statistic`.`domain_BEFORE_UPDATE`;
CREATE TRIGGER `domain_statistic`.`domain_BEFORE_UPDATE` BEFORE UPDATE ON `domain` FOR EACH ROW
BEGIN
DECLARE max_id integer;
IF NEW.registrant <> OLD.registrant
OR NEW.register_date <> OLD.register_date
OR NEW.register_date_end <> OLD.register_date_end
OR NEW.free_date <> OLD.free_date
OR NEW.delegated <> OLD.delegated
OR NEW.a1 <> OLD.a1
OR NEW.a2 <> OLD.a2
OR NEW.a3 <> OLD.a3
OR NEW.a4 <> OLD.a4
OR NEW.mx1 <> OLD.mx1
OR NEW.mx2 <> OLD.mx2
OR NEW.mx3 <> OLD.mx3
OR NEW.mx4 <> OLD.mx4
OR NEW.ns1 <> OLD.ns1
OR NEW.ns2 <> OLD.ns2
OR NEW.ns3 <> OLD.ns3
OR NEW.ns4 <> OLD.ns4
OR NEW.txt <> OLD.txt
OR NEW.asn1 <> OLD.asn1
OR NEW.asn2 <> OLD.asn2
OR NEW.asn3 <> OLD.asn3
OR NEW.asn4 <> OLD.asn4
OR NEW.aaaa1 <> OLD.aaaa1
OR NEW.aaaa2 <> OLD.aaaa2
OR NEW.aaaa3 <> OLD.aaaa3
OR NEW.aaaa4 <> OLD.aaaa4
OR NEW.cname <> OLD.cname
THEN
SELECT max(id) INTO max_id FROM domain_history WHERE domain_id = OLD.id;
UPDATE domain_history SET date_end = NOW() WHERE id = max_id;
INSERT INTO domain_history(domain_id,date_start, date_end, domain_name,
registrant, tld, register_date, register_date_end,
free_date, delegated, a1, a2,
a3, a4, mx1, mx2,
mx3, mx4, ns1, ns2,
ns3, ns4, txt, asn1,
asn2, asn3, asn4, aaaa1,
aaaa2, aaaa3, aaaa4, cname,
nserrors)
VALUE(NEW.id, NOW(), '2099-01-01', NEW.domain_name,
NEW.registrant, NEW.tld, NEW.register_date, NEW.register_date_end,
NEW.free_date, NEW.delegated, NEW.a1, NEW.a2,
NEW.a3, NEW.a4, NEW.mx1, NEW.mx2,
NEW.mx3, NEW.mx4, NEW.ns1, NEW.ns2,
NEW.ns3, NEW.ns4, NEW.txt, NEW.asn1,
NEW.asn2, NEW.asn3, NEW.asn4, NEW.aaaa1,
NEW.aaaa2, NEW.aaaa3, NEW.aaaa4, NEW.cname,
NEW.nserrors);
END IF;
END ;;
DELIMITER ;
DELIMITER ;;
DROP TRIGGER IF EXISTS `domain_statistic`.`domain_BEFORE_DELETE`;
CREATE TRIGGER `domain_statistic`.`domain_BEFORE_DELETE` BEFORE DELETE ON `domain` FOR EACH ROW
BEGIN
DECLARE max_id integer;
SELECT max(id) INTO max_id FROM domain_history WHERE domain_id = OLD.id;
UPDATE domain_history SET date_end = NOW() WHERE id = max_id;
END ;;
DELIMITER ;
DROP TABLE IF EXISTS `domain_history`;
CREATE TABLE `domain_history` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`domain_id` int(11) NOT NULL,
`date_start` date DEFAULT NULL,
`date_end` date DEFAULT NULL,
`domain_name` varchar(256) DEFAULT NULL,
`registrant` varchar(64) DEFAULT NULL,
`tld` varchar(32) DEFAULT NULL,
`register_date` datetime DEFAULT NULL,
`register_date_end` datetime DEFAULT NULL,
`free_date` datetime DEFAULT NULL,
`delegated` enum('Y','N') DEFAULT NULL,
`a1` varchar(16) DEFAULT NULL,
`a2` varchar(16) DEFAULT NULL,
`a3` varchar(16) DEFAULT NULL,
`a4` varchar(16) DEFAULT NULL,
`ns1` varchar(45) DEFAULT NULL,
`ns2` varchar(45) DEFAULT NULL,
`ns3` varchar(45) DEFAULT NULL,
`ns4` varchar(45) DEFAULT NULL,
`mx1` varchar(70) DEFAULT NULL,
`mx2` varchar(70) DEFAULT NULL,
`mx3` varchar(70) DEFAULT NULL,
`mx4` varchar(70) DEFAULT NULL,
`txt` varchar(255) DEFAULT NULL,
`asn1` int(11) DEFAULT NULL,
`asn2` int(11) DEFAULT NULL,
`asn3` int(11) DEFAULT NULL,
`asn4` int(11) DEFAULT NULL,
`aaaa1` varchar(55) DEFAULT NULL,
`aaaa2` varchar(55) DEFAULT NULL,
`aaaa3` varchar(55) DEFAULT NULL,
`aaaa4` varchar(55) DEFAULT NULL,
`cname` varchar(55) DEFAULT NULL,
`nserrors` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `domain_id` (`domain_id`),
KEY `period` (`date_start`, `date_end`),
KEY `period_tld` (`date_start`, `date_end`, `tld`),
KEY `period_tld_delegated` (`date_start`, `date_end`, `tld`, `delegated`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `regru_providers`;
CREATE TABLE `regru_providers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date_create` date NOT NULL,
`name` varchar(255) NOT NULL,
`description` varchar(255) NOT NULL DEFAULT '-',
`link` varchar(255) NOT NULL,
`type` varchar(255) NOT NULL DEFAULT 'nothosting',
`status` varchar(255) NOT NULL DEFAULT 'noactive',
`count_ns` int(11) NOT NULL DEFAULT '2',
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `regru_stat_data`;
CREATE TABLE `regru_stat_data` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`provider_id` int(11) DEFAULT NULL,
`value` bigint(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `provider_id` (`provider_id`),
KEY `date` (`date`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `domain_count_statistic`;
CREATE TABLE `domain_count_statistic` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`tld` VARCHAR(32) DEFAULT NULL,
`count` bigint(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `date` (`date`),
KEY `date_tld` (`date`, `tld`),
UNIQUE KEY `uniq` (`date`, `tld`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `as_count_statistic`;
CREATE TABLE `as_count_statistic` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`asn` int(11) DEFAULT NULL,
`tld` varchar(32) DEFAULT NULL,
`count` bigint(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `date` (`date`),
KEY `date_tld` (`date`, `tld`),
UNIQUE KEY `uniq` (`date`, `asn`, `tld`),
KEY asn (`asn`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `mx_count_statistic`;
CREATE TABLE `mx_count_statistic` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`mx` VARCHAR(70) DEFAULT NULL,
`tld` varchar(32) DEFAULT NULL,
`count` bigint(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `date` (`date`),
KEY `date_tld` (`date`, `tld`),
UNIQUE KEY `uniq` (`date`, `mx`, `tld`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `ns_count_statistic`;
CREATE TABLE `ns_count_statistic` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`ns` VARCHAR(70) DEFAULT NULL,
`tld` varchar(32) DEFAULT NULL,
`count` bigint(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `date` (`date`),
KEY `date_tld` (`date`, `tld`),
UNIQUE KEY `uniq` (`date`, `ns`, `tld`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `registrant_count_statistic`;
CREATE TABLE `registrant_count_statistic` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`registrant` VARCHAR(70) DEFAULT NULL,
`tld` varchar(32) DEFAULT NULL,
`count` bigint(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `date` (`date`),
KEY `date_tld` (`date`, `tld`),
UNIQUE KEY `uniq` (`date`, `registrant`, `tld`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `a_count_statistic`;
CREATE TABLE `a_count_statistic` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`a` VARCHAR(16) DEFAULT NULL,
`asn` int(11) DEFAULT NULL,
`tld` varchar(32) DEFAULT NULL,
`count` bigint(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `date` (`date`),
KEY `date_tld` (`date`, `tld`),
UNIQUE KEY `uniq` (`date`, `a`, `tld`),
KEY asn (`asn`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `cname_count_statistic`;
CREATE TABLE `cname_count_statistic` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`cname` VARCHAR(55) DEFAULT NULL,
`tld` varchar(32) DEFAULT NULL,
`count` bigint(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `date` (`date`),
KEY `date_tld` (`date`, `tld`),
UNIQUE KEY `uniq` (`date`, `cname`, `tld`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
|
7c816bf61d5e98d2251c7efb963a100ec956c30c
|
[
"SQL",
"Python",
"Shell"
] | 5
|
Python
|
ivsero/domain_statistic
|
6321d9a59e57c5653a69187fd4397bf039b623ef
|
e438f4c5330c6f3f953b0550f3ae337255127c42
|
refs/heads/master
|
<repo_name>sydtju/TinySTL<file_sep>/TinySTL/Test/StringTest.h
#ifndef _STRING_TEST_H_
#define _STRING_TEST_H_
#include "TestUtil.h"
#include "../String.h"
#include <string>
#include <cassert>
#include <iterator>
namespace TinySTL{
namespace StringTest{
using stdStr = std::string;
using tsStr = TinySTL::string;
void testCase1();
void testCase2();
void testCase3();
void testCase4();
void testCase5();
void testCase6();
void testCase7();
void testCase8();
void testCase9();
void testCase10();
void testCase11();
void testCase12();
void testCase13();
void testCase14();
void testCase15();
void testCase16();
void testCase17();
void testCase18();
void testCase19();
void testCase20();
void testCase21();
void testCase22();
void testCase23();
void testCase24();
void testCase25();
void testCase26();
void testCase27();
void testCase28();
void testCase29();
void testAllCases();
}
}
#endif<file_sep>/TinySTL/Test/COWPtrTest.h
#ifndef _COWPTR_TEST_H_
#define _COWPTR_TEST_H_
#include "../COWPtr.h"
#include <cassert>
namespace TinySTL{
namespace COWPtrTest{
void testCase1();
void testAllCases();
}
}
#endif<file_sep>/TinySTL/Test/BitmapTest.h
#ifndef _BITMAP_TEST_H_
#define _BITMAP_TEST_H_
#include "TestUtil.h"
#include "../Bitmap.h"
#include <cassert>
#include <iostream>
namespace TinySTL{
namespace BitmapTest{
using std::cout;
using std::endl;
void testCase1();
void testCase2();
void testCase3();
void testCase4();
void testCase5();
void testCase6();
void testCase7();
void testAllCases();
}
}
#endif<file_sep>/TinySTL/Test/SharedPtrTest.cpp
#include "SharedPtrTest.h"
#include "../String.h"
namespace TinySTL{
namespace SharedPtrTest{
void testCase1(){
shared_ptr<int> sp1(new int(10));
assert(*(sp1.get()) == 10);
shared_ptr<int> sp2(new int(1), default_delete<int>());
assert(sp2.use_count() == 1);
auto sp3(sp2);
assert(sp3.use_count() == 2);
{
auto sp4 = sp2;
assert(sp4.use_count() == 3 && sp3.use_count() == sp4.use_count());
assert(sp2.get() == sp3.get() && sp2.get() == sp4.get());
assert(sp2 == sp3 && !(sp2 != sp4));
}
assert(sp3.use_count() == 2);
shared_ptr<string> sp5(new string("hello"));
assert(*sp5 == "hello");
sp5->append(" world");
assert(*sp5 == "hello world");
auto sp6 = make_shared<string>(10, '0');
assert(*sp6 == "0000000000");
shared_ptr<int> spp;
assert(spp == nullptr);
assert(!(spp != nullptr));
}
void testAllCases(){
testCase1();
}
}
}<file_sep>/TinySTL/Test/BinarySearchTreeTest.h
#ifndef _BINARY_SEARCH_TREE_TEST_H_
#define _BINARY_SEARCH_TREE_TEST_H_
#include "TestUtil.h"
#include "../BinarySearchTree.h"
#include <algorithm>
#include <cassert>
#include <random>
#include <string>
#include <vector>
namespace TinySTL{
namespace BinarySearchTreeTest{
template<class T>
using tsBst = TinySTL::binary_search_tree < T > ;
void testCase1();
void testCase2();
void testCase3();
void testCase4();
void testAllCases();
}
}
#endif<file_sep>/TinySTL/CircularBuffer.h
#ifndef _CIRCULAR_BUFFER_H_
#define _CIRCULAR_BUFFER_H_
#include "Allocator.h"
#include "Iterator.h"
#include "UninitializedFunctions.h"
#include <cassert>
namespace TinySTL{
template<class T, size_t N, class Alloc>
class circular_buffer;
namespace Detail{
//the iterator of circular buffer
template<class T, size_t N, class Alloc = allocator<T>>
class cb_iter:iterator<bidirectional_iterator_tag, T>{//bidirectional iterator
private:
typedef ::TinySTL::circular_buffer<T, N, Alloc> cb;
typedef cb *cbPtr;
T *ptr_;
int index_;
cbPtr container_;
public:
cb_iter() :ptr_(0), index_(0), container_(0){}
cb_iter(T *ptr, cbPtr container) :
ptr_(ptr), index_(ptr - container->start_), container_(container){}
cb_iter(const cb_iter& cit) :
ptr_(cit.ptr_), index_(cit.index_), container_(cit.container_){}
cb_iter& operator = (const cb_iter& cit);
public:
operator T*(){ return ptr_; }
T& operator *(){ return *ptr_; }
T *operator ->(){ return &(operator*()); }
cb_iter& operator ++();
cb_iter operator ++(int);
cb_iter& operator --();
cb_iter operator --(int);
bool operator == (const cb_iter& it)const;
bool operator != (const cb_iter& it)const;
private:
void setIndex_(int index){ index_ = index; }
void setPtr_(T *ptr){ ptr_ = ptr; }
int nextIndex(int index){ return (++index) % N; }
int prevIndex(int index);
public:
template<class T, size_t N, class Alloc>
friend cb_iter<T, N, Alloc> operator +(const cb_iter<T, N, Alloc>& cit, std::ptrdiff_t i);
template<class T, size_t N, class Alloc>
friend cb_iter<T, N, Alloc> operator -(const cb_iter<T, N, Alloc>& cit, std::ptrdiff_t i);
};
}//end of Detail namespace
//circular buffer
template<class T, size_t N, class Alloc = allocator<T>>
class circular_buffer{
template<class T, size_t N, class Alloc>
friend class ::TinySTL::Detail::cb_iter;
public:
typedef T value_type;
typedef Detail::cb_iter<T, N> iterator;
typedef iterator pointer;
typedef T& reference;
typedef int size_type;
typedef ptrdiff_t difference_type;
private:
T *start_;
T *finish_;
int indexOfHead;//the first position
int indexOfTail;//the last position
size_type size_;
typedef Alloc dataAllocator;
public:
explicit circular_buffer(const int& n, const value_type& val = value_type());
template<class InputIterator>
circular_buffer(InputIterator first, InputIterator last);
circular_buffer(const circular_buffer& cb);
circular_buffer& operator = (const circular_buffer& cb);
circular_buffer& operator = (circular_buffer&& cb);
circular_buffer(circular_buffer&& cb);
~circular_buffer();
bool full(){ return size_ == N; }
bool empty(){ return size_ == 0; }
difference_type capacity(){ return finish_ - start_; }
size_type size(){ return size_; }
void clear();
iterator first(){ return iterator(start_ + indexOfHead, this); }
iterator last(){ return iterator(start_ + indexOfTail, this); }
reference operator [](size_type i){ return *(start_ + i); }
reference front(){ return *(start_ + indexOfHead); }
reference back(){ return *(start_ + indexOfTail); }
void push_back(const T& val);
void pop_front();
bool operator == (circular_buffer& cb);
bool operator != (circular_buffer& cb);
Alloc get_allocator(){ return dataAllocator; }
private:
void allocateAndFillN(const int& n, const value_type& val);
template<class InputIterator>
void allocateAndCopy(InputIterator first, InputIterator last);
int nextIndex(int index){ return (index + 1) % N; }
void copyAllMembers(const circular_buffer& cb);
void zeroCircular(circular_buffer& cb);
void clone(const circular_buffer& cb);
public:
template<class T, size_t N, class Alloc>
friend std::ostream& operator <<(std::ostream& os, circular_buffer<T, N, Alloc>& cb);
};//end of circular buffer
}
#include "Detail\CircularBuffer.impl.h"
#endif<file_sep>/TinySTL/Test/DequeTest.h
#ifndef _DEQUE_TEST_H_
#define _DEQUE_TEST_H_
#include "TestUtil.h"
#include "../Deque.h"
#include <deque>
#include <cassert>
#include <string>
namespace TinySTL{
namespace DequeTest{
template<class T>
using stdDQ = std::deque < T > ;
template<class T>
using tsDQ = TinySTL::deque < T > ;
void testCase1();
void testCase2();
void testCase3();
void testCase4();
void testCase5();
void testCase6();
void testAllCases();
}
}
#endif<file_sep>/TinySTL/Detail/Graph.impl.h
#include "../Graph.h"
namespace TinySTL{
namespace Detail{
template<class Index, class Value, class EqualFunc>
typename graph<Index, Value, EqualFunc>::node_type
graph<Index, Value, EqualFunc>::make_node(const Index& index, const Value& val){
return node_type(index, val);
}
template<class Index, class Value, class EqualFunc>
typename const graph<Index, Value, EqualFunc>::node_type&
graph<Index, Value, EqualFunc>::get_node(const Index& index){
for (auto& pair : nodes_){
if (equal_func(pair.first.first, index))
return pair.first;
}
static node_type empty_node;
return empty_node;
}
template<class Index, class Value, class EqualFunc>
bool graph<Index, Value, EqualFunc>::is_contained(const Index& index){
for (auto& pair : nodes_){
if (equal_func(pair.first.first, index))
return true;
}
return false;
}
template<class Index, class Value, class EqualFunc>
typename graph<Index, Value, EqualFunc>::nodes_set_type
graph<Index, Value, EqualFunc>::empty_node_set(){
return nodes_set_type();
}
template<class Index, class Value, class EqualFunc>
bool graph<Index, Value, EqualFunc>::empty()const{
return nodes_.empty();
}
template<class Index, class Value, class EqualFunc>
typename graph<Index, Value, EqualFunc>::inner_iterator
graph<Index, Value, EqualFunc>::begin(const Index& index){
for (auto& pair : nodes_){
if (equal_func(pair.first.first, index))
return inner_iterator(this, (pair.second).begin());
}
return end(index);
}
template<class Index, class Value, class EqualFunc>
typename graph<Index, Value, EqualFunc>::inner_iterator
graph<Index, Value, EqualFunc>::end(const Index& index){
for (auto& pair : nodes_){
if (equal_func(pair.first.first, index))
return inner_iterator(this, (pair.second).end());
}
return inner_iterator();
}
template<class Index, class Value, class EqualFunc>
typename graph<Index, Value, EqualFunc>::iterator graph<Index, Value, EqualFunc>::begin(){
return iterator(this, nodes_.begin());
}
template<class Index, class Value, class EqualFunc>
typename graph<Index, Value, EqualFunc>::iterator graph<Index, Value, EqualFunc>::end(){
return iterator(this, nodes_.end());
}
template<class Index, class Value, class EqualFunc>
size_t graph<Index, Value, EqualFunc>::size()const{
return size_;
}
template<class Index, class Value, class EqualFunc>
typename graph<Index, Value, EqualFunc>::nodes_set_type
graph<Index, Value, EqualFunc>::adjacent_nodes(const Index& index){
nodes_set_type s;
for (auto it = begin(index); it != end(index); ++it){
s.push_back(*it);
}
return s;
}
template<class Index, class Value, class EqualFunc>
typename graph<Index, Value, EqualFunc>::nodes_set_type
graph<Index, Value, EqualFunc>::adjacent_nodes(const node_type& n){
return adjacent_nodes(n.first);
}
template<class Index, class Value, class EqualFunc>
void graph<Index, Value, EqualFunc>::_DFS(node_type& node,
visiter_func_type func, Unordered_set<Index, std::hash<Index>, EqualFunc>& visited){
auto nodes = adjacent_nodes(node.first);
func(node);
visited.insert(node.first);
for (auto& n : nodes){
if (visited.count(n.first) == 0)//has not visited
_DFS(n, func, visited);
}
}
template<class Index, class Value, class EqualFunc>
void graph<Index, Value, EqualFunc>::DFS(const Index& index, visiter_func_type func){
node_type start = (get_node(index));
Unordered_set<Index, std::hash<Index>, EqualFunc> visited(7);
_DFS(start, func, visited);
}
template<class Index, class Value, class EqualFunc>
void graph<Index, Value, EqualFunc>::_BFS(node_type& node,
visiter_func_type func, Unordered_set<Index, std::hash<Index>, EqualFunc>& visited){
auto nodes = adjacent_nodes(node.first);
func(node);
visited.insert(node.first);
do{
nodes_set_type temp;
for (auto it = nodes.begin(); it != nodes.end(); ++it){
if (visited.count(it->first) == 0){//has not visited
func(*it);
visited.insert(it->first);
auto s = adjacent_nodes(it->first);
temp.insert(temp.end(), s.begin(), s.end());
}
}
nodes = temp;
} while (!nodes.empty());
}
template<class Index, class Value, class EqualFunc>
void graph<Index, Value, EqualFunc>::BFS(const Index& index, visiter_func_type func){
node_type start = (get_node(index));
Unordered_set<Index, std::hash<Index>, EqualFunc> visited(7);
_BFS(start, func, visited);
}
template<class Index, class Value, class EqualFunc>
string graph<Index, Value, EqualFunc>::to_string(){
string str;
std::ostringstream oss;
for (auto oit = begin(); oit != end(); ++oit){
oss << "[" << oit->first << "," << oit->second << "]" << ":";
auto eit = end(oit->first);
for (auto iit = begin(oit->first); iit != eit; ++iit){
oss << "[" << iit->first << "," << iit->second << "]" << "->";
}
oss << "[nil]" << std::endl << std::setw(4) << "|" << std::endl;
}
oss << "[nil]" << std::endl;
str.append(oss.str().c_str());
return str;
}
template<class Index, class Value, class EqualFunc>
typename graph<Index, Value, EqualFunc>::equal_func_type
graph<Index, Value, EqualFunc>::get_equal_func()const{
return equal_func;
}
//********************************************************************************
template<class Index, class Value, class EqualFunc>
inner_iterator<Index, Value, EqualFunc>& inner_iterator<Index, Value, EqualFunc>::operator ++(){
++inner_it_;
return *this;
}
template<class Index, class Value, class EqualFunc>
const inner_iterator<Index, Value, EqualFunc> inner_iterator<Index, Value, EqualFunc>::operator ++(int){
auto temp = *this;
++*this;
return temp;
}
template<class Index, class Value, class EqualFunc>
bool operator ==(const inner_iterator<Index, Value, EqualFunc>& lhs,
const inner_iterator<Index, Value, EqualFunc>& rhs){
return lhs.container_ == rhs.container_ && lhs.inner_it_ == rhs.inner_it_;
}
template<class Index, class Value, class EqualFunc>
bool operator !=(const inner_iterator<Index, Value, EqualFunc>& lhs,
const inner_iterator<Index, Value, EqualFunc>& rhs){
return !(lhs == rhs);
}
//*********************************************************************************
template<class Index, class Value, class EqualFunc>
outter_iterator<Index, Value, EqualFunc>& outter_iterator<Index, Value, EqualFunc>::operator ++(){
++outter_it_;
return *this;
}
template<class Index, class Value, class EqualFunc>
const outter_iterator<Index, Value, EqualFunc> outter_iterator<Index, Value, EqualFunc>::operator ++(int){
auto temp = *this;
++*this;
return temp;
}
template<class Index, class Value, class EqualFunc>
bool operator ==(const outter_iterator<Index, Value, EqualFunc>& lhs,
const outter_iterator<Index, Value, EqualFunc>& rhs){
return lhs.container_ == rhs.container_ && lhs.outter_it_ == rhs.outter_it_;
}
template<class Index, class Value, class EqualFunc>
bool operator !=(const outter_iterator<Index, Value, EqualFunc>& lhs,
const outter_iterator<Index, Value, EqualFunc>& rhs){
return !(lhs == rhs);
}
}//end of Detail
template<class Index, class Value, class EqualFunc>
directed_graph<Index, Value, EqualFunc>::directed_graph():graph(){}
template<class Index, class Value, class EqualFunc>
void directed_graph<Index, Value, EqualFunc>::add_node_helper(const Index& index, const nodes_set_type& nodes){
if (nodes.empty())
return;
//find node n's list
list<typename graph::node_type>* l;
for (auto& pair : nodes_){
if (equal_func(pair.first.first, index))
l = &(pair.second);
}
for (const auto& item : nodes){
l->push_front(item);
if (!is_contained(item.first)){
add_node(item, empty_node_set());
}
}
}
template<class Index, class Value, class EqualFunc>
void directed_graph<Index, Value, EqualFunc>::add_node(const node_type& n, const nodes_set_type& nodes){
if (!is_contained(n.first)){
nodes_.push_front(make_pair(n, list<typename graph::node_type>()));
++size_;
}
add_node_helper(n.first, nodes);
}
template<class Index, class Value, class EqualFunc>
void directed_graph<Index, Value, EqualFunc>::add_node(const Index& index, const nodes_set_type& nodes){
add_node_helper(index, nodes);
}
template<class Index, class Value, class EqualFunc>
void directed_graph<Index, Value, EqualFunc>::delete_node(const Index& index){
for (auto oit = nodes_.begin(); oit != nodes_.end();){
auto& l = oit->second;
if (equal_func((oit->first).first, index)){
oit = nodes_.erase(oit);
}else{
for (auto iit = l.begin(); iit != l.end();){
if (equal_func(iit->first, index))
iit = l.erase(iit);
else
++iit;
}
++oit;
}
}
}
template<class Index, class Value, class EqualFunc>
void directed_graph<Index, Value, EqualFunc>::delete_node(const node_type& item){
delete_node(item.first);
}
template<class Index, class Value, class EqualFunc>
void directed_graph<Index, Value, EqualFunc>::make_edge(const Index& index1, const Index& index2){
auto node1 = get_node(index1), node2 = get_node(index2);
for (auto it = nodes_.begin(); it != nodes_.end(); ++it){
if (equal_func((it->first).first, index1))
(it->second).push_front(node2);
}
}
}<file_sep>/TinySTL/Test/CircularBufferTest.h
#ifndef _CIRCULAR_BUFFER_TEST_H_
#define _CIRCULAR_BUFFER_TEST_H_
#include "TestUtil.h"
#include "../CircularBuffer.h"
#include <cassert>
#include <string>
#include <iostream>
namespace TinySTL{
namespace CircularBufferTest{
template<class T, size_t N>
using tsCB = TinySTL::circular_buffer<T, N>;
template<class T, size_t N>
bool circular_buffer_equal(tsCB<T, N>& cb1, tsCB<T, N> cb2){
auto it1 = cb1.first(), it2 = cb2.first();
for (; it1 != cb1.last() && it2 != cb1.last(); ++it1, ++it2){
if (*it1 != *it2)
return false;
}
return (it1 == cb1.last() && it2 == cb2.last() && (*(cb1.last()) == *(cb2.last())));
}
void testCase1();
void testCase2();
void testCase3();
void testCase4();
void testCase5();
void testCase6();
void testAllCases();
}
}
#endif<file_sep>/TinySTL/Test/TrieTreeTest.cpp
#include "TrieTreeTest.h"
namespace TinySTL{
namespace TrieTreeTest{
void testCase1(){
trie_tree t;
t.insert("abc");
t.insert("def");
assert(t.is_existed("abc"));
assert(!t.is_existed("a"));
}
void testCase2(){
trie_tree t;
string arr[] = { "ab", "abbreviation", "abide", "abolish", "abstract"};
for (const auto& str : arr){
t.insert(str);
}
t.insert("action");
auto v = t.get_word_by_prefix("ab");
assert(TinySTL::Test::container_equal(v, arr));
}
void testCase3(){
trie_tree t;
string arr[] = { "a", "ab", "abc", "d", "a", "abc" };
assert(t.empty());
assert(t.size() == 0);
for (const auto& str : arr){
t.insert(str);
}
assert(!t.empty());
assert(t.size() == 4);
}
void testAllCases(){
testCase1();
testCase2();
testCase3();
}
}
}<file_sep>/TinySTL/Bitmap.h
#ifndef _BITMAP_H_
#define _BITMAP_H_
#include <cstdint>
#include <iostream>
#include <stdexcept>
//#include <string>
#include "Allocator.h"
#include "String.h"
#include "UninitializedFunctions.h"
namespace TinySTL{
//bitmap会将N上调至8的倍数
//因此bitmap实际上会操作的bit数是大于等于N的
template<size_t N>
class bitmap{
public:
typedef allocator<uint8_t> dataAllocator;
private:
uint8_t *start_;
uint8_t *finish_;
const size_t size_;//记录多少bit
const size_t sizeOfUINT8_;//记录多少uint8_t
enum EAlign{ ALIGN = 8 };
public:
bitmap();
//Returns the number of bits in the bitset that are set (i.e., that have a value of one)
size_t count() const;
size_t size() const{ return size_; }
//Returns whether the bit at position pos is set (i.e., whether it is one).
bool test(size_t pos) const;
//Returns whether any of the bits is set (i.e., whether at least one bit in the bitset is set to one).
bool any() const;
//Returns whether none of the bits is set (i.e., whether all bits in the bitset have a value of zero).
bool none() const;
//Returns whether all of the bits in the bitset are set (to one).
bool all() const;
bitmap& set();
bitmap& set(size_t pos, bool val = true);
bitmap& reset();
bitmap& reset(size_t pos);
bitmap& flip();
bitmap& flip(size_t pos);
//std::string to_string() const;
string to_string() const;
template<size_t N>
friend std::ostream& operator <<(std::ostream& os, const bitmap<N>& bm);
private:
size_t roundUp8(size_t bytes);
//将i的第nth为置为newVal
void setNthInInt8(uint8_t& i, size_t nth, bool newVal);
//取出i的第nth位
uint8_t getMask(uint8_t i, size_t nth)const{ return (i & (1 << nth)); }
//将第n个位置转换为其在第几个uint8_t中
size_t getNth(size_t n)const{ return (n / 8); }
//将第n个位置转换为其在第N个uint8_t中的第几个bit上
size_t getMth(size_t n)const{ return (n % EAlign::ALIGN); }
void allocateAndFillN(size_t n, uint8_t val);
void THROW(size_t n)const;
};// end of bitmap
}
#include "Detail\Bitmap.impl.h"
#endif<file_sep>/TinySTL/Test/SharedPtrTest.h
#ifndef _SHARED_PTR_TEST_H_
#define _SHARED_PTR_TEST_H_
#include "../Memory.h"
#include <cassert>
namespace TinySTL{
namespace SharedPtrTest{
void testCase1();
void testAllCases();
}
}
#endif<file_sep>/TinySTL/Test/RefTest.h
#ifndef _REF_TEST_H_
#define _REF_TEST_H_
#include "../Detail/Ref.h"
#include <cassert>
namespace TinySTL{
namespace RefTest{
template<class T>
using ref_t = TinySTL::Detail::ref_t < T > ;
void testCaseRef();
void testAllCases();
}
}
#endif<file_sep>/TinySTL/Test/GraphTest.h
#ifndef _GRAPH_TEST_H_
#define _GRAPH_TEST_H_
#include "TestUtil.h"
#include "../Graph.h"
#include <cassert>
namespace TinySTL{
namespace GraphTest{
template<class Index, class Value>
using dGraph = TinySTL::directed_graph < Index, Value > ;
void testCase1();
void testCase2();
void testCase3();
void testCase4();
void testAllCases();
}
}
#endif<file_sep>/TinySTL/Test/SuffixArrayTest.h
#ifndef _SUFFIX_ARRAY_TEST_H_
#define _SUFFIX_ARRAY_TEST_H_
#include "TestUtil.h"
#include "../SuffixArray.h"
#include <cassert>
#include <string>
namespace TinySTL{
namespace SuffixArrayTest{
void testCase();
void testAllCases();
}
}
#endif<file_sep>/TinySTL/main.cpp
#include <iostream>
#include "Algorithm.h"
#include "Profiler\Profiler.h"
#include "Test\AlgorithmTest.h"
#include "Test\AVLTreeTest.h"
#include "Test\BitmapTest.h"
#include "Test\BinarySearchTreeTest.h"
#include "Test\CircularBufferTest.h"
#include "Test\COWPtrTest.h"
#include "Test\DequeTest.h"
#include "Test\GraphTest.h"
#include "Test\ListTest.h"
#include "Test\PairTest.h"
#include "Test\PriorityQueueTest.h"
#include "Test\QueueTest.h"
#include "Test\RefTest.h"
#include "Test\SharedPtrTest.h"
#include "Test\StackTest.h"
#include "Test\StringTest.h"
#include "Test\SuffixArrayTest.h"
#include "Test\TrieTreeTest.h"
#include "Test\UFSetTest.h"
#include "Test\UniquePtrTest.h"
#include "Test\Unordered_setTest.h"
#include "Test\VectorTest.h"
using namespace TinySTL::Profiler;
int main(){
TinySTL::AlgorithmTest::testAllCases();
TinySTL::AVLTreeTest::testAllCases();
TinySTL::BitmapTest::testAllCases();
TinySTL::BinarySearchTreeTest::testAllCases();
TinySTL::CircularBufferTest::testAllCases();
TinySTL::COWPtrTest::testAllCases();
TinySTL::DequeTest::testAllCases();
TinySTL::ListTest::testAllCases();
TinySTL::GraphTest::testAllCases();
TinySTL::PairTest::testAllCases();
TinySTL::PriorityQueueTest::testAllCases();
TinySTL::QueueTest::testAllCases();
TinySTL::RefTest::testAllCases();
TinySTL::SharedPtrTest::testAllCases();
TinySTL::StackTest::testAllCases();
TinySTL::StringTest::testAllCases();
TinySTL::SuffixArrayTest::testAllCases();
TinySTL::TrieTreeTest::testAllCases();
TinySTL::UFSetTest::testAllCases();
TinySTL::UniquePtrTest::testAllCases();
TinySTL::Unordered_setTest::testAllCases();
TinySTL::VectorTest::testAllCases();
system("pause");
return 0;
}<file_sep>/TinySTL/Test/CircularBufferTest.cpp
#include "CircularBufferTest.h"
#include <sstream>
namespace TinySTL{
namespace CircularBufferTest{
void testCase1(){
tsCB<int, 10> cb1(10, 1);
for (auto i = 0; i != 10; ++i)
assert(cb1[i] == 1);
int arr[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
tsCB<int, 10> cb2(std::begin(arr), std::end(arr));
for (auto i = 0; i != 10; ++i)
assert(cb2[i] == i);
auto cb3(cb2);
assert(circular_buffer_equal(cb2, cb3));
auto cb4(std::move(cb2));//cb2 clear
assert(circular_buffer_equal(cb3, cb4));
auto cb5 = cb3;
assert(circular_buffer_equal(cb3, cb5));
auto cb6 = std::move(cb3);//cb3 clear
assert(circular_buffer_equal(cb5, cb6));
}
void testCase2(){
tsCB<int, 2> cb(1);
assert(cb.size() == 1);
cb.pop_front();
assert(!cb.full());
assert(cb.size() == 0);
assert(cb.empty());
cb.push_back(1), cb.push_back(2);
assert(cb.full());
assert(!cb.empty());
assert(cb.size() == 2);
}
void testCase3(){
tsCB<std::string, 3> cb(3);
cb[0] = "one", cb[1] = "two", cb[2] = "three";
assert(*(cb.first()) == "one" && *(cb.last()) == "three");
assert(cb.front() == "one" && cb.back() == "three");
}
void testCase4(){
tsCB<std::string, 3> cb(1);
assert(cb.front() == std::string());
cb.push_back("zxh"); cb.push_back("jwl");
assert(cb.back() == "jwl");
cb.pop_front();
assert(cb.front() == "zxh");
}
void testCase5(){
tsCB<int, 3> cb1(3), cb2(3);
assert(cb1 == cb2);
assert(!(cb1 != cb2));
cb1[0] = -1;
assert(!(cb1 == cb2));
assert(cb1 != cb2);
}
void testCase6(){
std::string arr[] = { "1", "2", "3" };
tsCB<std::string, 3> cb(std::begin(arr), std::end(arr));
std::ostringstream os;
os << cb;
assert(os.str() == "(1, 2, 3)");
}
void testAllCases(){
testCase1();
testCase2();
testCase3();
testCase4();
testCase5();
testCase6();
}
}
}<file_sep>/TinySTL/kmp.c
void GetNext(char*key,int *next){
int length=strlen(key);
int i=0;
int k=-1;
next[0]=-1;
while(i<length-1){//因为
if(k==-1||key[k]==key[i])
{
k++;i++;
next[i]=k;
}
else
{
k=next[k];
}
}
}
int KmpSerach(char* dat,char*key){
int len_dat=strlen(dat);
int len_key=strlen(key);
int *next=(int*)malloc((len_key+1)*sizeof(int));
int i=0,j=0;
if(!next){
exit(-1);
}
GetNext(key,next);
while(i<len_dat&&j<len_key){
if(j==-1||dat[i]==key[j]){
i++;j++;
}
else{
j=next[j];
}
}
return j==len_key?i-j:-1;
}
<file_sep>/TinySTL/Test/PairTest.h
#ifndef _PAIR_TEST_H_
#define _PAIR_TEST_H_
#include "TestUtil.h"
#include "../Utility.h"
#include <utility>
#include <cassert>
#include <iostream>
#include <string>
namespace TinySTL{
namespace PairTest{
template<typename T>
using stdPair = std::pair < T, T > ;
template<typename T>
using tsPair = TinySTL::pair < T, T > ;
void testCase1();
void testCase2();
void testCase3();
void testCase4();
void testCase5();
void testAllCases();
}
}
#endif<file_sep>/TinySTL/Test/StackTest.h
#ifndef _STACK_TEST_H_
#define _STACK_TEST_H_
#include "TestUtil.h"
#include "../Stack.h"
#include <stack>
#include <cassert>
#include <string>
namespace TinySTL{
namespace StackTest{
template<class T>
using stdSt = std::stack < T > ;
template<class T>
using tsSt = TinySTL::stack < T > ;
void testCase1();
void testCase2();
void testCase3();
void testCase4();
void testAllCases();
}
}
#endif<file_sep>/TinySTL/Test/COWPtrTest.cpp
#include "COWPtrTest.h"
#include "../String.h"
namespace TinySTL{
namespace COWPtrTest{
void testCase1(){
cow_ptr<string> cp1(new string("hello"));
assert(*cp1 == "hello");
assert(cp1);
auto cp2 = cp1;
assert(*cp2 == "hello");
cow_ptr<string> cp3;
cp3 = cp1;
assert(*cp3 == "hello");
assert(cp1.get() == cp2.get() && cp2.get() == cp3.get());
assert(cp1 == cp2 && !(cp2 != cp3));
string zxh(" zouxiaohang");
cp1->append(zxh);
assert(*cp1 == "hello zouxiaohang");
assert(*cp2 == "hello" && *cp3 == "hello");
cow_ptr<string> cp4;
assert(cp4 == nullptr);
}
void testCase2(){
cow_ptr<string> cp1 = make_cow<string>("zouxiaohang");
auto cp2 = cp1, cp3 = cp1;
assert(cp1 == cp2 && cp2 == cp3);
assert(*cp1 == *cp2 && *cp2 == *cp3 && *cp3 == "zouxiaohang");
//cp2->capacity(); change the cow_ptr -> 由于代理类代理的类型未知(T)造成的
string s = *cp2;//read
assert(s == "zouxiaohang");
assert(cp1 == cp2 && cp2 == cp3);
assert(*cp1 == *cp2 && *cp2 == *cp3 && *cp3 == "zouxiaohang");
*cp2 = ("C++");//write
assert(*cp1 == *cp3 && *cp3 == "zouxiaohang");
assert(*cp2 == "C++");
}
void testAllCases(){
testCase1();
testCase2();
}
}
}<file_sep>/TinySTL/Test/AlgorithmTest.cpp
#include "AlgorithmTest.h"
namespace TinySTL{
namespace AlgorithmTest{
void testFill(){
std::vector<int> v1(8), v2(8);
std::fill(v1.begin(), v1.begin() + 4, 5); //5 5 5 5 0 0 0 0
std::fill(v1.begin() + 3, v1.end() - 2, 8); //5 5 5 8 8 8 0 0
TinySTL::fill(v2.begin(), v2.begin() + 4, 5); //5 5 5 5 0 0 0 0
TinySTL::fill(v2.begin() + 3, v2.end() - 2, 8); //5 5 5 8 8 8 0 0
assert(TinySTL::Test::container_equal(v1, v2));
}
void testFillN(){
std::vector<int> v1(8, 10), v2(8, 10);
std::fill_n(v1.begin(), 4, 20); //20 20 20 20 10 10 10 10
std::fill_n(v1.begin() + 3, 3, 33); //20 20 20 33 33 33 10 10
TinySTL::fill_n(v2.begin(), 4, 20); //20 20 20 20 10 10 10 10
TinySTL::fill_n(v2.begin() + 3, 3, 33); //20 20 20 33 33 33 10 10
assert(TinySTL::Test::container_equal(v1, v2));
}
void testMinMax(){
assert(TinySTL::min(1, 2) == 1);
assert(TinySTL::min(2, 1) == 1);
assert(TinySTL::min('a', 'z') == 'a');
assert(TinySTL::min(3.14, 2.72) == 2.72);
assert(TinySTL::max(1, 2) == 2);
assert(TinySTL::max(2, 1) == 2);
assert(TinySTL::max('a', 'z') == 'z');
assert(TinySTL::max(3.14, 2.73) == 3.14);
}
void testHeapAlgorithm(){
int myints[] = { 10, 20, 30, 5, 15 };
std::vector<int> v1(myints, myints + 5);
std::vector<int> v2(myints, myints + 5);
std::make_heap(v1.begin(), v1.end());
TinySTL::make_heap(v2.begin(), v2.end());
assert(TinySTL::Test::container_equal(v1, v2));
std::pop_heap(v1.begin(), v1.end()); v1.pop_back();
TinySTL::pop_heap(v2.begin(), v2.end()); v2.pop_back();
assert(TinySTL::Test::container_equal(v1, v2));
v1.push_back(99); std::push_heap(v1.begin(), v1.end());
v2.push_back(99); TinySTL::push_heap(v2.begin(), v2.end());
assert(TinySTL::Test::container_equal(v1, v2));
std::sort_heap(v1.begin(), v1.end());
TinySTL::sort_heap(v2.begin(), v2.end());
assert(TinySTL::Test::container_equal(v1, v2));
}
void testIsHeap(){
std::vector<int> v1{ 9, 5, 2, 6, 4, 1, 3, 8, 7 };
std::vector<int> v2{ 9, 5, 2, 6, 4, 1, 3, 8, 7 };
if (!std::is_heap(v1.begin(), v1.end()))
std::make_heap(v1.begin(), v1.end());
if (!TinySTL::is_heap(v2.begin(), v2.end()))
TinySTL::make_heap(v2.begin(), v2.end());
assert(TinySTL::Test::container_equal(v1, v2));
}
void testAllOf(){
std::array<int, 8> foo = { 3, 5, 7, 11, 13, 17, 19, 23 };
assert(TinySTL::all_of(foo.begin(), foo.end(), [](int i){return i % 2; }));
}
void testNoneOf(){
std::array<int, 8> foo = { 1, 2, 4, 8, 16, 32, 64, 128 };
assert(TinySTL::none_of(foo.begin(), foo.end(), [](int i){return i < 0; }));
}
void testAnyOf(){
std::array<int, 7> foo = { 0, 1, -1, 3, -3, 5, -5 };
assert(std::any_of(foo.begin(), foo.end(), [](int i){return i < 0; }));
}
void testForEach(){
std::vector<int> myvector{ 10, 20, 30 };
std::vector<int> temp{ 11, 21, 31 };
TinySTL::for_each(myvector.begin(), myvector.end(), [&myvector](int& i){
++i;
});
assert(TinySTL::Test::container_equal(myvector, temp));
}
void testFind(){
std::vector<int> v{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
assert(TinySTL::find(v.begin(), v.end(), 5) != v.end());
assert(TinySTL::find(v.begin(), v.end(), 10) == v.end());
assert(TinySTL::find_if(v.begin(), v.end(), [](int i){return i < 0; }) == v.end());
assert(TinySTL::find_if_not(v.begin(), v.end(), [](int i){return i < 0; }) != v.end());
}
void testFindEnd(){
int myints[] = { 1, 2, 3, 4, 5, 1, 2, 3, 4, 5 };
std::vector<int> v(myints, myints + 10);
int needle1[] = { 1, 2, 3 };
auto it = TinySTL::find_end(v.begin(), v.end(), needle1, needle1 + 3);
assert(it == v.begin() + 5);
int needle2[] = { 4, 5, 1 };
it = TinySTL::find_end(v.begin(), v.end(), needle2, needle2 + 3, [](int i, int j){return i == j; });
assert(it == v.begin() + 3);
}
void testFindFirstOf(){
int mychars[] = { 'a', 'b', 'c', 'A', 'B', 'C' };
std::vector<char> v(mychars, mychars + 6);
int needle[] = { 'A', 'B', 'C' };
auto it = TinySTL::find_first_of(v.begin(), v.end(), needle, needle + 3);
assert(*it == 'A');
it = TinySTL::find_first_of(v.begin(), v.end(), needle, needle + 3,
[](char ch1, char ch2){return std::tolower(ch1) == std::tolower(ch2); });
assert(*it == 'a');
}
void testAdjacentFind(){
int myints[] = { 5, 20, 5, 30, 30, 20, 10, 10, 20 };
std::vector<int> v(myints, myints + 8);
auto it = TinySTL::adjacent_find(v.begin(), v.end());
assert(*it == 30);
it = TinySTL::adjacent_find(++it, v.end(), [](int i, int j){return i == j; });
assert(*it == 10);
}
void testCount(){
int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 }; // 8 elements
int mycount = TinySTL::count(myints, myints + 8, 10);
assert(mycount == 3);
mycount = TinySTL::count_if(myints, myints + 8, [](int i){return i % 2 == 0; });
assert(mycount == 8);
}
void testMismatch(){
std::vector<int> v;
for (int i = 1; i<6; i++) v.push_back(i * 10); //10 20 30 40 50
int myints[] = { 10, 20, 80, 320, 1024 };
TinySTL::pair<std::vector<int>::iterator, int*> mypair;
mypair = TinySTL::mismatch(v.begin(), v.end(), myints);
assert(*mypair.first == 30 && *mypair.second == 80);
++mypair.first; ++mypair.second;
mypair = TinySTL::mismatch(mypair.first, v.end(), mypair.second, [](int i, int j){return i == j; });
}
void testEqual(){
int myints[] = { 20, 40, 60, 80, 100 };
std::vector<int>v(myints, myints + 5); //20 40 60 80 100
assert(TinySTL::equal(v.begin(), v.end(), myints));
v[3] = 81;
assert(!TinySTL::equal(v.begin(), v.end(), myints, [](int i, int j){return i == j; }));
}
void testIsPermutation(){
std::array<int, 5> foo = { 1, 2, 3, 4, 5 };
std::array<int, 5> bar = { 3, 1, 4, 5, 2 };
assert(TinySTL::is_permutation(foo.begin(), foo.end(), bar.begin()));
}
void testSearch(){
std::vector<int> v;
for (int i = 1; i<10; i++) v.push_back(i * 10);
int needle1[] = { 40, 50, 60, 70 };
auto it = TinySTL::search(v.begin(), v.end(), needle1, needle1 + 4);
assert(it == v.begin() + 3);
int needle2[] = { 20, 30, 50 };
it = std::search(v.begin(), v.end(), needle2, needle2 + 3, [](int i, int j){return i == j; });
assert(it == v.end());
}
void testAdvance(){
TinySTL::vector<int> v;
TinySTL::list<int> l;
TinySTL::binary_search_tree<int> bst;
for (auto i = 0; i != 10; ++i){
v.push_back(i);
l.push_back(i);
bst.insert(i);
}
auto vit = v.begin();
auto lit = l.begin();
auto bit = bst.cbegin();
TinySTL::advance(vit, 5);
TinySTL::advance(lit, 5);
TinySTL::advance(bit, 5);
assert(*vit == 5 && *lit == 5 && *bit == 5);
TinySTL::advance(vit, -5);
TinySTL::advance(lit, -5);
assert(*vit == 0 && *lit == 0);
}
void testSort(){
int arr1[1] = { 0 };
TinySTL::sort(std::begin(arr1), std::end(arr1));
assert(std::is_sorted(std::begin(arr1), std::end(arr1)));
int arr2[2] = { 1, 0 };
TinySTL::sort(std::begin(arr2), std::end(arr2));
assert(std::is_sorted(std::begin(arr2), std::end(arr2)));
int arr3[3] = { 2, 1, 3 };
TinySTL::sort(std::begin(arr3), std::end(arr3));
assert(std::is_sorted(std::begin(arr3), std::end(arr3)));
int arr4[100];
std::random_device rd;
for (auto i = 0; i != 10; ++i){
for (auto& n : arr4){
n = rd() % 65536;
}
TinySTL::sort(std::begin(arr4), std::end(arr4));
assert(std::is_sorted(std::begin(arr4), std::end(arr4)));
}
}
void testGenerate(){
int arr1[100], arr2[100];
auto f = [](int i){ return i; };
for (auto i = 0; i != 100; ++i){
auto func = std::bind(f, i);
TinySTL::generate(std::begin(arr1), std::end(arr1), func);
std::generate(std::begin(arr2), std::end(arr2), func);
}
assert(TinySTL::Test::container_equal(arr1, arr2));
int n1 = 0, n2 = 0;
auto gen1 = [&n1](){return n1++; };
auto gen2 = [&n2](){return n2++; };
int arr3[100], arr4[100];
TinySTL::generate_n(arr3, 100, gen1);
std::generate_n(arr4, 100, gen2);
assert(TinySTL::Test::container_equal(arr3, arr4));
}
void testDistance(){
TinySTL::list<int> l(10, 0);
TinySTL::vector<int> v(10, 0);
auto lit = l.begin();
TinySTL::advance(lit, 5);
auto vit = v.begin();
TinySTL::advance(vit, 5);
assert(TinySTL::distance(l.begin(), lit) == 5);
assert(TinySTL::distance(v.begin(), vit) == 5);
}
void testCopy(){
char arr1[] = "hello", res1[6] = { 0 };
TinySTL::copy(std::begin(arr1), std::end(arr1), res1);
assert(TinySTL::Test::container_equal(arr1, res1));
wchar_t arr2[] = L"hello", res2[6] = { 0 };
TinySTL::copy(std::begin(arr2), std::end(arr2), res2);
assert(TinySTL::Test::container_equal(arr2, res2));
int arr3[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, res3[10] = { 0 };
TinySTL::copy(std::begin(arr3), std::end(arr3), res3);
assert(TinySTL::Test::container_equal(arr3, res3));
std::string arr4[3] = { "1", "2", "3" }, res4[3];
TinySTL::copy(std::begin(arr4), std::end(arr4), res4);
assert(TinySTL::Test::container_equal(arr4, res4));
}
void testAllCases(){
testFill();
testFillN();
testMinMax();
testHeapAlgorithm();
testIsHeap();
testAllOf();
testNoneOf();
testAnyOf();
testForEach();
testFind();
testFindEnd();
testFindFirstOf();
testAdjacentFind();
testCount();
testMismatch();
testEqual();
testIsPermutation();
testSearch();
testAdvance();
testSort();
testGenerate();
testDistance();
testCopy();
}
}
}<file_sep>/TinySTL/Test/TrieTreeTest.h
#ifndef _TRIE_TREE_TEST_H_
#define _TRIE_TREE_TEST_H_
#include "TestUtil.h"
#include "../TrieTree.h"
#include <cassert>
namespace TinySTL{
namespace TrieTreeTest{
void testCase1();
void testCase2();
void testCase3();
void testAllCases();
}
}
#endif<file_sep>/TinySTL/Test/UniquePtrTest.h
#ifndef _UNIQUEPTR_TEST_H_
#define _UNIQUEPTR_TEST_H_
#include "TestUtil.h"
#include "../Memory.h"
#include <cassert>
namespace TinySTL{
namespace UniquePtrTest{
void testCase1();
void testCase2();
void testCase3();
void testAllCases();
}
}
#endif<file_sep>/TinySTL/Test/AVLTreeTest.h
#ifndef _AVL_TREE_TEST_H_
#define _AVL_TREE_TEST_H_
#include "TestUtil.h"
#include "../AVLTree.h"
#include <algorithm>
#include <cassert>
#include <random>
#include <string>
#include <vector>
namespace TinySTL{
namespace AVLTreeTest{
template<class T>
using tsAVL = TinySTL::avl_tree < T > ;
void testCase1();
void testCase2();
void testCase3();
void testCase4();
void testAllCases();
}
}
#endif<file_sep>/TinySTL/Test/UFSetTest.cpp
#include "UFSetTest.h"
namespace TinySTL{
namespace UFSetTest{
void testCase1(){
uf_set<10> uf;
uf.Union(0, 1);
uf.Union(2, 3);
uf.Union(3, 1);
assert(uf.Find(0) == uf.Find(2));
}
void testAllCases(){
testCase1();
}
}
}<file_sep>/TinySTL/Test/Unordered_setTest.h
#ifndef _UNORDERED_SET_TEST_H_
#define _UNORDERED_SET_TEST_H_
#include "TestUtil.h"
#include "../Unordered_set.h"
#include <unordered_set>
#include <algorithm>
#include <cassert>
#include <random>
#include <string>
#include <vector>
namespace TinySTL{
namespace Unordered_setTest{
template<class T>
using stdUst = std::unordered_set < T > ;
template<class T>
using tsUst = TinySTL::Unordered_set < T > ;
void testCase1();
void testCase2();
void testCase3();
void testCase4();
void testCase5();
void testAllCases();
}
}
#endif<file_sep>/TinySTL/Test/PriorityQueueTest.h
#ifndef _PRIORITY_QUEUE_TEST_H_
#define _PRIORITY_QUEUE_TEST_H_
#include "TestUtil.h"
#include "../Queue.h"
#include <queue>
#include <algorithm>
#include <cassert>
#include <string>
namespace TinySTL{
namespace PriorityQueueTest{
template<class T>
using stdPQ = std::priority_queue < T > ;
template<class T>
using tsPQ = TinySTL::priority_queue < T > ;
void testCase1();
void testCase2();
void testCase3();
void testCase4();
void testCase5();
void testAllCases();
}
}
#endif<file_sep>/TinySTL/Test/Unordered_setTest.cpp
#include "Unordered_setTest.h"
namespace TinySTL{
namespace Unordered_setTest{
template<class Container1, class Container2>
bool container_equal(Container1& con1, Container2& con2){
std::vector<typename Container1::value_type> vec1, vec2;
for (auto& item : con1){
vec1.push_back(item);
}
for (auto& item : con2){
vec2.push_back(item);
}
std::sort(vec1.begin(), vec1.end());
std::sort(vec2.begin(), vec2.end());
return vec1 == vec2;
}
void testCase1(){
stdUst<int> ust1(10);
tsUst<int> ust2(10);
assert(container_equal(ust1, ust2));
int arr[] = { 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
stdUst<int> ust3(std::begin(arr), std::end(arr));
tsUst<int> ust4(std::begin(arr), std::end(arr));
assert(container_equal(ust3, ust4));
auto ust5(ust3);
auto ust6(ust4);
assert(container_equal(ust5, ust6));
auto ust7 = ust3;
auto ust8 = ust4;
assert(container_equal(ust7, ust8));
}
void testCase2(){
tsUst<int> ust1(10);
assert(ust1.empty());
assert(ust1.size() == 0);
int arr[] = { 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
tsUst<int> ust2(std::begin(arr), std::end(arr));
assert(!ust2.empty());
assert(ust2.size() == 10);
}
void testCase3(){
tsUst<std::string> ust1(10);
stdUst<std::string> ust2(10);
std::random_device rd;
for (auto i = 0; i != 100; ++i){
auto n = std::to_string(rd() % 65536);
ust1.insert(n);
ust2.insert(n);
}
assert(container_equal(ust1, ust2));
tsUst<int> ust3(10);
stdUst<int> ust4(10);
std::vector<int> v(200);
std::generate(v.begin(), v.end(), [&rd](){return rd() % 65536; });
ust3.insert(v.begin(), v.end());
ust4.insert(v.begin(), v.end());
assert(container_equal(ust3, ust4));
}
void testCase4(){
int arr[] = { 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
stdUst<int> ust1(std::begin(arr), std::end(arr));
tsUst<int> ust2(std::begin(arr), std::end(arr));
ust1.erase(9);
auto n = ust2.erase(9);
assert(n == 1);
ust1.erase(7);
auto it = ust2.find(7);
it = ust2.erase(it);
assert(it != ust2.end());
assert(container_equal(ust1, ust2));
}
void testCase5(){
int arr[] = { 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 7, 8, 9 };
tsUst<int> ust(std::begin(arr), std::end(arr));
assert(ust.find(0) != ust.end());
assert(ust.count(10) == 0);
}
void testAllCases(){
testCase1();
testCase2();
testCase3();
testCase4();
testCase5();
}
}
}<file_sep>/TinySTL/Detail/CircularBuffer.impl.h
#ifndef _CIRCULAR_BUFFER_IMPL_H_
#define _CIRCULAR_BUFFER_IMPL_H_
namespace TinySTL{
namespace Detail{
template<class T, size_t N, class Alloc>
int cb_iter<T, N, Alloc>::prevIndex(int index){
--index;
index = (index == -1 ? index + N : index);
return index;
}
template<class T, size_t N, class Alloc>
bool cb_iter<T, N, Alloc>::operator == (const cb_iter& it)const{
return (container_ == it.container_) &&
(ptr_ == it.ptr_) && (index_ == it.index_);
}
template<class T, size_t N, class Alloc>
bool cb_iter<T, N, Alloc>::operator != (const cb_iter& it)const{
return !((*this) == it);
}
template<class T, size_t N, class Alloc>
cb_iter<T, N, Alloc>& cb_iter<T, N, Alloc>::operator ++(){
setIndex_(nextIndex(index_));
setPtr_(container_->start_ + index_);
return *this;
}
template<class T, size_t N, class Alloc>
cb_iter<T, N, Alloc> cb_iter<T, N, Alloc>::operator ++(int){
cb_iter temp(*this);
++(*this);
return temp;
}
template<class T, size_t N, class Alloc>
cb_iter<T, N, Alloc>& cb_iter<T, N, Alloc>::operator --(){
setIndex_(prevIndex(index_));
setPtr_(container_->start_ + index_);
return *this;
}
template<class T, size_t N, class Alloc>
cb_iter<T, N, Alloc> cb_iter<T, N, Alloc>::operator --(int){
cb_iter temp(*this);
--(*this);
return temp;
}
template<class T, size_t N, class Alloc>
cb_iter<T, N, Alloc>& cb_iter<T, N, Alloc>::operator = (const cb_iter& cit){
if (this != &cit){
ptr_ = cit.ptr_;
index_ = cit.index_;
container_ = cit.container_;
}
return *this;
}
template<class T, size_t N, class Alloc>
cb_iter<T, N, Alloc> operator +(const cb_iter<T, N, Alloc>& cit, std::ptrdiff_t i){
int real_i = i % (std::ptrdiff_t)N;//assume i >= 0
if (real_i < 0)
real_i += 5;
cb_iter<T, N, Alloc> res = cit;
res.setIndex_(res.index_ + real_i);
res.setPtr_(res.ptr_ + res.index_);
return res;
}
template<class T, size_t N, class Alloc>
cb_iter<T, N, Alloc> operator -(const cb_iter<T, N, Alloc>& cit, std::ptrdiff_t i){
cb_iter<T, N, Alloc> res = cit;
return (res + (-i));
}
}//end of Detail namespace
//**********构造,复制,析构相关*****************
template<class T, size_t N, class Alloc>
circular_buffer<T, N, Alloc>::~circular_buffer(){
clear();
dataAllocator::deallocate(start_, size_);
}
template<class T, size_t N, class Alloc>
circular_buffer<T, N, Alloc>::circular_buffer(const int& n, const value_type& val = value_type()){
assert(n != 0);
allocateAndFillN(n, val);
}
template<class T, size_t N, class Alloc>
template<class InputIterator>
circular_buffer<T, N, Alloc>::circular_buffer(InputIterator first, InputIterator last){
//bug fix
//2015.01.05
assert(first != last);
allocateAndCopy(first, last);
}
template<class T, size_t N, class Alloc>
circular_buffer<T, N, Alloc>::circular_buffer(const circular_buffer<T, N, Alloc>& cb){
clone(cb);
}
template<class T, size_t N, class Alloc>
circular_buffer<T, N, Alloc>::circular_buffer(circular_buffer<T, N, Alloc>&& cb){
copyAllMembers(cb);
zeroCircular(cb);
}
template<class T, size_t N, class Alloc>
circular_buffer<T, N, Alloc>& circular_buffer<T, N, Alloc>::operator = (const circular_buffer<T, N, Alloc>& cb){
if (this != &cb){
clone(cb);
}
return *this;
}
template<class T, size_t N, class Alloc>
circular_buffer<T, N, Alloc>& circular_buffer<T, N, Alloc>::operator = (circular_buffer<T, N, Alloc>&& cb){
if (*this != cb){
copyAllMembers(cb);
zeroCircular(cb);
}
return *this;
}
//************插入,删除相关***********************
template<class T, size_t N, class Alloc>
void circular_buffer<T, N, Alloc>::push_back(const T& val){
if (full()){
indexOfTail = nextIndex(indexOfTail);
dataAllocator::construct(start_ + indexOfTail, val);
indexOfHead = nextIndex(indexOfHead);
}
else{
indexOfTail = nextIndex(indexOfTail);
dataAllocator::construct(start_ + indexOfTail, val);
++size_;
}
}
template<class T, size_t N, class Alloc>
void circular_buffer<T, N, Alloc>::pop_front(){
if (empty())
throw;
dataAllocator::destroy(start_ + indexOfHead);
indexOfHead = nextIndex(indexOfHead);
--size_;
}
template<class T, size_t N, class Alloc>
std::ostream& operator <<(std::ostream& os, circular_buffer<T, N, Alloc>& cb){
circular_buffer<T, N, Alloc>::size_type size = cb.size();
if (!cb.empty()){
os << "(";
for (auto it = cb.first(); it != cb.last() && size != 0; ++it, --size){
os << *it << ", ";
}
os << *(cb.last()) << ")";
}
return os;
}
template<class T, size_t N, class Alloc>
void circular_buffer<T, N, Alloc>::clear(){
for (; !empty(); indexOfHead = nextIndex(indexOfHead), --size_){
dataAllocator::destroy(start_ + indexOfHead);
}
indexOfHead = indexOfTail = 0;
}
template<class T, size_t N, class Alloc>
bool circular_buffer<T, N, Alloc>::operator == (circular_buffer& cb){
auto it1 = first(), it2 = cb.first();
for (; it1 != last() && it2 != cb.last(); ++it1, ++it2){
if (*it1 != *it2) return false;
}
return (it1 == last()) && (it2 == cb.last()) && (*(last()) == *(cb.last()));
}
template<class T, size_t N, class Alloc>
bool circular_buffer<T, N, Alloc>::operator != (circular_buffer& cb){
return !(*this == cb);
}
template<class T, size_t N, class Alloc>
void circular_buffer<T, N, Alloc>::allocateAndFillN(const int& n, const value_type& val){//only for ctor
start_ = dataAllocator::allocate(N);
finish_ = start_ + N;
indexOfHead = 0;
if (N <= n){
finish_ = TinySTL::uninitialized_fill_n(start_, N, val);
indexOfTail = N - 1;
size_ = N;
}
else{//N > n
finish_ = TinySTL::uninitialized_fill_n(start_, n, val);
finish_ = TinySTL::uninitialized_fill_n(finish_, N - n, value_type());
indexOfTail = n - 1;
size_ = n;
}
}
template<class T, size_t N, class Alloc>
template<class InputIterator>
void circular_buffer<T, N, Alloc>::allocateAndCopy(InputIterator first, InputIterator last){//only for ctor
int n = last - first;
start_ = dataAllocator::allocate(N);
indexOfHead = 0;
if (N <= n){
finish_ = TinySTL::uninitialized_copy(first, first + N, start_);
indexOfTail = N - 1;
size_ = N;
}
else{//N > n
finish_ = TinySTL::uninitialized_copy(first, last, start_);
finish_ = TinySTL::uninitialized_fill_n(finish_, N - n, value_type());
indexOfTail = n - 1;
size_ = n;
}
}
template<class T, size_t N, class Alloc>
void circular_buffer<T, N, Alloc>::copyAllMembers(const circular_buffer& cb){
start_ = cb.start_;
finish_ = cb.finish_;
indexOfHead = cb.indexOfHead;
indexOfTail = cb.indexOfTail;
size_ = cb.size_;
}
template<class T, size_t N, class Alloc>
void circular_buffer<T, N, Alloc>::zeroCircular(circular_buffer& cb){
cb.start_ = cb.finish_ = 0;
cb.indexOfHead = cb.indexOfTail = cb.size_ = 0;
}
template<class T, size_t N, class Alloc>
void circular_buffer<T, N, Alloc>::clone(const circular_buffer& cb){
start_ = dataAllocator::allocate(N);
finish_ = start_ + N;
size_ = N;
indexOfHead = cb.indexOfHead;
indexOfTail = cb.indexOfTail;
TinySTL::uninitialized_copy(cb.start_, cb.finish_, start_);
}
}
#endif<file_sep>/TinySTL/Test/GraphTest.cpp
#include "GraphTest.h"
#include <sstream>
#include <fstream>
namespace TinySTL{
namespace GraphTest{
void testCase1(){
dGraph<int, int> g;
assert(g.empty());
assert(g.size() == 0);
g.add_node(g.make_node(0, 0), g.empty_node_set());
assert(!g.empty());
assert(g.size() == 1);
assert(g.is_contained(0));
auto node = g.get_node(0);
assert(node.first == 0 && node.second == 0);
}
void testCase2(){
dGraph<int, int> g;
dGraph<int, int>::nodes_set_type set1, set2, set3;
set1.push_back(g.make_node(1, 11));
set1.push_back(g.make_node(2, 22));
set1.push_back(g.make_node(3, 33));
g.add_node(g.make_node(0, 0), set1);
set2.push_back(g.make_node(5, 55));
set2.push_back(g.make_node(6, 66));
set2.push_back(g.make_node(7, 77));
g.add_node(g.make_node(1, 11), set2);
set3.push_back(g.make_node(12, 1212));
set3.push_back(g.make_node(13, 1313));
set3.push_back(g.make_node(14, 1414));
g.add_node(7, set3);
g.make_edge(12, 2);
g.make_edge(12, 3);
g.make_edge(12, 0);
std::ostringstream os;
os << g.to_string();
std::string res(R"([14,1414]:[nil]
|
[13,1313]:[nil]
|
[12,1212]:[0,0]->[3,33]->[2,22]->[nil]
|
[7,77]:[14,1414]->[13,1313]->[12,1212]->[nil]
|
[6,66]:[nil]
|
[5,55]:[nil]
|
[3,33]:[nil]
|
[2,22]:[nil]
|
[1,11]:[7,77]->[6,66]->[5,55]->[nil]
|
[0,0]:[3,33]->[2,22]->[1,11]->[nil]
|
[nil]
)");
assert(os.str() == res);
std::ostringstream os1, os2;
auto func1 = [&os1](const dGraph<int, int>::node_type& node){
os1 << "[" << node.first << "," << node.second << "]";
};
auto func2 = [&os2](const dGraph<int, int>::node_type& node){
os2 << "[" << node.first << "," << node.second << "]";
};
res = R"([1,11][7,77][14,1414][13,1313][12,1212][0,0][3,33][2,22][6,66][5,55])";
g.DFS(1, func1);
assert(os1.str() == res);
res = R"([1,11][7,77][6,66][5,55][14,1414][13,1313][12,1212][0,0][3,33][2,22])";
g.BFS(1, func2);
assert(os2.str() == res);
std::ostringstream os3;
g.delete_node(dGraph<int, int>::node_type(7, 77));
os3 << g.to_string();
res = R"([14,1414]:[nil]
|
[13,1313]:[nil]
|
[12,1212]:[0,0]->[3,33]->[2,22]->[nil]
|
[6,66]:[nil]
|
[5,55]:[nil]
|
[3,33]:[nil]
|
[2,22]:[nil]
|
[1,11]:[6,66]->[5,55]->[nil]
|
[0,0]:[3,33]->[2,22]->[1,11]->[nil]
|
[nil]
)";
assert(os3.str() == res);
}
void testCase3(){
dGraph<int, int> g;
dGraph<int, int>::nodes_set_type set1, set2;
set1.push_back(g.make_node(1, 11));
set1.push_back(g.make_node(2, 22));
set1.push_back(g.make_node(3, 33));
g.add_node(g.make_node(0, 0), set1);
auto nodes = g.adjacent_nodes(0);
std::reverse(set1.begin(), set1.end());
assert(TinySTL::Test::container_equal(nodes, set1));
for (auto it = g.begin(0); it != g.end(0); ++it){
set2.push_back(*it);
}
assert(TinySTL::Test::container_equal(nodes, set2));
}
void testCase4(){
dGraph<int, int> g;
dGraph<int, int>::nodes_set_type set;
for (auto i = 0; i != 10; ++i){
auto node = g.make_node(i, i);
g.add_node(node, g.empty_node_set());
set.push_back(node);
}
std::reverse(set.begin(), set.end());
auto it2 = set.begin();
for (auto it1 = g.begin(); it1 != g.end() && it2 != set.end(); ++it1, ++it2){
assert(*it1 == *it2);
}
}
void testAllCases(){
testCase1();
testCase2();
testCase3();
testCase4();
}
}
}<file_sep>/TinySTL/Test/QueueTest.h
#ifndef _QUEUE_TEST_H_
#define _QUEUE_TEST_H_
#include "TestUtil.h"
#include "../Queue.h"
#include <queue>
#include <cassert>
#include <string>
namespace TinySTL{
namespace QueueTest{
template<class T>
using stdQ = std::queue < T > ;
template<class T>
using tsQ = TinySTL::queue < T > ;
void testCase1();
void testCase2();
void testCase3();
void testCase4();
void testCase5();
void testAllCases();
}
}
#endif<file_sep>/TinySTL/Test/BinarySearchTreeTest.cpp
#include "BinarySearchTreeTest.h"
namespace TinySTL{
namespace BinarySearchTreeTest{
template<class Container1, class Container2>
bool container_equal(const Container1& con1, const Container2& con2){
auto first1 = con1.cbegin(), last1 = con1.cend();
auto first2 = con2.cbegin(), last2 = con2.cend();
for (; first1 != last1 && first2 != last2; ++first1, ++first2){
if (*first1 != *first2)
return false;
}
return (first1 == last1 && first2 == last2);
}
void testCase1(){
tsBst<std::string> bst;
assert(bst.empty());
assert(bst.size() == 0);
bst.insert("1");
assert(!bst.empty());
assert(bst.size() == 1);
}
void testCase2(){
tsBst<int> bst;
for (auto i = 0; i != 100; ++i)
bst.insert(i);
assert(bst.height() == 100);
}
void testCase3(){
tsBst<int> bst;
std::vector<int> v;
std::random_device rd;
for (auto i = 0; i != 100; ++i){
auto r = rd() % 65536;
bst.insert(r);
v.push_back(r);
}
std::sort(v.begin(), v.end());
v.erase(std::unique(v.begin(), v.end()), v.end());
assert(container_equal(bst, v));
for (auto i = 0; i != 20; ++i){
bst.erase(*bst.cbegin());
v.erase(v.begin());
assert(container_equal(bst, v));
}
tsBst<int> bst1;
bst1.insert(v.begin(), v.end());
assert(container_equal(bst1, v));
}
void testCase4(){
tsBst<int> bst;
for (auto i = 0; i != 10; ++i)
bst.insert(i);
assert(*bst.find(5) == 5);
assert(*bst.find_min() == 0);
assert(*bst.find_max() == 9);
}
void testAllCases(){
testCase1();
testCase2();
testCase3();
testCase4();
}
}
}<file_sep>/TinySTL/Detail/Bitmap.impl.h
#ifndef _BITMAP_IMPL_H_
#define _BITMAP_IMPL_H_
namespace TinySTL{
template<size_t N>
void bitmap<N>::allocateAndFillN(size_t n, uint8_t val){
start_ = dataAllocator::allocate(n);
finish_ = uninitialized_fill_n(start_, n, val);
}
template<size_t N>
void bitmap<N>::THROW(size_t n)const{
if (!(0 <= n && n < size()))
throw std::out_of_range("Out Of Range");
}
template<size_t N>
void bitmap<N>::setNthInInt8(uint8_t& i, size_t nth, bool newVal){//nth从0开始
uint8_t temp = getMask(i, nth);
if ((bool)temp == newVal){
return;
}
else{
if (temp){//nth位为1
temp = ~temp;
i = i & temp;
}
else{//nth位为0
i = i | (1 << nth);
}
}
}
template<size_t N>
size_t bitmap<N>::roundUp8(size_t bytes){
return ((bytes + EAlign::ALIGN - 1) & ~(EAlign::ALIGN - 1));
}
template<size_t N>
bitmap<N>& bitmap<N>::set(){
uninitialized_fill_n(start_, sizeOfUINT8_, ~0);
return *this;
}
template<size_t N>
bitmap<N>& bitmap<N>::reset(){
uninitialized_fill_n(start_, sizeOfUINT8_, 0);
return *this;
}
template<size_t N>
bool bitmap<N>::test(size_t pos) const{
THROW(pos);
const auto nth = getNth(pos);
const auto mth = getMth(pos);
uint8_t *ptr = start_ + nth;
uint8_t temp = getMask(*ptr, mth);
if (temp)
return true;
return false;
}
template<size_t N>
bitmap<N>::bitmap() :size_(roundUp8(N)), sizeOfUINT8_(roundUp8(N) / 8){
allocateAndFillN(sizeOfUINT8_, 0);
}
template<size_t N>
bitmap<N>& bitmap<N>::set(size_t pos, bool val){
THROW(pos);
const auto nth = getNth(pos);
const auto mth = getMth(pos);
uint8_t *ptr = start_ + nth;//get the nth uint8_t
setNthInInt8(*ptr, mth, val);
return *this;
}
template<size_t N>
bitmap<N>& bitmap<N>::reset(size_t pos){
set(pos, false);
return *this;
}
template<size_t N>
bitmap<N>& bitmap<N>::flip(){
uint8_t *ptr = start_;
for (; ptr != finish_; ++ptr){
uint8_t n = *ptr;
*ptr = ~n;
}
return *this;
}
template<size_t N>
bitmap<N>& bitmap<N>::flip(size_t pos){
THROW(pos);
const auto nth = getNth(pos);
const auto mth = getMth(pos);
uint8_t *ptr = start_ + nth;
uint8_t temp = getMask(*ptr, mth);
if (temp)
setNthInInt8(*ptr, mth, false);
else
setNthInInt8(*ptr, mth, true);
return *this;
}
template<size_t N>
size_t bitmap<N>::count() const{
uint8_t *ptr = start_;
size_t sum = 0;
for (; ptr != finish_; ++ptr){
for (int i = 0; i != 8; ++i){
uint8_t t = getMask(*ptr, i);
if (t){
++sum;
}
}
}
return sum;
}
template<size_t N>
bool bitmap<N>::any() const{
uint8_t *ptr = start_;
for (; ptr != finish_; ++ptr){
uint8_t n = *ptr;
if (n != 0)
return true;
}
return false;
}
template<size_t N>
bool bitmap<N>::all() const{
uint8_t *ptr = start_;
for (; ptr != finish_; ++ptr){
uint8_t n = *ptr;
if (n != (uint8_t)~0)
return false;
}
return true;
}
template<size_t N>
bool bitmap<N>::none() const{
return !any();
}
template<size_t N>
string bitmap<N>::to_string() const{
string str;
uint8_t *ptr = start_;
for (; ptr != finish_; ++ptr){
uint8_t n = *ptr;
for (int i = 0; i != 8; ++i){
uint8_t t = getMask(n, i);
if (t) str += "1";
else str += "0";
}
}
return str;
}
template<size_t N>
std::ostream& operator <<(std::ostream& os, const bitmap<N>& bm){
os << bm.to_string();
return os;
}
}
#endif<file_sep>/TinySTL/Test/BitmapTest.cpp
#include "BitmapTest.h"
namespace TinySTL{
namespace BitmapTest{
void testCase1(){
bitmap<1> bt1;
assert(bt1.size() == 8);
bitmap<7> bt2;
assert(bt2.size() == 8);
bitmap<127> bt3;
assert(bt3.size() == 128);
}
void testCase2(){
bitmap<8> bt1, bt2;
bt1.set();
assert(bt1.to_string() == "11111111");
bt1.reset();
assert(bt1.to_string() == "00000000");
bt2.set(0); bt2.set(2); bt2.set(4);
assert(bt2.to_string() == "10101000");
bt2.reset(0); bt2.reset(2); bt2.reset(4);
assert(bt2.to_string() == "00000000");
}
void testCase3(){
bitmap<8> bt;
bt.flip();
assert(bt.to_string() == "11111111");
bt.flip(0);
assert(bt.to_string() == "01111111");
}
void testCase4(){
bitmap<8> bt;
bt.set();
assert(bt.count() == 8);
bt.flip();
assert(bt.count() == 0);
bt.set(0);
assert(bt.count() == 1);
}
void testCase5(){
bitmap<8> bt;
assert(!bt.test(0));
bt.set(0);
assert(bt.test(0));
}
void testCase6(){
bitmap<8> bt;
assert(!bt.any());
assert(bt.none());
assert(!bt.all());
bt.set(0);
assert(bt.any());
assert(!bt.none());
assert(!bt.all());
bt.set();
assert(bt.any());
assert(!bt.none());
assert(bt.all());
bt.reset();
assert(!bt.any());
assert(bt.none());
assert(!bt.all());
}
void testCase7(){
bitmap<8> bt;
bt.set(0); bt.set(2); bt.set(4); bt.set(6);
assert(bt.to_string() == TinySTL::string("10101010"));
}
void testAllCases(){
testCase1();
testCase2();
testCase3();
testCase4();
testCase5();
testCase6();
testCase7();
}
}
}<file_sep>/TinySTL/Test/UniquePtrTest.cpp
#include "UniquePtrTest.h"
#include "../String.h"
namespace {
template<class T>
struct Del{
void operator()(T *p){ delete p; }
};
}
namespace TinySTL{
namespace UniquePtrTest{
void testCase1(){
unique_ptr<int> up1;
assert(up1 == nullptr);
unique_ptr<int> up2(new int(5));
assert(up2 != nullptr);
assert(*up2 == 5);
unique_ptr<string, Del<string>> up3(new string("zouxiaohang"), Del<string>());
assert(up3 != nullptr);
assert(*up3 == "zouxiaohang");
auto up4(std::move(up2));
assert(*up4 == 5);
assert(up2 == nullptr);
unique_ptr<string, Del<string>> up5;
up5 = std::move(up3);
assert(*up5 == "zouxiaohang");
assert(up3 == nullptr);
auto up6 = make_unique<string>(6, 'z');
assert(*up6 == "zzzzzz");
}
void testCase2(){
auto up = make_unique<string>(10, '0');
up->append("111");
assert(*up == "0000000000111");
up.release();
assert(up == nullptr);
up.reset(new string("hello"));
assert(*up == "hello");
}
void testCase3(){
auto up1 = make_unique<string>(2, '0');
auto up2 = make_unique<string>(2, '1');
up1.swap(up2);
assert(*up1 == "11" && *up2 == "00");
swap(up1, up2);
assert(*up1 == "00" && *up2 == "11");
}
void testAllCases(){
testCase1();
testCase2();
testCase3();
}
}
}<file_sep>/TinySTL/Graph.h
#ifndef _GRAPH_H_
#define _GRAPH_H_
#include "Iterator.h"
#include "List.h"
#include "String.h"
#include "Unordered_set.h"
#include "Utility.h"
#include "Vector.h"
#include <functional>
#include <iomanip>
#include <sstream>
namespace TinySTL{
namespace Detail{
template<class Index, class Value, class EqualFunc>
class inner_iterator;
template<class Index, class Value, class EqualFunc>
class outter_iterator;
template<class Index, class Value, class EqualFunc = equal_to<Index>>
class graph{//base class
public:
friend class inner_iterator < Index, Value, EqualFunc >;
friend class outter_iterator < Index, Value, EqualFunc > ;
public:
typedef Index index_type;
typedef Value value_type;
typedef EqualFunc equal_func_type;
typedef pair<Index, Value> node_type;
typedef vector<node_type> nodes_set_type;
typedef std::function<void(node_type&)> visiter_func_type;
typedef outter_iterator<Index, Value, EqualFunc> iterator;
typedef inner_iterator<Index, Value, EqualFunc> inner_iterator;
public:
graph() :size_(0){};
virtual ~graph(){};
//node can be not in the graph
virtual void add_node(const node_type& item, const nodes_set_type& nodes) = 0;
//node of the index must in the graph
virtual void add_node(const Index& index, const nodes_set_type& nodes) = 0;
virtual void make_edge(const Index& index1, const Index& index2) = 0;
virtual void delete_node(const node_type& item) = 0;
virtual void delete_node(const Index& index) = 0;
void DFS(const Index& index, visiter_func_type func);
void BFS(const Index& index, visiter_func_type func);
node_type make_node(const Index& index, const Value& val);
const node_type& get_node(const Index& index);
bool is_contained(const Index& index);
inline static nodes_set_type empty_node_set();
nodes_set_type adjacent_nodes(const Index& index);
nodes_set_type adjacent_nodes(const node_type& n);
bool empty()const;
size_t size()const;
inner_iterator begin(const Index& index);
inner_iterator end(const Index& index);
iterator begin();
iterator end();
equal_func_type get_equal_func()const;
string to_string();
protected:
void _DFS(node_type& node, visiter_func_type func, Unordered_set<Index, std::hash<Index>, EqualFunc>& visited);
void _BFS(node_type& node, visiter_func_type func, Unordered_set<Index, std::hash<Index>, EqualFunc>& visited);
protected:
list<pair<node_type, list<node_type>>> nodes_;
equal_func_type equal_func;
size_t size_;
};
template<class Index, class Value, class EqualFunc = equal_to<Index>>
class inner_iterator :public iterator<bidirectional_iterator_tag,
typename graph<Index, Value, EqualFunc>::node_type>{
public:
friend class graph < Index, Value, EqualFunc > ;
typedef graph<Index, Value, EqualFunc>* cntrPtr;
typedef graph<Index, Value, EqualFunc> graph_type;
typedef typename list<typename graph_type::node_type>::iterator inner_it_type;
public:
explicit inner_iterator(cntrPtr c = nullptr, inner_it_type iit = inner_it_type())
:container_(c), inner_it_(iit){}
inner_iterator& operator ++();
const inner_iterator operator ++(int);
typename graph_type::node_type& operator*(){ return *inner_it_; }
typename graph_type::node_type* operator ->(){ return &(operator*()); }
private:
cntrPtr container_;
inner_it_type inner_it_;
public:
template<class Index, class Value, class EqualFunc>
friend bool operator ==(const inner_iterator<Index, Value, EqualFunc>& lhs,
const inner_iterator<Index, Value, EqualFunc>& rhs);
template<class Index, class Value, class EqualFunc>
friend bool operator !=(const inner_iterator<Index, Value, EqualFunc>& lhs,
const inner_iterator<Index, Value, EqualFunc>& rhs);
};
template<class Index, class Value, class EqualFunc = equal_to<Index>>
class outter_iterator :public iterator<bidirectional_iterator_tag,
typename graph<Index, Value, EqualFunc>::node_type>{
public:
friend class graph < Index, Value, EqualFunc >;
typedef graph<Index, Value, EqualFunc>* cntrPtr;
typedef graph<Index, Value, EqualFunc> graph_type;
typedef typename list<pair<typename graph_type::node_type, list<typename graph_type::node_type>>>::iterator outter_it_type;
private:
cntrPtr container_;
outter_it_type outter_it_;
public:
explicit outter_iterator(cntrPtr c = nullptr, outter_it_type oit = outter_it_type())
:container_(c), outter_it_(oit){}
outter_iterator& operator ++();
const outter_iterator operator ++(int);
typename graph_type::node_type& operator*(){ return outter_it_->first; }
typename graph_type::node_type* operator ->(){ return &(operator*()); }
public:
template<class Index, class Value, class EqualFunc>
friend bool operator ==(const outter_iterator<Index, Value, EqualFunc>& lhs,
const outter_iterator<Index, Value, EqualFunc>& rhs);
template<class Index, class Value, class EqualFunc>
friend bool operator !=(const outter_iterator<Index, Value, EqualFunc>& lhs,
const outter_iterator<Index, Value, EqualFunc>& rhs);
};
}//end of namespace Detail
//directed graph
template<class Index, class Value, class EqualFunc = equal_to<Index>>
class directed_graph :public Detail::graph < Index, Value, EqualFunc > {
public:
directed_graph();
~directed_graph(){}
//node n -> every node_type in the nodes set
void add_node(const node_type& n, const nodes_set_type& nodes) override final;
void add_node(const Index& index, const nodes_set_type& nodes) override final;
//node index1 -> node index2
void make_edge(const Index& index1, const Index& index2) override final;
void delete_node(const node_type& item) override final;
void delete_node(const Index& index) override final;
private:
void add_node_helper(const Index& index, const nodes_set_type& nodes);
};
}
#include "Detail\Graph.impl.h"
#endif<file_sep>/TinySTL/Test/SuffixArrayTest.cpp
#include "SuffixArrayTest.h"
namespace TinySTL{
namespace SuffixArrayTest{
void testCase(){
//char arr[] = { 'a', 'a', 'b', 'a', 'a', 'a', 'a', 'b' };
std::string str("aabaaaab");
//TinySTL::suffix_array sa(arr, 8);
TinySTL::suffix_array sa(str.data(), str.size());
auto sa1 = sa.suffixArray();
auto sa2 = TinySTL::suffix_array::array_type{3, 4, 5, 0, 6, 1, 7, 2};
assert(TinySTL::Test::container_equal(sa1, sa2));
auto ra1 = sa.rankArray();
auto ra2 = TinySTL::suffix_array::array_type{ 3, 5, 7, 0, 1, 2, 4, 6 };
assert(TinySTL::Test::container_equal(ra1, ra2));
auto ha1 = sa.heightArray();
auto ha2 = TinySTL::suffix_array::array_type{ 3, 2, 3, 1, 2, 0, 1 };
assert(TinySTL::Test::container_equal(ha1, ha2));
}
void testAllCases(){
testCase();
}
}
}<file_sep>/TinySTL/SuffixArray.h
#ifndef _SUFFIX_ARRAY_H_
#define _SUFFIX_ARRAY_H_
#include <vector>
namespace TinySTL{
class suffix_array{
public:
using array_type = std::vector < int > ;
private:
array_type _suffix_array;
array_type _height_array;
array_type _rank_array;
public:
template<class InputIterator>
//arr - 源数组
//len - 源数组长度
//max_len - max_len代表字符串arr中字符的取值范围,是基数排序的一个参数,原序列都是字母所以可以直接取256
suffix_array(const InputIterator arr, size_t len, size_t max_len = 256){
if (max_len > 256)
throw std::exception("out of the range");
calSuffix(arr, len, max_len);
calRank();
calHeight(arr, len);
}
array_type suffixArray()const{ return _suffix_array; }
array_type heightArray()const{ return _height_array; }
array_type rankArray()const{ return _rank_array; }
private:
template<class InputIteraotr>
bool cmp(const InputIteraotr arr, size_t a, size_t b, size_t l);
void calRank(){
_rank_array.resize(_suffix_array.size());
for (auto i = 0; i != _suffix_array.size(); ++i){
_rank_array[_suffix_array[i]] = i;
}
}
template<class InputIterator>
void calSuffix(const InputIterator arr, size_t len, size_t max_len);
template<class InputIteraotr>
void calHeight(const InputIteraotr arr, size_t len);
};
template<class InputIteraotr>
bool suffix_array::cmp(const InputIteraotr arr, size_t a, size_t b, size_t l){
return arr[a] == arr[b] && arr[a + l] == arr[b + l];
}
template<class InputIteraotr>
void suffix_array::calHeight(const InputIteraotr arr, size_t len){
_height_array.resize(_suffix_array.size() - 1);
for (auto i = 0; i != _suffix_array.size() - 1; ++i){
auto n = 0;
for (auto j = _suffix_array[i], k = _suffix_array[i + 1];
arr[j] == arr[k] && (arr + j) != (arr + len) && (arr + k) != (arr + len);
++j, ++k)
++n;
_height_array[i] = n;
}
}
template<class InputIterator>
void suffix_array::calSuffix(const InputIterator arr, size_t len, size_t max_len){
//采用了罗穗骞论文中实现的倍增算法
//算法时间复杂度 = O(nlg(n))
_suffix_array.resize(len);
int wa[256], wb[256], wv[256], ws[256];
int i, j, p, *x = wa, *y = wb, *t;
//以下四行代码是把各个字符(也即长度为1的字符串)进行基数排序
for (i = 0; i < max_len; i++) ws[i] = 0;
//x[]里面本意是保存各个后缀的rank值的,但是这里并没有去存储rank值,因为后续只是涉及x[]的比较工作,因而这一步可以不用存储真实的rank值,能够反映相对的大小即可。
for (i = 0; i < len; i++) ws[x[i] = arr[i]]++;
for (i = 1; i < max_len; i++) ws[i] += ws[i - 1];
//i之所以从len-1开始循环,是为了保证在当字符串中有相等的字符串时,默认靠前的字符串更小一些。
for (i = len - 1; i >= 0; i--) _suffix_array[--ws[x[i]]] = i;
//下面这层循环中p代表rank值不用的字符串的数量,如果p达到len,那么各个字符串的大小关系就已经明了了。
//j代表当前待合并的字符串的长度,每次将两个长度为j的字符串合并成一个长度为2*j的字符串,当然如果包含字符串末尾具体则数值应另当别论,但思想是一样的。
//max_len同样代表基数排序的元素的取值范围
for (j = 1, p = 1; p < len; j *= 2, max_len = p){
//以下两行代码实现了对第二关键字的排序
for (p = 0, i = len - j; i < len; i++) y[p++] = i;
for (i = 0; i < len; i++) if (_suffix_array[i] >= j) y[p++] = _suffix_array[i] - j;
//第二关键字基数排序完成后,y[]里存放的是按第二关键字排序的字符串下标
//这里相当于提取出每个字符串的第一关键字(前面说过了x[]是保存rank值的,也就是字符串的第一关键字),放到wv[]里面是方便后面的使用
//以下四行代码是按第一关键字进行的基数排序
for (i = 0; i < len; i++) wv[i] = x[y[i]];
for (i = 0; i < max_len; i++) ws[i] = 0;
for (i = 0; i < len; i++) ws[wv[i]]++;
for (i = 1; i < max_len; i++) ws[i] += ws[i - 1];
for (i = len - 1; i >= 0; i--) _suffix_array[--ws[wv[i]]] = y[i];
//下面两行就是计算合并之后的rank值了,而合并之后的rank值应该存在x[]里面,但我们计算的时候又必须用到上一层的rank值,也就是现在x[]里面放的东西,如果我既要从x[]里面拿,又要向x[]里面放,怎么办?
//当然是先把x[]的东西放到另外一个数组里面,省得乱了。这里就是用交换指针的方式,高效实现了将x[]的东西“复制”到了y[]中。
for (t = x, x = y, y = t, p = 1, x[_suffix_array[0]] = 0, i = 1; i < len; i++)
x[_suffix_array[i]] = cmp(y, _suffix_array[i - 1], _suffix_array[i], j) ? p - 1 : p++;
}
}
}
#endif<file_sep>/TinySTL/Test/AlgorithmTest.h
#ifndef _ALGORITHM_TEST_H_
#define _ALGORITHM_TEST_H_
#include "TestUtil.h"
#include "../Algorithm.h"
#include <algorithm>
#include <array>
#include <cctype>
#include <cstring>
#include <cassert>
#include <functional>
#include <list>
#include <random>
#include <vector>
#include "../BinarySearchTree.h"
#include "../List.h"
#include "../Vector.h"
namespace TinySTL{
namespace AlgorithmTest{
void testFill();
void testFillN();
void testMinMax();
void testHeapAlgorithm();
void testIsHeap();
void testAllOf();
void testNoneOf();
void testAnyOf();
void testForEach();
void testFind();
void testFindEnd();
void testFindFirstOf();
void testAdjacentFind();
void testCount();
void testMismatch();
void testEqual();
void testIsPermutation();
void testSearch();
void testAdvance();
void testSort();
void testGenerate();
void testDistance();
void testCopy();
void testAllCases();
}
}
#endif<file_sep>/TinySTL/Test/PairTest.cpp
#include "PairTest.h"
namespace TinySTL{
namespace PairTest{
template<class Container1, class Container2>
static inline bool container_equal(const Container1& pair1, const Container2& pair2){
return (pair1.first == pair2.first && pair1.second == pair2.second);
}
void testCase1(){
stdPair<int> p1(5, 5);
tsPair<int> p2(5, 5);
assert(container_equal(p1, p2));
}
void testCase2(){
stdPair<int> p1(stdPair<int>(0, 0));
tsPair<int> p2(tsPair<int>(0, 0));
assert(container_equal(p1, p2));
}
void testCase3(){
stdPair<std::string> temp1 = std::make_pair(std::string("zxh"), std::string("zxh"));
stdPair<std::string> p1 = temp1;
tsPair<std::string> temp2 = TinySTL::make_pair(std::string("zxh"), std::string("zxh"));
tsPair<std::string> p2 = temp2;
assert(container_equal(p1, p2));
}
void testCase4(){
TinySTL::pair<int, char> foo(10, 'z');
TinySTL::pair<int, char> bar(90, 'a');
assert(!(foo == bar));
assert(foo != bar);
assert(foo < bar);
assert(!(foo > bar));
assert(foo <= bar);
assert(!(foo >= bar));
}
void testCase5(){
TinySTL::pair<int, char> foo(10, 'z');
TinySTL::pair<int, char> bar(90, 'a');
foo.swap(bar);
assert(foo.first == 90 && foo.second == 'a');
assert(bar.first == 10 && bar.second == 'z');
}
void testAllCases(){
testCase1();
testCase2();
testCase3();
testCase4();
testCase5();
}
}
}<file_sep>/TinySTL/Test/UFSetTest.h
#ifndef _UF_SET_TEST_H_
#define _UF_SET_TEST_H_
#include "../UFSet.h"
#include <cassert>
namespace TinySTL{
namespace UFSetTest{
void testCase1();
void testAllCases();
}
}
#endif<file_sep>/README.md
TinySTL
=======
采用C++11实现一款简易的STL标准库,既是C++STL的一个子集(裁剪了一些容器和算法)又是一个超集(增加了一些容器和算法)
目的:练习数据结构与算法和C++ Template编程
编译环境:VS2013及以上版本
##开发计划:
* STL的几大基本组件,如string、vector、list、deque、set、map、unordered_\*等
* STL算法库中的大部分算法
* circular buffer
* bitmap
* skip list
* binary search tree
* AVL tree
* rbtree
* segment tree
* splay tree
* rope
* Van Emde Boas tree
* treap
* B-tree
* trie
* suffix array/tree
* Disjoint-set data structure
* k-d tree
* R-tree
* Matrix
* Graph
* bloom filter
##完成进度:
* STL的几大基本组件
* type traits:100%
* 空间配置器:100%
* iterator traits:100%
* reverse_iterator:100%
* vector:100%
* string:100%
* priority_queue:100%
* stack:100%
* deque:100%
* queue:100%
* pair:100%
* list:100%
* unordered_set:100%
* unique_ptr:100%
* shared_ptr:100%
* cow_ptr:100%
* STL Algorithms:
* fill:100%
* fill_n:100%
* find:100%
* is_heap:100%
* min、max:100%
* make_heap:100%
* pop_heap:100%
* push_heap:100%
* sort_heap:100%
* swap:100%
* all_of:100%
* any_of:100%
* none_of:100%
* find_if:100%
* find_if_not:100%
* adjacent_find:100%
* count:100%
* count_if:100%
* mismatch:100%
* equal:100%
* is_permutation:100%
* search:100%
* advance:100%
* sort:100%
* generate:100%
* generate_n:100%
* distance:100%
* copy:100%
* 其他组件:
* circular_buffer:100%
* bitmap:100%
* binary_search_tree:100%
* avl_tree:100%
* suffix_array:100%
* directed_graph:100%
* trie tree:100%
* Disjoint-set data structure:100%
##TinySTL单元测试(原单元测试代码逐步):
* pair:100%
* algorithm:20%
* vector:100%
* string:100%
* priority_queue:100%
* suffix_array:100%
* queue:100%
* stack:100%
* bitmap:100%
* circular_buffer:100%
* deque:100%
* list:100%
* binary_search_tree:100%
* avl_tree:100%
* unordered_set:100%
* directed_graph:100%
* trie tree:100%
* unique_ptr:100%
* shared_ptr:100%
* Disjoint-set data structure:100%
#TinySTL性能测试:
###测试环境:Windows 7 && VS2013 && release模式
###测试结果:
####(1):vector<int>
//std::vector<int> vec;
TinySTL::vector<int> vec;
ProfilerInstance::start();
int i = 0;
for (; i != 10000; ++i){
vec.push_back(i);
}
ProfilerInstance::finish();
ProfilerInstance::dumpDuringTime();
|container|quantity|time(ms)|
|---------|--------|--------|
|TinySTL::vector<int>|10万|2|
|TinySTL::vector<int>|100万|11|
|TinySTL::vector<int>|1000万|129|
|std::vector<int>|10万|6|
|std::vector<int>|100万|16|
|std::vector<int>|1000万|210|
####(2):vector<string>
//std::vector<std::string> vec;
TinySTL::vector<std::string> vec;
ProfilerInstance::start();
int i = 0;
for (; i != 100000; ++i){
vec.push_back(std::string("zouxiaohang"));
}
ProfilerInstance::finish();
ProfilerInstance::dumpDuringTime();
|container|quantity|time(ms)|
|---------|--------|--------|
|TinySTL::vector<string>|10万|18|
|TinySTL::vector<string>|100万|181|
|TinySTL::vector<string>|1000万|2372|
|std::vector<string>|10万|29|
|std::vector<string>|100万|232|
|std::vector<string>|1000万|1972|
####(3):circular_buffer<int, N>
TinySTL::circular_buffer<int, 10000> cb(10000, 0);
//boost::circular_buffer<int> cb(10000, 0);
ProfilerInstance::start();
for (int i = 0; i != 10000000; ++i){
cb.push_back(i);
}
ProfilerInstance::finish();
ProfilerInstance::dumpDuringTime();
|container|quantity|time(ms)|
|---------|--------|--------|
|TinySTL::circular_buffer|1000万|75|
|TinySTL::circular_buffer|10000万|604|
|TinySTL::circular_buffer|100000万|5936|
|boost::circular_buffer|1000万|22|
|boost::circular_buffer|10000万|252|
|boost::circular_buffer|100000万|2241|
####(4):题目:利用bitmap找出str中未出现的字母
std::string str("abcdefghijklmnpqrstuvwxyz");
TinySTL::bitmap<26> bm;
for (auto it = str.cbegin(); it != str.cend(); ++it){
bm.set(*it - 'a');
}
cout << bm << endl;
cout << bm.size() << endl;
for (int i = 0; i != 26; ++i){
if (!bm.test(i))
cout << "字母" << (char)('a' + i) << "没出现!!!" << endl;
}
输出结果:
111111111111110111111111111000000
32
字母o没出现!!!
####(5):string
//std::string str;
TinySTL::string str;
ProfilerInstance::start();
int i = 0;
for (; i != 1000000; ++i){
str.push_back('x');
}
ProfilerInstance::finish();
ProfilerInstance::dumpDuringTime();
|container|quantity|time(ms)|
|---------|--------|--------|
|TinySTL::string|100万|7|
|TinySTL::string|1000万|39|
|TinySTL::string|10000万|484|
|std::string|100万|37|
|std::string|1000万|229|
|std::string|10000万|1965|
####(6):priority_queue<int>
//std::priority_queue<int> pq;
TinySTL::priority_queue<int> pq;
ProfilerInstance::start();
int i = 0;
for (; i != 100000; ++i){
pq.push(i);
}
ProfilerInstance::finish();
ProfilerInstance::dumpDuringTime();
|container|quantity|time(ms)|
|---------|--------|--------|
|TinySTL::priority_queue<int>|10万|13|
|TinySTL::priority_queue<int>|100万|97|
|TinySTL::priority_queue<int>|1000万|1032|
|std::priority_queue<int>|10万|12|
|std::priority_queue<int>|100万|67|
|std::priority_queue<int>|1000万|752|
TinySTL::vector<int> v;
int i = 0;
for (; i != 100000; ++i){
v.push_back(i);
}
//std::priority_queue<int> pq(v.begin(), v.end());
TinySTL::priority_queue<int> pq(v.begin(), v.end());
ProfilerInstance::start();
for (i = 0; i != 100000; ++i){
pq.pop();
}
ProfilerInstance::finish();
ProfilerInstance::dumpDuringTime();
|container|quantity|time(ms)|
|---------|--------|--------|
|TinySTL::priority_queue<int>|10万|19|
|TinySTL::priority_queue<int>|100万|137|
|TinySTL::priority_queue<int>|1000万|1532|
|std::priority_queue<int>|10万|7|
|std::priority_queue<int>|100万|92|
|std::priority_queue<int>|1000万|1214|
####(7):binary_search_tree<string>
ifstream f;
//char buff[256] = { 0 };
std::string word;
f.open("C:\\Users\\zxh\\Desktop\\text.txt");
TinySTL::vector<TinySTL::string> v;
while (f.good()){
f >> word;
//std::copy(word.begin(), word.end(), buff);
//v.push_back(TinySTL::string(buff, buff + word.size()));
v.push_back(word);
}
TinySTL::binary_search_tree<TinySTL::string> sbst;
ProfilerInstance::start();
for (const auto& word : v){
sbst.insert(word);
}
ProfilerInstance::finish();
ProfilerInstance::dumpDuringTime();
f.close();
|container|quantity|time(ms)|
|---------|--------|--------|
|TinySTL::binary_search_tree<string>|44067|16|
|TinySTL::binary_search_tree<string>|169664|64|
|TinySTL::binary_search_tree<string>|438230|277|
####(8):deque<int>
//std::deque<int> dq;
TinySTL::deque<int> dq;
ProfilerInstance::start();
const int max = 10000000;
int i = 0;
for (; i != max / 2; ++i){
dq.push_front(i);
}
for (; i != max; ++i){
dq.push_back(i);
}
ProfilerInstance::finish();
ProfilerInstance::dumpDuringTime();
|container|quantity|time(ms)|
|---------|--------|--------|
|TinySTL::deque<int>|10万|15|
|TinySTL::deque<int>|100万|78|
|TinySTL::deque<int>|1000万|1186|
|std::deque<int>|10万|90|
|std::deque<int>|100万|1087|
|std::deque<int>|1000万|4835|
#####ps:这个性能差距的原因1是内部实现的机制不同,我的deque是预先分配内存因此相同条件下占用的内存更多,而stl的deque是需要的时候再分配,更加节省内存;2是stl的deque实现了更多更灵活的插入删除操作,我只是实现了在头尾的插入和删除
####(9):avl_tree<int>
TinySTL::binary_search_tree<int> bst;
TinySTL::avl_tree<int> avlt;
for (int i = 0; i != 10000; ++i){
avlt.insert(i);
bst.insert(i);
}
cout << "binary_search_tree height = " << bst.height() << endl;
cout << "avl_tree height = " << avlt.height() << endl;
输出结果:
binary_search_tree height = 10000
avl_tree height = 14
####(10):list<int>
TinySTL::list<int> list;
//std::list<int> list;
const size_t max = 100000;
ProfilerInstance::start();
for (size_t i = 0; i != max; ++i)
list.push_back(i);
ProfilerInstance::finish();
ProfilerInstance::dumpDuringTime();
|container|quantity|time(ms)|
|---------|--------|--------|
|TinySTL::list<int>|10万|4|
|TinySTL::list<int>|100万|33|
|TinySTL::list<int>|1000万|286|
|std::list<int>|10万|189|
|std::list<int>|100万|1774|
|std::list<int>|1000万|17571|
####(11):list<int>::sort()
TinySTL::list<int> list1;
std::list<int> list2;
std::default_random_engine dre;
std::uniform_int_distribution<int> id;
const size_t max = 10000;
for (int i = 0; i != max; ++i){
auto n = id(dre);
list1.push_back(n);
list2.push_back(n);
}
double cost1 = 0.0, cost2 = 0.0;
for (int i = 0; i != 100; ++i){
ProfilerInstance::start();
list1.sort();//TinySTL::list<int>
ProfilerInstance::finish();
cost1 += ProfilerInstance::millisecond();
ProfilerInstance::start();
list2.sort();//std::list<int>
ProfilerInstance::finish();
cost2 += ProfilerInstance::millisecond();
}
cout << "TinySTL time: " << cost1 / 100 << "ms" << endl;
cout << "std time: " << cost2 / 100 << "ms" << endl;
|container|quantity|time(ms)|
|---------|--------|--------|
|TinySTL::list<int>|1万|0.88|
|TinySTL::list<int>|10万|17.621|
|TinySTL::list<int>|100万|591.354|
|std::list<int>|1万|1.25|
|std::list<int>|10万|35.692|
|std::list<int>|100万|665.128|
####(12):suffix_array
char arr[] = { 'a', 'a', 'b', 'a', 'a', 'a', 'a', 'b' };
TinySTL::suffix_array sa(arr, 8);
auto suffixArray = sa.suffixArray();
auto rankArray = sa.rankArray();
auto heightArray = sa.heightArray();
TinySTL::Test::print_container(suffixArray, "suffixArray");
TinySTL::Test::print_container(rankArray, "rankArray");
TinySTL::Test::print_container(heightArray, "heightArray");

####(13):unordered_set<int>
TinySTL::Unordered_set<int> ust(10);
//std::unordered_set<int> ust(10);
const size_t insert_count = 1000000;
const uint64_t query_count = 100000000;
//calculate total insert time
ProfilerInstance::start();
for (size_t i = 0; i != insert_count; ++i){
ust.insert(i);//per insert time
}
ProfilerInstance::finish();
ProfilerInstance::dumpDuringTime();
//calculate total query time
ProfilerInstance::start();
for (uint64_t i = 0; i != query_count; ++i){
ust.count(i);//per query time
}
ProfilerInstance::finish();
ProfilerInstance::dumpDuringTime();
|container|quantity|insert time(ms)|query time(ms)|
|---------|--------|--------|--------|
|TinySTL::unordered_set<int>|1万/1亿|8|97|
|TinySTL::unordered_set<int>|10万/10亿|139|1000|
|TinySTL::unordered_set<int>|100万/100亿|1214|9546|
|std::unordered_set<int>|1万/1亿|64|101|
|std::unordered_set<int>|10万/10亿|884|953|
|std::unordered_set<int>|100万/100亿|2781|9682|
####(14):sort
std::random_device rd;
const int len = 10000000;
int arr[len];
std::generate(std::begin(arr), std::end(arr), [&rd](){return rd(); });
ProfilerInstance::start();
TinySTL::sort(std::begin(arr), std::end(arr));
//std::sort(std::begin(arr), std::end(arr));
ProfilerInstance::finish();
ProfilerInstance::dumpDuringTime();
|algorithm|quantity|time(ms)|
|---------|--------|--------|
|TinySTL::sort|10万|11|
|TinySTL::sort|100万|133|
|TinySTL::sort|1000万|1547|
|std::sort|10万|13|
|std::sort|100万|147|
|std::sort|1000万|1730|
####(15):directed_graph
template<class Index, class Value>
using dGraph = TinySTL::directed_graph < Index, Value > ;
dGraph<int, int> g;
dGraph<int, int>::nodes_set_type set1, set2, set3;
set1.push_back(g.make_node(1, 11));
set1.push_back(g.make_node(2, 22));
set1.push_back(g.make_node(3, 33));
g.add_node(g.make_node(0, 0), set1);
set2.push_back(g.make_node(5, 55));
set2.push_back(g.make_node(6, 66));
set2.push_back(g.make_node(7, 77));
g.add_node(g.make_node(1, 11), set2);
set3.push_back(g.make_node(12, 1212));
set3.push_back(g.make_node(13, 1313));
set3.push_back(g.make_node(14, 1414));
g.add_node(7, set3);
g.make_edge(12, 2);
g.make_edge(12, 3);
g.make_edge(12, 0);
std::cout << "graph after add nodes:" << std::endl;
std::cout << g.to_string();
auto func = [](const dGraph<int, int>::node_type& node){
std::cout << "[" << node.first << "," << node.second << "]" << std::endl;
};
std::cout << "graph DFS from node(1, 11):" << std::endl;
g.DFS(1, func);
std::cout << "graph BFS from node(1, 11):" << std::endl;
g.BFS(1, func);
std::cout << "graph after delete node(7, 77):" << std::endl;
g.delete_node(dGraph<int, int>::node_type(7, 77));
std::cout << g.to_string();




####(16):trie tree
TinySTL::trie_tree t;
std::ifstream in;
in.open("C:\\Users\\zxh\\Desktop\\trie_tree_test.txt");
std::vector<std::string> v;
std::string s;
while (in){
in >> s;
v.push_back(s);
}
ProfilerInstance::start();
for (const auto& str : v){
t.insert(TinySTL::string(str.data()));
}
ProfilerInstance::finish();
std::cout << "build trie tree costs " << ProfilerInstance::millisecond() << "ms" << std::endl;
ProfilerInstance::start();
auto res = t.get_word_by_prefix("v");
ProfilerInstance::finish();
std::cout << "get word by prefix \"v\" costs " << ProfilerInstance::millisecond() << "ms" << std::endl;
auto i = 0;
for (const auto& str : res){
++i;
if (i % 10 == 0) std::cout << std::endl;
std::cout << str << " ";
}
std::cout << std::endl;

####(17):shared_ptr
shared_ptr<string> sp1(new string("hello"));
assert(sp1.use_count() == 1);
assert(*sp1 == "hello");
sp1->append(" world");
assert(*sp1 == "hello world");
{
auto sp2 = sp1;
assert(sp1.use_count() == 2);
}
assert(sp1.use_count() == 1);
####(18):unique_ptr
auto up = make_unique<string>(10, '0');
up->append("111");
assert(*up == "0000000000111");
up.release();
assert(up == nullptr);
up.reset(new string("hello"));
assert(*up == "hello");
####(19):cow_ptr
cow_ptr<string> cp1 = make_cow<string>("zouxiaohang");
auto cp2 = cp1, cp3 = cp1;
assert(cp1 == cp2 && cp2 == cp3);
assert(*cp1 == *cp2 && *cp2 == *cp3 && *cp3 == "zouxiaohang");
string s = *cp2;//read
assert(s == "zouxiaohang");
assert(cp1 == cp2 && cp2 == cp3);
assert(*cp1 == *cp2 && *cp2 == *cp3 && *cp3 == "zouxiaohang");
*cp2 = ("C++");//write
assert(*cp1 == *cp3 && *cp3 == "zouxiaohang");
assert(*cp2 == "C++");
####(19):union-find set
uf_set<10> uf;
uf.Union(0, 1);
uf.Union(2, 3);
uf.Union(3, 1);
assert(uf.Find(0) == uf.Find(2));
####(20):子字符查询 改进原来代码中mn-n的复杂度
<file_sep>/TinySTL/Test/RefTest.cpp
#include "RefTest.h"
namespace TinySTL{
namespace RefTest{
void testCaseRef(){
ref_t<int> r1;
assert(r1.count() == 0);
assert(r1.get_data() == nullptr);
int *p = new int(0);
ref_t<int> r2(p);
assert(r2.count() == 1);
assert(r2.get_data() != nullptr);
++r2;
assert(r2.count() == 2);
--r2;
assert(r2.count() == 1);
}
void testAllCases(){
testCaseRef();
}
}
}
|
8662931078c2ff999c8b2ee248ee1ce2109ab81a
|
[
"Markdown",
"C",
"C++"
] | 44
|
C++
|
sydtju/TinySTL
|
a02fe7120f2512b472a133a84d25a57ab8b4d03d
|
6d0d396dc4cf11e686b2abe6edde707ea9e9df3b
|
refs/heads/master
|
<repo_name>ejprok/HackathonSpring2018<file_sep>/TODO.txt
UI:
*Display the test
<file_sep>/requirements.txt
absl-py==0.1.13
astor==0.6.2
beautifulsoup4==4.6.0
bleach==1.5.0
bs4==0.0.1
certifi==2018.1.18
chardet==3.0.4
click==6.7
Flask==0.12.2
gast==0.2.0
grpcio==1.10.1
html5lib==0.9999999
idna==2.6
itsdangerous==0.24
Jinja2==2.10
lxml==4.2.1
Markdown==2.6.11
MarkupSafe==1.0
numpy==1.14.2
pandas==0.22.0
protobuf==3.5.2.post1
PyMySQL==0.8.0
python-dateutil==2.7.2
pytz==2018.3
requests==2.18.4
six==1.11.0
tensorboard==1.7.0
tensorflow==1.7.0
termcolor==1.1.0
urllib3==1.22
Werkzeug==0.14.1
<file_sep>/lib/Database.py
import pymysql
class Database:
def __init__(self):
self.conn = pymysql.connect(host='localhost', user='root', passwd='<PASSWORD>', db='Question_Database')
self.cur = self.conn.cursor()
def insertQuestion(self, question, answer, keyword):
insert = """INSERT INTO Test_Questions (Question, Answer, Keyword) VALUES (%s, %s, %s)"""
try:
if (question != "" and answer != "" and question != "..." and answer != "..."):
self.cur.execute(insert, (question, answer, keyword))
except:
print("cannot insert")
self.conn.commit()
def selectQuestions(self, keyword):
select = """SELECT Question, Answer FROM Test_Questions WHERE Keyword=%s ORDER BY RAND() LIMIT 20;"""
try:
self.cur.execute(select, (keyword))
result = self.cur.fetchall()
except:
print("cannot select")
return result
self.conn.commit()
def closeConnection(self):
self.conn.close()
<file_sep>/lib/Scraper.py
import bs4 as bs
import urllib.request
import pymysql
from lib.Database import Database
class Scraper:
def scan_and_scrape(self, kw):
data = {}
count = 1
sauce = urllib.request.urlopen('https://quizlet.com/subject/'+ kw + '/').read()
soup = bs.BeautifulSoup(sauce, 'lxml')
db = Database()
for div in soup.find_all("div", {"class": "UILinkBox-link"}):
souce = urllib.request.urlopen(div.a.get('href')).read()
stone_soup = bs.BeautifulSoup(souce, 'lxml')
for span in stone_soup.find_all("span", {"class": "TermText"}):
data[count] = span.text
if (count % 2 == 0):
db.insertQuestion(data[count - 1], data[count], kw)
count += 1
db.closeConnection()
return data
<file_sep>/app.py
from flask import Flask, render_template, request, redirect, url_for
from lib.Scraper import Scraper
from lib.Database import Database
import tensorflow as tf
import requests
import pymysql
import _thread
import time
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/exam")
def exam():
keyword = request.args.get('keyword')
db = Database()
questions = db.selectQuestions(keyword)
return render_template("exam.html", questions=questions, keyword=keyword)
@app.route("/quizlet", methods=['GET', 'POST'])
def quizlet_search():
if request.method == 'POST':
search = request.form.get('search')
try:
_thread.start_new_thread( scrape_quizlet, (search,) )
except:
print( "cannot create a new thread")
return redirect(url_for('exam', keyword=search))
return "you were searching"
def scrape_quizlet(search):
sc = Scraper()
data = sc.scan_and_scrape(search)
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0', port=80)
|
9505dd0aabea30cd50d8f0a00839b6cbd87b2f58
|
[
"Python",
"Text"
] | 5
|
Text
|
ejprok/HackathonSpring2018
|
c5ba07b4732a3b816b937df9c1efa641660d9497
|
2cfac3731f87dab5d9b18695c05b23a9d3d454f9
|
refs/heads/main
|
<repo_name>stayboogy/custom-debian-iso-creator<file_sep>/README.md
# Custom Debian ISO Creator
Scripts I use for Debian home WiFi penetration testing, deploying/downloading Linux and other operating systems, and other ad-hoc linux utility functionality like formatting disks or resetting Windows passwords on old drives.
See [Create a Custom Debian Live Environment (CD or USB)](https://willhaley.com/blog/custom-debian-live-environment/) for further discussion.
## Run
Copy the `sample-config.yaml` to `config.yaml` and update as needed.
```
# Build the docker image, run it, and start a shell.
./run.sh
```
```
# Generate ISO.
docker:$ ./generate.py
```
## Custom Files
* `custom-system-files` add any files here in the desired output directory stucture (e.g. `custom-system-files/etc/whatever/whatever.conf`). These files will be copied as `root` before `apt` is run in the `chroot` environment.
* `custom-user-files` add any files here in the desired output directory structure (e.g. `custom-user-files/home/myuser/file.txt`). These filles will be copied as the `<user>` as defined in `config.yaml` and will be copied after `apt` has run in the `chroot` and the user account was created.
## Utilities
Some of the installed applications (transmission-gtk for BitTorrent, reaver, aircrack, hashcat, etc.) in this repo may raise a few eyebrows. There is nothing wrong with using these tools for research purposes.
I think it is interesting and a great learning experience for future security researchers or computer hobbyists to try "hacking" one's own WiFi network to understand how weak or strong their home security truly is and how networking security protocols function.
See references and related materials from well-known univerities.
* https://rtg.cis.upenn.edu/cis700-002/talks/Aircrack-Reaver-Fern.pdf
* https://super.cs.uchicago.edu/usable17/crackingtutorial.html
* https://tagteam.harvard.edu/hub_feeds/4158/feed_items/2535345
* http://people.oregonstate.edu/~marshaby/OSUSIM_Project_Writeups/2018_AirCrackNG/AirCrackNG.html
* https://courses.cs.washington.edu/courses/cse484/15sp/slides/484Lecture-Wireless-Hacking.pdf
* https://core.ac.uk/download/pdf/80993616.pdf
* https://courses.engr.illinois.edu/cs461/fa2015/static/proj3_2.pdf
* http://www-scf.usc.edu/~csci530l/instructions/lab-authentication-instructions-hashcat.htm
* https://www.cs.usfca.edu/~ejung/courses/686/lab1.html
* http://mirrors.mit.edu/parrot/misc/openbooks/security/HHS_en11_Hacking_Passwords.v2.pdf
* https://courses.csail.mit.edu/6.857/2016/files/9.pdf
* http://www.scs.stanford.edu/~sorbo/bittau-wep-slides.pdf
Just like criminal justice, psychology, philosophy, art, mechnical engineering, mathematics, health, astrophysics, or just about any other discipline may ask "what if" or "let me test these understood assumptions", so does computer science, and the utilities included in these scripts exist for that purpose.
<file_sep>/lib/standard-files/usr/local/bin/custom-startup.sh
#!/bin/bash
set -e
date
id=$(cat /etc/machine-id)
name=$(printf "${id}" | head -c8)
hostnamectl set-hostname "${name}"
cat << EO1 > /etc/hosts
127.0.0.1 ${name} ${name}.localhost localhost
::1 ${name} localhost ip6-localhost ip6-loopback
fc00:db20:35b:7399::5 ip6-allnodes
fc00:db20:35b:7399::5 ip6-allrouters
EO1
date
<file_sep>/lib/scripts/_bootstrap_debian.sh
#!/usr/bin/env bash
set -e
rm -rf "${HOME}/LIVE_BOOT/chroot"
cache_server=""
if [ -n "${CONFIG_APT_CACHE_SERVER_ADDRESS}" ];
then
cache_server="${CONFIG_APT_CACHE_SERVER_ADDRESS}/"
fi
debootstrap \
--arch=amd64 \
--variant=minbase \
"${CONFIG_RELEASE}" \
"${HOME}/LIVE_BOOT/chroot" \
"http://${cache_server}${CONFIG_APT_SERVER_ADDRESS}/debian/"
if [ -n "${cache_server}" ];
then
sed -i "s|${cache_server}||g" ${HOME}/LIVE_BOOT/chroot/etc/apt/*.list
fi
<file_sep>/lib/scripts/_customize_debian.sh
#!/usr/bin/env bash
set -e
printf "${CONFIG_APT_LIST_BACKPORTS}" > "${HOME}/LIVE_BOOT/chroot/etc/apt/sources.list.d/backports.list"
printf "${CONFIG_APT_LIST_EXTRAS}" > "${HOME}/LIVE_BOOT/chroot/etc/apt/sources.list.d/extras.list"
printf "${CONFIG_APT_LIST_SECURITY}" > "${HOME}/LIVE_BOOT/chroot/etc/apt/sources.list.d/security.list"
# Copy basic configuration files that these scripts will always need.
rsync -avr /app/standard-files/ "${HOME}/LIVE_BOOT/chroot/"
# Copy any additional system-files the user has defined.
rsync -avr /app/custom-system-files/ "${HOME}/LIVE_BOOT/chroot/"
chroot ${HOME}/LIVE_BOOT/chroot /bin/bash <<EOF
set -e
export DEBIAN_FRONTEND=noninteractive
apt update
# Install packages, but use DPkg options to preserve any custom configs.
# https://debian-handbook.info/browse/stable/sect.package-meta-information.html#sidebar.questions-conffiles
apt install -y --no-install-recommends -o DPkg::options::="--force-confdef" -o DPkg::options::="--force-confold" ${CONFIG_PACKAGES_STANDARD}
apt install -y --no-install-recommends -o DPkg::options::="--force-confdef" -o DPkg::options::="--force-confold" --download-only ${CONFIG_PACKAGES_DOWNLOAD_ONLY}
apt -t bullseye-backports install -y --no-install-recommends -o DPkg::options::="--force-confdef" -o DPkg::options::="--force-confold" ${CONFIG_PACKAGES_BACKPORTS}
useradd -m -s /bin/bash -G sudo ${CONFIG_USER}
printf "${CONFIG_PASSWORD}\n${CONFIG_PASSWORD}\n" | passwd ${CONFIG_USER}
passwd -l root
EOF
# Copy additional files as needed to further customize the image.
uid=$(chroot ${HOME}/LIVE_BOOT/chroot /bin/bash -c "id -u ${CONFIG_USER}")
gid=$(chroot ${HOME}/LIVE_BOOT/chroot /bin/bash -c "id -g ${CONFIG_USER}")
rsync -avr --chown "${uid}:${gid}" /app/custom-user-files/ "${HOME}/LIVE_BOOT/chroot/"
chroot "${HOME}/LIVE_BOOT/chroot" /bin/bash -c "${CONFIG_COMMANDS_CHROOT}"
chroot "${HOME}/LIVE_BOOT/chroot" /bin/bash <<EOF
systemctl enable custom-startup.service
update-initramfs -u
EOF
rm -f "${HOME}/LIVE_BOOT/chroot/etc/hosts"
<file_sep>/lib/generate.py
#!/usr/bin/env python3
import os
import subprocess
import sys
import yaml
with open("/app/config.yaml", "r") as config_file:
config = yaml.safe_load(config_file)
user = config.get("user", {})
debian = config.get("debian", {})
debian_apt = debian.get("apt", {})
debian_apt_lists = debian_apt.get("lists", {})
debian_apt_packages = debian_apt.get("packages", {})
commands = config.get("commands", {})
# Required config settings.
os.environ["CONFIG_USER"] = user.get("name")
os.environ["CONFIG_PASSWORD"] = user.get("password")
os.environ["CONFIG_RELEASE"] = debian.get("release")
os.environ["CONFIG_APT_SERVER_ADDRESS"] = debian_apt.get("server_address")
# Optional config settings.
os.environ["CONFIG_PACKAGES_STANDARD"] = debian_apt_packages.get("standard", "")
os.environ["CONFIG_PACKAGES_BACKPORTS"] = debian_apt_packages.get("backports", "")
os.environ["CONFIG_PACKAGES_DOWNLOAD_ONLY"] = debian_apt_packages.get("download_only", "")
os.environ["CONFIG_COMMANDS_CHROOT"] = commands.get("chroot", "")
os.environ["CONFIG_APT_CACHE_SERVER_ADDRESS"] = debian_apt.get("bootstrap_cache_server_address", "")
os.environ["CONFIG_APT_LIST_BACKPORTS"] = debian_apt_lists.get("backports", "")
os.environ["CONFIG_APT_LIST_EXTRAS"] = debian_apt_lists.get("extras", "")
os.environ["CONFIG_APT_LIST_SECURITY"] = debian_apt_lists.get("security", "")
subprocess.run("/app/scripts/_bootstrap_debian.sh", check=True, shell=True, stdout=sys.stdout, stderr=sys.stderr)
subprocess.run("/app/scripts/_customize_debian.sh", check=True, shell=True, stdout=sys.stdout, stderr=sys.stderr)
subprocess.run("/app/scripts/_build_iso.sh", check=True, shell=True, stdout=sys.stdout, stderr=sys.stderr)
<file_sep>/run.sh
#!/usr/bin/env bash
set -e
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
docker build "${SCRIPT_DIR}/lib" -t williamhaley/custom-debian-builder
docker run \
--rm \
-it \
-v "${SCRIPT_DIR}/output":/output \
-v "${SCRIPT_DIR}/config.yaml":/app/config.yaml:ro \
-v "${SCRIPT_DIR}/lib/scripts":/app/scripts:ro \
-v "${SCRIPT_DIR}/lib/standard-files":/app/standard-files:ro \
-v "${SCRIPT_DIR}/lib/generate.py":/app/generate.py:ro \
-v "${SCRIPT_DIR}/custom-system-files":/app/custom-system-files:ro \
-v "${SCRIPT_DIR}/custom-user-files":/app/custom-user-files:ro \
williamhaley/custom-debian-builder \
/bin/bash
<file_sep>/lib/scripts/_build_iso.sh
#!/usr/bin/env bash
set -e
mkdir -p ${HOME}/LIVE_BOOT/{staging/{EFI/boot,boot/grub/x86_64-efi,isolinux,live},tmp}
squashfs_image="${HOME}/LIVE_BOOT/staging/live/filesystem.squashfs"
mksquashfs \
"${HOME}/LIVE_BOOT/chroot" \
"${squashfs_image}" \
-e boot
cp ${HOME}/LIVE_BOOT/chroot/boot/vmlinuz-* \
"${HOME}/LIVE_BOOT/staging/live/vmlinuz" && \
cp ${HOME}/LIVE_BOOT/chroot/boot/initrd.img-* \
"${HOME}/LIVE_BOOT/staging/live/initrd"
cat << EOF > ${HOME}/LIVE_BOOT/staging/isolinux/isolinux.cfg
UI vesamenu.c32
MENU TITLE Boot Menu
DEFAULT linux
TIMEOUT 50
MENU RESOLUTION 640 480
MENU COLOR border 30;44 #40ffffff #a0000000 std
MENU COLOR title 1;36;44 #9033ccff #a0000000 std
MENU COLOR sel 7;37;40 #e0ffffff #20ffffff all
MENU COLOR unsel 37;44 #50ffffff #a0000000 std
MENU COLOR help 37;40 #c0ffffff #a0000000 std
MENU COLOR timeout_msg 37;40 #80ffffff #00000000 std
MENU COLOR timeout 1;37;40 #c0ffffff #00000000 std
MENU COLOR msg07 37;40 #90ffffff #a0000000 std
MENU COLOR tabmsg 31;40 #30ffffff #00000000 std
LABEL linux
MENU LABEL Debian Live [BIOS/ISOLINUX]
MENU DEFAULT
KERNEL /live/vmlinuz
APPEND initrd=/live/initrd boot=live net.ifnames=0
LABEL linux
MENU LABEL Debian Live [BIOS/ISOLINUX] (nomodeset)
MENU DEFAULT
KERNEL /live/vmlinuz
APPEND initrd=/live/initrd boot=live nomodeset net.ifnames=0
EOF
cat <<'EOF' >${HOME}/LIVE_BOOT/staging/boot/grub/grub.cfg
search --set=root --file /DEBIAN_CUSTOM
set default="0"
set timeout=5
# If X has issues finding screens, experiment with/without nomodeset.
menuentry "Debian Live [EFI/GRUB]" {
linux ($root)/live/vmlinuz boot=live net.ifnames=0
initrd ($root)/live/initrd
}
menuentry "Debian Live [EFI/GRUB] (nomodeset)" {
linux ($root)/live/vmlinuz boot=live nomodeset net.ifnames=0
initrd ($root)/live/initrd
}
EOF
cat <<'EOF' >${HOME}/LIVE_BOOT/tmp/grub-standalone.cfg
search --set=root --file /DEBIAN_CUSTOM
set prefix=($root)/boot/grub/
configfile /boot/grub/grub.cfg
EOF
touch "${HOME}/LIVE_BOOT/staging/DEBIAN_CUSTOM"
cp /usr/lib/ISOLINUX/isolinux.bin "${HOME}/LIVE_BOOT/staging/isolinux/" && \
cp /usr/lib/syslinux/modules/bios/* "${HOME}/LIVE_BOOT/staging/isolinux/"
cp -r /usr/lib/grub/x86_64-efi/* "${HOME}/LIVE_BOOT/staging/boot/grub/x86_64-efi/"
grub-mkstandalone \
--format=x86_64-efi \
--output="${HOME}/LIVE_BOOT/tmp/bootx64.efi" \
--locales="" \
--fonts="" \
"boot/grub/grub.cfg=${HOME}/LIVE_BOOT/tmp/grub-standalone.cfg"
(cd "${HOME}/LIVE_BOOT/staging/EFI/boot" && \
dd if=/dev/zero of=efiboot.img bs=1M count=20 && \
mkfs.vfat efiboot.img && \
mmd -i efiboot.img efi efi/boot && \
mcopy -vi efiboot.img "${HOME}/LIVE_BOOT/tmp/bootx64.efi" ::efi/boot/
)
xorriso \
-as mkisofs \
-iso-level 3 \
-o "${HOME}/LIVE_BOOT/debian-custom.iso" \
-full-iso9660-filenames \
-volid "DEBIAN_CUSTOM" \
-isohybrid-mbr /usr/lib/ISOLINUX/isohdpfx.bin \
-eltorito-boot \
isolinux/isolinux.bin \
-no-emul-boot \
-boot-load-size 4 \
-boot-info-table \
--eltorito-catalog isolinux/isolinux.cat \
-eltorito-alt-boot \
-e /EFI/boot/efiboot.img \
-no-emul-boot \
-isohybrid-gpt-basdat \
-append_partition 2 0xef "${HOME}/LIVE_BOOT/staging/EFI/boot/efiboot.img" \
"${HOME}/LIVE_BOOT/staging"
cp "${HOME}/LIVE_BOOT/debian-custom.iso" /output/
<file_sep>/lib/Dockerfile
FROM ubuntu
ARG DEBIAN_FRONTEND=noninteractive
RUN apt update \
&& apt-get install -y \
debootstrap \
dosfstools \
squashfs-tools \
xorriso \
isolinux \
syslinux-efi \
grub-pc-bin \
grub-efi-amd64-bin \
mtools \
rsync \
python3 python3-venv \
&& apt-get -q -y autoremove \
&& apt-get -q -y clean \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
ENV VIRTUAL_ENV=/env
ENV PATH="${VIRTUAL_ENV}/bin:$PATH"
RUN python3 -m venv ${VIRTUAL_ENV}
COPY ./poetry.lock /env/
COPY ./pyproject.toml /env/
RUN pip install poetry && cd /env && poetry install
|
86c353f761df29cff4dc3f1d9650887f3d65fcb5
|
[
"Markdown",
"Python",
"Dockerfile",
"Shell"
] | 8
|
Markdown
|
stayboogy/custom-debian-iso-creator
|
af7d1646fdede1f00ed457b6a92fff267a6f0c6e
|
a0ce31aabb2543f46000f29823a9b12748549d6a
|
refs/heads/master
|
<repo_name>DevCenterHouse/cmpd.ie<file_sep>/www/portfolio.php
<div class="theme-page padding-bottom-70">
<div class="row gray full-width page-header vertical-align-table">
<div class="row full-width padding-top-bottom-50 vertical-align-cell">
<div class="row">
<div class="page-header-left">
<h1>PORTFOLIO</h1>
</div>
<div class="page-header-right">
<div class="bread-crumb-container">
<label>You Are Here:</label>
<ul class="bread-crumb">
<li>
<a title="Home" href="?page=home">
HOME
</a>
</li>
<li class="separator">
/
</li>
<li>
PORTFOLIO
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="clearfix">
<div class="row">
<ul class="gallery clearfix portfolio-list isotope">
<?php
for($i = 1; $i <= 77; $i++){
echo "
<li>
<a href=\"images/samples/portfolio/img_".$i.".jpg\" rel=\"prettyPhoto[gallery1]\" class=\"prettyPhoto re-preload\">
<img src=\"images/samples/portfolio/img_".$i.".jpg\">
</a>
</li>
";
}
?>
</ul>
</div>
</div>
</div><file_sep>/www/header.php
<!DOCTYPE html>
<html>
<head>
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-PDFRWSF');</script>
<!-- End Google Tag Manager -->
<title>CMPD - Carpentry, Building Maintenance, Roofing, Decking, Attic Conversions and Extension Services in Dublin</title>
<!--meta-->
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.2" />
<meta name="format-detection" content="telephone=yes" />
<meta name="keywords" content="dublin home services, dublin carpenter, dublin carpentry, dublin property maintenance, dublin building maintenance, dublin home maintenance, dublin plumbing, dublin painting, dublin landscaping, dublin composite decking, dublin attic" />
<meta name="description" content="Expert carpentry and property maintenance services with over 15 years of experience on a wide range of construction projects from residential to commercial properties." />
<!--slider revolution-->
<link rel="stylesheet" type="text/css" href="rs-plugin/css/settings.css">
<!--style-->
<link href='//fonts.googleapis.com/css?family=Raleway:100,300,400,500,600,700,900' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="style/reset.css">
<link rel="stylesheet" type="text/css" href="style/superfish.css">
<link rel="stylesheet" type="text/css" href="style/prettyPhoto.css">
<link rel="stylesheet" type="text/css" href="style/jquery.qtip.css">
<link rel="stylesheet" type="text/css" href="style/style.css">
<link rel="stylesheet" type="text/css" href="style/animations.css">
<link rel="stylesheet" type="text/css" href="style/responsive.css">
<link rel="stylesheet" type="text/css" href="style/odometer-theme-default.css">
<!--fonts-->
<link rel="stylesheet" type="text/css" href="fonts/streamline-small/styles.css">
<link rel="stylesheet" type="text/css" href="fonts/streamline-large/styles.css">
<link rel="stylesheet" type="text/css" href="fonts/template/styles.css">
<link rel="stylesheet" type="text/css" href="fonts/social/styles.css">
<!-- favicon -->
<link rel="apple-touch-icon" sizes="180x180" href="/favicon/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon/favicon-16x16.png">
<link rel="manifest" href="/favicon/site.webmanifest">
<link rel="mask-icon" href="/favicon/safari-pinned-tab.svg" color="#d65b5e">
<link rel="shortcut icon" href="/favicon/favicon.ico">
<meta name="apple-mobile-web-app-title" content="CMPD">
<meta name="application-name" content="CMPD">
<meta name="msapplication-TileColor" content="#d65b5e">
<meta name="msapplication-config" content="/favicon/browserconfig.xml">
<meta name="theme-color" content="#ffffff">
</head>
<body class="<?php echo (isset($_COOKIE['re_layout']) && $_COOKIE['re_layout']=="boxed" ? (isset($_COOKIE['re_layout_style']) && $_COOKIE['re_layout_style']!="" ? $_COOKIE['re_layout_style'] . ' ' . $_COOKIE['re_image_overlay'] : 'image-1 overlay') : ''); ?>">
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-PDFRWSF"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<div class="site-container<?php echo ($_COOKIE['re_layout']=="boxed" ? ' boxed' : ''); ?>">
<!--<div class="site-container boxed">-->
<div class="header-top-bar-container clearfix">
<div class="header-top-bar">
<ul class="contact-details clearfix">
<li class="template-clock">
<p style="margin-top: 5.5%">Mon - Fri: 09.00 - 18.00</p>
</li>
<li class="template-phone">
<p>
<a href="tel:+35315314938">01-5314938</a><br>
<a href="tel:+353852047399">085-2047399</a>
</p>
</li>
<li class="template-mail top-icon-button">
<p style="margin-top: 8.5%"><a href="mailto:<EMAIL>" title="Email us"><EMAIL></a></p>
</li>
</ul>
</div>
<a href="#" class="header-toggle template-arrow-up"></a>
</div>
<div class="header-container<?php echo (isset($_COOKIE['re_menu_type']) ? ' ' . $_COOKIE['re_menu_type'] : '');?>">
<!--<div class="header-container sticky">-->
<div class="vertical-align-table column-1-1">
<div class="header clearfix">
<div class="logo vertical-align-cell">
<a href="?page=home"><h1>CMPD<span class="h1s">.IE</span></h1></a>
</div>
<a href="#" class="mobile-menu-switch vertical-align-cell">
<span class="line"></span>
<span class="line"></span>
<span class="line"></span>
</a>
<div class="menu-container clearfix vertical-align-cell">
<?php
require_once('menu.php');
?>
</div>
</div>
</div>
</div><file_sep>/www/consultation.php
<?php
require_once("contact_form/config.php");
?>
<div class="theme-page padding-bottom-66">
<div class="row gray full-width page-header vertical-align-table">
<div class="row full-width padding-top-bottom-50 vertical-align-cell">
<div class="row">
<div class="page-header-left">
<h1>FREE CONSULTATION</h1>
</div>
<div class="page-header-right">
<div class="bread-crumb-container">
<label>You Are Here:</label>
<ul class="bread-crumb">
<li>
<a title="HOME" href="?page=home">
HOME
</a>
</li>
<li class="separator">
/
</li>
<li>
FREE CONSULTATION
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="row margin-top-20">
<div class="column column-2-3">
<p class="description t1 margin-top-0">Interested in a free on-site visit? <br>With our easy-to-use form, you can get started right away.</p>
<p class="description t1">Please add as much information as possible. <br>We will contact you within one business day to arrange a free on-site visit and give you a quotation.</p>
<div class="small no-scroll align-left clearfix page-margin-top">
<form class="contact-form" method="post" action="contact_form/contact_form.php">
<div class="consultation-box consultation-contact clearfix margin-top-10">
<div class="row">
<label>Contact Details</label>
</div>
<div class="row margin-top-20">
<fieldset>
<input class="text-input" name="name" type="text" value="<?php echo _def_name; ?>" placeholder="<?php echo _def_name; ?>">
<input class="text-input" name="email" type="text" value="<?php echo _def_email; ?>" placeholder="<?php echo _def_email; ?>">
<input class="text-input" name="phone" type="text" value="<?php echo _def_phone; ?>" placeholder="<?php echo _def_phone; ?>">
</fieldset>
<fieldset class="margin-top-20">
<textarea name="address" placeholder="<?php echo _def_address; ?>"><?php echo _def_address; ?></textarea>
</fieldset>
<fieldset class="margin-top-20">
<textarea name="message" placeholder="<?php echo _def_message; ?>"><?php echo _def_message; ?></textarea>
</fieldset>
</div>
<div class="row margin-top-30">
<div class="column column-1-2">
<p class="description t1">We do not store any of your details in our database.</p>
</div>
<div id="submitBtn" class="column column-1-2">
<input type="hidden" name="action" value="contact_form">
<input type="submit" name="submit" value="SUBMIT" id="myBtn" class="more active">
</div>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p><b>THANK YOU</b></p>
<p>We will respond within one business day.</p>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<div class="column column-1-3">
<div class="row">
<a href="images/samples/portfolio/img_62.jpg" class="prettyPhoto re-preload">
<img src='images/samples/portfolio/img_62.jpg'>
</a>
</div>
<div class="row margin-top-30">
<a href="images/samples/portfolio/img_48.jpg" class="prettyPhoto re-preload">
<img src="images/samples/portfolio/img_48.jpg">
</a>
</div>
<div class="row margin-top-30">
<a href="images/samples/portfolio/img_51.jpg" class="prettyPhoto re-preload">
<img src="images/samples/portfolio/img_51.jpg">
</a>
</div>
</div>
<div class="row">
<div class="column column-2-3 margin-top-40">
<h4 class="box-header">WHAT YOU GET</h4>
<p class="description t1 margin-top-34">With 15 years of experience and a real focus on customer satisfaction, you can rely on us with peace-of-mind.</p>
<ul class="list margin-top-20">
<li class="template-bullet">We combine quality workmanship, superior knowledge, and low prices to provide you the best possible service.</li>
<li class="template-bullet">We have the experience, personel, and resources to make sure everything is of the highest quality.</li>
<li class="template-bullet">We ensure that every step along the way is pleasant and to be there with you until everything is perfectly in place.</a></li>
<li class="template-bullet">We stay on time and on budget.</li>
<li class="template-bullet">We focus on pure customer satisfaction.</li>
</ul>
</div>
</div>
</div>
</div><file_sep>/www/contact_form/config.php
<?php
define('_to_name', 'CMPD');
define('_to_email', '<EMAIL>');
define('_smtp_host', 'smtp.gmail.com');
define('_smtp_username', '<EMAIL>'); // from
define('_smtp_password', '<PASSWORD>');
define('_smtp_port', '587');
define('_smtp_secure', 'tls'); // ssl or tls
define('_subject_email', 'Customer Support');
define('_def_name', 'Full Name');
define('_def_email', 'Email Address');
define('_def_phone', 'Contact Number');
define('_def_address', 'Full Address');
define('_def_message', 'How can we help you today?');
define('_msg_invalid_data_name', 'Please enter your name.');
define('_msg_invalid_data_email', 'Please enter a valid email address.');
define('_msg_invalid_data_phone', 'Please enter your contact number.');
define('_msg_invalid_data_address', 'Please enter your address.');
define('_msg_invalid_data_message', 'Please enter a description.');
define('_msg_send_error', 'Sorry, we can\'t send this message.');
?><file_sep>/www/contact_form/template.php
<?php
ob_start();
?>
<html>
<head>
</head>
<body>
<div>
<b>Contact Details</b>
<div>Name: <?php echo $values["name"]; ?></div>
<div>Email: <?php echo $values["email"]; ?></div>
<div>Number: <?php echo $values["phone"]; ?></div>
<br>
</div>
<?php if($values["address"]!="NA"):?>
<div>
<b>Address</b>
<div><?php echo nl2br($values["address"]); ?></div>
</div>
<br>
<?php endif; ?>
<div>
<b>Message</b>
<div><?php echo nl2br($values["message"]); ?></div>
</div>
<br>
</body>
</html>
<?php
$content = ob_get_contents();
ob_end_clean();
return($content);
?><file_sep>/www/footer.php
<?php if($_GET["page"]!="contact" && $_GET["page"]!="contact_2"):?>
<div class="row purple full-width padding-top-bottom-30">
<div class="row">
<div class="column column-1-3">
<ul class="contact-details-list">
<li class="sl-small-mail">
<p>Email:<br>
<a id="mailo" href="mailto:<EMAIL>"><EMAIL></a></p>
</li>
</ul>
</div>
<div class="column column-1-3">
<ul class="contact-details-list">
<li class="sl-small-phone">
<p>
<a href="tel:+35315314938">01-5314938</a><br>
<a href="tel:+353852047399">085-2047399</a>
</p>
</li>
</ul>
</div>
<div class="column column-1-3">
<ul class="contact-details-list">
<li class="sl-small-location">
<p style="white-space: nowrap; font-size: 0.9em; position: relative; bottom: 0.5em;">
Bolton Print Centre,<br>Aughrim Lane Industrial Estate,<br>Dublin 7, D07E54F, Ireland.
</p>
</li>
</ul>
</div>
</div>
</div>
<?php endif; ?>
<div class="row gray full-width page-padding-top padding-bottom-50">
<div class="row row-4-4">
<div class="column column-1-4">
<h6 class="box-header">About Us</h6>
<p class="description t1">Founded by <NAME>,<br> CMPD aims to take the stress out of property management by providing professional residential and domestic maintenance services.</p>
</div>
<div class="column column-1-4">
<h6 class="box-header">Our Services</h6>
<ul class="list margin-top-20">
<li class="template-bullet"><h1>Carpentry</h1></li>
<li class="template-bullet">General Maintenance</li>
<li class="template-bullet">Maintenance Contracts</li>
</ul>
</div>
<div class="column column-1-4">
<h6 class="box-header">Categories</h6>
<ul class="taxonomies margin-top-30">
<li><a href="?page=service_carpentry"><h1>CARPENTRY</h1></a></li>
<li><a href="?page=service_carpentry"><h1>ROOFING</h1></a></li>
<li><a href="?page=service_carpentry"><h1>DECKING</h1></a></li>
<li><a href="?page=service_general_maintenance"><h1>PLASTERING</h1></a></li>
<li><a href="?page=service_general_maintenance"><h1>RESIDENTIAL MAINTENANCE</h1></a></li>
<li><a href="?page=service_general_maintenance"><h1>COMMERCIAL MAINTENANCE</h1></a></li>
<li><a href="?page=service_general_maintenance"><h1>BUILDING MAINTENANCE</h1></a></li>
<li><a href="?page=service_carpentry"><h1>ATTIC</h1></a></li>
<li><a href="?page=service_general_maintenance"><h1>GARDEN LANDCAPING</h1></a></li>
<li><a href="?page=service_general_maintenance"><h1>PAINTING</h1></a></li>
<li><a href="?page=service_general_maintenance"><h1>PLUMBING</h1></a></li>
<li><a href="?page=service_maintenance_contracts"><h1>COMPOSITE DECKING</h1></a></li>
</ul>
</div>
<div class="column column-1-4">
<h6 class="box-header">Latest</h6>
<ul class="blog small margin-top-30">
<li>
<a href="?page=service_carpentry" class="post-image">
<img src="images/samples/latest/img_01.jpg" width="90px">
</a>
<div class="post-content">
<a href="?page=service_carpentry">New Carpentry Services</a>
<ul class="post-details">
<li class="date">June 25, <?php echo date("Y");?></li>
</ul>
</div>
</li>
<li>
<a href="?page=service_maintenance_contracts" class="post-image">
<img src="images/samples/latest/img_02.jpg" width="90px">
</a>
<div class="post-content">
<a href="?page=service_maintenance_contracts">Maintenance Contracts</a>
<ul class="post-details">
<li class="date">December 29, <?php echo date("Y")-1;?></li>
</ul>
</div>
</li>
</ul>
</div>
</div>
</div>
<div class="row align-center padding-top-bottom-30">
<span class="copyright">© <?php echo date("Y");?> CMPD | Developed by <a target="_blank" href="http://devcentrehouse.eu">Dev Centre House Ltd.</a></span>
</div>
</div>
<a href="#top" class="scroll-top animated-element template-arrow-up" title="Scroll to top"></a>
<div class="background-overlay"></div>
<!--js-->
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="js/jquery-migrate-1.4.1.min.js"></script>
<!--slider revolution-->
<script type="text/javascript" src="rs-plugin/js/jquery.themepunch.tools.min.js"></script>
<script type="text/javascript" src="rs-plugin/js/jquery.themepunch.revolution.min.js"></script>
<script type="text/javascript" src="js/jquery.ba-bbq.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.11.4.custom.min.js"></script>
<script type="text/javascript" src="js/jquery.ui.touch-punch.min.js"></script>
<script type="text/javascript" src="js/jquery.isotope.min.js"></script>
<script type="text/javascript" src="js/jquery.easing.1.3.min.js"></script>
<script type="text/javascript" src="js/jquery.carouFredSel-6.2.1-packed.js"></script>
<script type="text/javascript" src="js/jquery.touchSwipe.min.js"></script>
<script type="text/javascript" src="js/jquery.transit.min.js"></script>
<script type="text/javascript" src="js/jquery.hint.min.js"></script>
<script type="text/javascript" src="js/jquery.costCalculator.min.js"></script>
<script type="text/javascript" src="js/jquery.parallax.min.js"></script>
<script type="text/javascript" src="js/jquery.prettyPhoto.js"></script>
<script type="text/javascript" src="js/jquery.qtip.min.js"></script>
<script type="text/javascript" src="js/jquery.blockUI.min.js"></script>
<script type="text/javascript" src="//maps.google.com/maps/api/js?key="></script>
<script type="text/javascript" src="js/main.js"></script>
<script type="text/javascript" src="js/odometer.min.js"></script>
<?php
//require_once("style_selector/style_selector.php");
?>
</body>
</html><file_sep>/www/contact.php
<?php
require_once("contact_form/config.php");
?>
<div class="theme-page padding-bottom-66">
<div class="clearfix">
<div class="row full-width">
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2381.4256194938325!2d-6.290851284300263!3d53.35353737998057!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x48670d1fb8e04813%3A0x6712b3384c8772f2!2sCMPD!5e0!3m2!1sen!2sie!4v1537265976773" height="450" frameborder="0" style="border:0; width: 100%;" allowfullscreen></iframe>
</div>
<div class="row page-margin-top">
<div class="column column-1-3">
<ul class="features-list">
<li class="sl-small-clock">
<p>Monday - Friday: 09.00 - 18.00</p>
</li>
</ul>
</div>
<div class="column column-1-3">
<ul class="features-list">
<li class="sl-small-phone">
<p>
<a href="tel:+35315314938">01-5314938</a><br>
<a href="tel:+353852047399">085-2047399</a>
</p>
</li>
</ul>
</div>
<div class="column column-1-3">
<ul class="features-list">
<li class="sl-small-location">
<p style="white-space: nowrap; font-size: 0.9em; position: relative; bottom: 0.75em;">
Bolton Print Centre,<br>Aughrim Lane Industrial Estate,<br>Dublin 7, D07E54F, Ireland.
</p>
</li>
</ul>
</div>
</div>
<div class="row page-margin-top">
<form class="contact-form" id="contact-form" method="post" action="contact_form/contact_form.php">
<div class="row">
<fieldset class="column column-1-2">
<input class="text-input" name="name" type="text" value="<?php echo _def_name; ?>" placeholder="<?php echo _def_name; ?>">
<input class="text-input" name="email" type="text" value="<?php echo _def_email; ?>" placeholder="<?php echo _def_email; ?>">
<input class="text-input" name="phone" type="text" value="<?php echo _def_phone; ?>" placeholder="<?php echo _def_phone; ?>">
<input class="text-input" name="address" type="hidden" value="NA" placeholder="NA">
</fieldset>
<fieldset class="column column-1-2">
<textarea name="message" placeholder="<?php echo _def_message; ?>"><?php echo _def_message; ?></textarea>
</fieldset>
</div>
<div class="row margin-top-30">
<div class="column column-1-2">
<p class="description t1">We do not store any of your details in our database.</p>
</div>
<div class="column column-1-2 align-right">
<input type="hidden" name="action" value="contact_form" />
<input id="myBtn" type="submit" name="submit" value="SEND MESSAGE" class="more active">
</div>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p><b>THANK YOU</b></p>
<p>We will respond within one business day.</p>
</div>
</div>
</div>
</form>
</div>
</div>
</div><file_sep>/www/menu.php
<nav>
<ul class="sf-menu">
<li <?php echo ($_GET["page"]=="" || $_GET["page"]=="home" ? " class='selected'" : ""); ?>>
<a href="?page=home">
HOME
</a>
</li>
<li <?php echo ($_GET["page"]=="services" || $_GET["page"]=="service_carpentry" || $_GET["page"]=="service_general_maintenance" || $_GET["page"]=="service_maintenance_contracts" ? " class='selected'" : ""); ?>>
<a href="?page=service_carpentry" title="View our services">
SERVICES
</a>
<ul>
<li <?php echo ($_GET["page"]=="service_carpentry" ? " class='selected'" : ""); ?>>
<a href="?page=service_carpentry">
Carpentry
</a>
</li>
<li <?php echo ($_GET["page"]=="service_general_maintenance" ? " class='selected'" : ""); ?>>
<a href="?page=service_general_maintenance">
General Maintenance
</a>
</li>
<li <?php echo ($_GET["page"]=="service_maintenance_contracts" ? " class='selected'" : ""); ?>>
<a href="?page=service_maintenance_contracts">
Maintenance Contracts
</a>
</li>
</ul>
</li>
<li <?php echo ($_GET["page"]=="portfolio" ? " class='selected'" : ""); ?>>
<a href="?page=portfolio" title="View our portfolio">
PORTFOLIO
</a>
</li>
<li <?php echo ($_GET["page"]=="consultation" ? " class='selected'" : ""); ?>>
<a href="?page=consultation" title="Request a free consultation">
FREE CONSULTATION
</a>
</li>
<li class="left-flyout<?php echo ($_GET["page"]=="contact" ? " selected" : ""); ?>">
<a href="?page=contact" title="Get in contact with us">
CONTACT US
</a>
</li>
</ul>
</nav>
<div class="mobile-menu-container">
<div class="mobile-menu-divider"></div>
<nav>
<ul class="mobile-menu collapsible-mobile-submenus">
<li <?php echo ($_GET["page"]=="" || $_GET["page"]=="home" ? " class='selected'" : ""); ?>>
<a href="?page=home">
HOME
</a>
</li>
<li <?php echo ($_GET["page"]=="services" || $_GET["page"]=="service_carpentry" || $_GET["page"]=="service_general_maintenance" || $_GET["page"]=="service_maintenance_contracts" ? " class='selected'" : ""); ?>>
<a href="?page=service_carpentry" title="View our services">
SERVICES
</a>
</li>
<li <?php echo ($_GET["page"]=="portfolio" ? " class='selected'" : ""); ?>>
<a href="?page=portfolio" title="View our portfolio">
PORTFOLIO
</a>
</li>
<li <?php echo ($_GET["page"]=="consultation" ? " class='selected'" : ""); ?>>
<a href="?page=consultation" title="Request a free consultation">
FREE CONSULTATION
</a>
</li>
<li <?php echo ($_GET["page"]=="contact" || $_GET["page"]=="contact_2" ? " class='selected'" : ""); ?>>
<a href="?page=contact" title="Get in contact with us">
CONTACT US
</a>
</li>
</ul>
</nav>
</div>
|
84fbc7cdbb20dc6920be43fe32f1591ccfad0896
|
[
"PHP"
] | 8
|
PHP
|
DevCenterHouse/cmpd.ie
|
b77cd6561840d52ade82f1cbc14da2bca468a6da
|
c32c73708772a277f53523c0ee3314f69ef3445d
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python2.7
import urllib
from bs4 import BeautifulSoup
from datetime import datetime
def send_email(user, pwd, recipient, subject, body):
import smtplib
gmail_user = user
gmail_pwd = pwd
FROM = user
TO = recipient if type(recipient) is list else [recipient]
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
server_ssl = smtplib.SMTP_SSL("smtp.gmail.com", 465)
server_ssl.ehlo() # optional, called by login()
server_ssl.login(gmail_user, gmail_pwd)
server_ssl.sendmail(FROM, TO, message)
server_ssl.close()
url = 'XXX'
sock = urllib.urlopen(url)
html_page = sock.read()
sock.close()
soup_page = BeautifulSoup(html_page, 'html.parser')
new_entry = soup_page.findAll("div", { "class" : "entry unvoted" })[1]
print('NEW ENTRY')
print(new_entry)
post = new_entry.find("div", { "class" : "md" }).p.string
print('NEW POST')
print(post)
time = new_entry.find('time')['datetime']
print('TIME')
print(time)
with open('time_saved.txt', 'r') as time_saved_file:
time_saved=time_saved_file.read()
if(time != time_saved):
send_email('XXX', 'XXX', 'XXX', 'XXX', post)
else:
print('NO NEW POST')
with open("time_saved.txt", "w") as time_saved_file:
time_saved_file.write(time)
|
ea47aab23aaefdfe7ae8afaa68e77c0b026a3247
|
[
"Python"
] | 1
|
Python
|
FischerLouis/Reddit_notification
|
6e3fc0513c42760bfb16ae81d756080bb97ab124
|
c203a44bae05631b631f83c850dd7133a27d298d
|
refs/heads/master
|
<file_sep>#The purpose of this file is to create a test set based on the 2016 season of IPL. This is drawing from the 2016 ipl team stats R script so run that one first.
rcb_bat <- read.csv("rcb2016bat.csv", stringsAsFactors = FALSE)
rcb_bat$Team <- 'RCB'
rcb_bat$Year <- 2016
playoff16 <- rcb_bat[c(1),c(19:23)]
playoff16 <- cbind(rcb_bat[c(1),c(17)], playoff16)
colnames(playoff16)[1] <- 'batting.rpo'
colnames(playoff16)[2] <- 'batting.average'
colnames(playoff16)[3] <- 'fifty.percent'
colnames(playoff16)[4] <- 'boundary.percent'
rcb_bowl <- read.csv("rcb2016bowl.csv", stringsAsFactors = FALSE)
rcb_bowl$Team <- 'RCB'
rcb_bowl$Year <- 2016
playoff16 <- cbind(rcb_bowl[c(1),c(16,17)], playoff16)
colnames(playoff16)[1] <- 'bowling.rpo'
colnames(playoff16)[2] <- 'bowling.sr'
# playoff16 <- playoff16[ ,c(1,2,3,4,7,8,9,10)]
-----------
mi_bat <- read.csv("mi2016bat.csv", stringsAsFactors = FALSE)
mi_bat$Team <- 'MI'
mi_bat$Year <- 2016
mi16 <- mi_bat[c(1), c(19:23)]
mi16 <- cbind(mi_bat[c(1),c(17)], mi16)
colnames(mi16)[1] <- 'batting.rpo'
colnames(mi16)[2] <- 'batting.average'
colnames(mi16)[3] <- 'fifty.percent'
colnames(mi16)[4] <- 'boundary.percent'
mi_bowl <- read.csv("mi2016bowl.csv", stringsAsFactors = FALSE)
mi_bowl$Team <- 'MI'
mi_bowl$Year <- 2016
mi16 <- cbind(mi_bowl[c(1),c(16,17)], mi16)
colnames(mi16)[1] <- 'bowling.rpo'
colnames(mi16)[2] <- 'bowling.sr'
colnames(mi16)[3] <- 'batting.rpo'
colnames(mi16)[4] <- 'batting.average'
colnames(mi16)[5] <- 'fifty.percent'
colnames(mi16)[6] <- 'boundary.percent'
playoff16 <- rbind(playoff16,mi16)
# playoff16 <- playoff16[ ,c(1,2,3,4,7,8,9,10)]
# KXIP
kxip_bat <- read.csv("kxip2016bat.csv", stringsAsFactors = FALSE)
kxip_bat$Team <- 'KXIP'
kxip_bat$Year <- 2016
kxip16 <- kxip_bat[c(1), c(19:23)]
kxip16 <- cbind(kxip_bat[c(1),c(17)], kxip16)
colnames(kxip16)[1] <- 'batting.rpo'
colnames(kxip16)[2] <- 'batting.average'
colnames(kxip16)[3] <- 'fifty.percent'
colnames(kxip16)[4] <- 'boundary.percent'
kxip_bowl <- read.csv("kxip2016bowl.csv", stringsAsFactors = FALSE)
kxip_bowl$Team <- 'kxip'
kxip_bowl$Year <- 2016
kxip16 <- cbind(kxip_bowl[c(1),c(16,17)], kxip16)
colnames(kxip16)[1] <- 'bowling.rpo'
colnames(kxip16)[2] <- 'bowling.sr'
colnames(kxip16)[3] <- 'batting.rpo'
colnames(kxip16)[4] <- 'batting.average'
colnames(kxip16)[5] <- 'fifty.percent'
colnames(kxip16)[6] <- 'boundary.percent'
playoff16 <- rbind(playoff16,kxip16)
# playoff16 <- playoff16[c(1,4,5),]
#SRH
srh_bat <- read.csv("srh2016bat.csv", stringsAsFactors = FALSE)
srh_bat$Team <- 'srh'
srh_bat$Year <- 2016
srh16 <- srh_bat[c(1), c(19:23)]
srh16 <- cbind(srh_bat[c(1),c(17)], srh16)
colnames(srh16)[1] <- 'batting.rpo'
colnames(srh16)[2] <- 'batting.average'
colnames(srh16)[3] <- 'fifty.percent'
colnames(srh16)[4] <- 'boundary.percent'
srh_bowl <- read.csv("srh2016bowl.csv", stringsAsFactors = FALSE)
srh_bowl$Team <- 'srh'
srh_bowl$Year <- 2016
srh16 <- cbind(srh_bowl[c(1),c(16,17)], srh16)
colnames(srh16)[1] <- 'bowling.rpo'
colnames(srh16)[2] <- 'bowling.sr'
colnames(srh16)[3] <- 'batting.rpo'
colnames(srh16)[4] <- 'batting.average'
colnames(srh16)[5] <- 'fifty.percent'
colnames(srh16)[6] <- 'boundary.percent'
playoff16 <- rbind(playoff16,srh16)
#RP
rp_bat <- read.csv("rp2016bat.csv", stringsAsFactors = FALSE)
rp_bat$Team <- 'rp'
rp_bat$Year <- 2016
rp16 <- rp_bat[c(1), c(19:23)]
rp16 <- cbind(rp_bat[c(1),c(17)], rp16)
colnames(rp16)[1] <- 'batting.rpo'
colnames(rp16)[2] <- 'batting.average'
colnames(rp16)[3] <- 'fifty.percent'
colnames(rp16)[4] <- 'boundary.percent'
rp_bowl <- read.csv("rp2016bowl.csv", stringsAsFactors = FALSE)
rp_bowl$Team <- 'rp'
rp_bowl$Year <- 2016
rp16 <- cbind(rp_bowl[c(1),c(16,17)], rp16)
colnames(rp16)[1] <- 'bowling.rpo'
colnames(rp16)[2] <- 'bowling.sr'
colnames(rp16)[3] <- 'batting.rpo'
colnames(rp16)[4] <- 'batting.average'
colnames(rp16)[5] <- 'fifty.percent'
colnames(rp16)[6] <- 'boundary.percent'
playoff16 <- rbind(playoff16,rp16)
#GL
gl_bat <- read.csv("gl2016bat.csv", stringsAsFactors = FALSE)
gl_bat$Team <- 'gl'
gl_bat$Year <- 2016
gl16 <- gl_bat[c(1), c(19:23)]
gl16 <- cbind(gl_bat[c(1),c(17)], gl16)
colnames(gl16)[1] <- 'batting.rpo'
colnames(gl16)[2] <- 'batting.average'
colnames(gl16)[3] <- 'fifty.percent'
colnames(gl16)[4] <- 'boundary.percent'
gl_bowl <- read.csv("gl2016bowl.csv", stringsAsFactors = FALSE)
gl_bowl$Team <- 'gl'
gl_bowl$Year <- 2016
gl16 <- cbind(gl_bowl[c(1),c(16,17)], gl16)
colnames(gl16)[1] <- 'bowling.rpo'
colnames(gl16)[2] <- 'bowling.sr'
colnames(gl16)[3] <- 'batting.rpo'
colnames(gl16)[4] <- 'batting.average'
colnames(gl16)[5] <- 'fifty.percent'
colnames(gl16)[6] <- 'boundary.percent'
playoff16 <- rbind(playoff16,gl16)
#KKR
kkr_bat <- read.csv("kkr2016bat.csv", stringsAsFactors = FALSE)
kkr_bat$Team <- 'kkr'
kkr_bat$Year <- 2016
kkr16 <- kkr_bat[c(1), c(19:23)]
kkr16 <- cbind(kkr_bat[c(1),c(17)], kkr16)
colnames(kkr16)[1] <- 'batting.rpo'
colnames(kkr16)[2] <- 'batting.average'
colnames(kkr16)[3] <- 'fifty.percent'
colnames(kkr16)[4] <- 'boundary.percent'
kkr_bowl <- read.csv("kkr2016bowl.csv", stringsAsFactors = FALSE)
kkr_bowl$Team <- 'kkr'
kkr_bowl$Year <- 2016
kkr16 <- cbind(kkr_bowl[c(1),c(16,17)], kkr16)
colnames(kkr16)[1] <- 'bowling.rpo'
colnames(kkr16)[2] <- 'bowling.sr'
colnames(kkr16)[3] <- 'batting.rpo'
colnames(kkr16)[4] <- 'batting.average'
colnames(kkr16)[5] <- 'fifty.percent'
colnames(kkr16)[6] <- 'boundary.percent'
playoff16 <- rbind(playoff16,kkr16)
#DD
dd_bat <- read.csv("dd2016bat.csv", stringsAsFactors = FALSE)
dd_bat$Team <- 'dd'
dd_bat$Year <- 2016
dd16 <- dd_bat[c(1), c(19:23)]
dd16 <- cbind(dd_bat[c(1),c(17)], dd16)
colnames(dd16)[1] <- 'batting.rpo'
colnames(dd16)[2] <- 'batting.average'
colnames(dd16)[3] <- 'fifty.percent'
colnames(dd16)[4] <- 'boundary.percent'
dd_bowl <- read.csv("dd2016bowl.csv", stringsAsFactors = FALSE)
dd_bowl$Team <- 'dd'
dd_bowl$Year <- 2016
dd16 <- cbind(dd_bowl[c(1),c(16,17)], dd16)
colnames(dd16)[1] <- 'bowling.rpo'
colnames(dd16)[2] <- 'bowling.sr'
colnames(dd16)[3] <- 'batting.rpo'
colnames(dd16)[4] <- 'batting.average'
colnames(dd16)[5] <- 'fifty.percent'
colnames(dd16)[6] <- 'boundary.percent'
playoff16 <- rbind(playoff16,dd16)
playoff16$First.five <- c(2,2,1,1,1,4,4,3)
playoff16$First.Seven <- c(2,3,2,4,2,6,4,5)
playoff16$NRR <- c(0.932,-0.146,-0.646,0.245,0.015,-0.374,0.106,-0.155)
playoff16$rpo.diff <- playoff16$batting.rpo - playoff16$bowling.rpo
<file_sep># Read in playoff and playoff15 csv files. They are created the same way we created the 2016 test set.
playoff <- read.csv("playoff.csv")
playoff15<- read.csv("playoff15.csv")
playoff15$rpo.diff <- playoff15$batting.rpo - playoff15$bowling.rpo
#playofftill15 is our training set now
playofftill15 <- rbind(playoff[,c(1:13)], playoff15)
playoff15$Playoffs <- c(1,0,1,0,1,1,0,0)
# playoffupdate <- read.csv("playoffupdate.csv")
str(playoff)
playoff$First.five <- as.numeric(playoff$First.five)
playoff$First.Seven <- as.numeric(playoff$First.Seven)
Log <- glm(Playoffs ~ fifty.percent + batting.rpo + bowling.rpo + bowling.sr + First.five + First.Seven , data= playofftill15, family = "binomial" )
summary(Log)
Log2 <- glm(Playoffs ~ fifty.percent + batting.rpo + bowling.rpo + bowling.sr + First.Seven + NRR, data= playofftill15, family = "binomial" )
summary(Log2)
Log3 <- glm(Playoffs ~ fifty.percent + batting.rpo + bowling.rpo + bowling.sr + First.Seven , data= playofftill15, family = "binomial" )
summary(Log3)
library(randomForest)
Rf <- randomForest(as.factor(Playoffs) ~ fifty.percent + batting.rpo + bowling.rpo + bowling.sr + First.five + First.Seven , data= playofftill15, method="class" )
varImpPlot(Rf)
predictRf <- predict(Rf, type="prob")
predictRf[,2]
RFtrain <- cbind(playofftill15$Team, playofftill15$Year ,playofftill15$Playoffs, predictRf[,2])
table(predictRf[,2]>0.5, playoff$Playoffs)
TeamprobsRf <- data.frame(Team = playofftill15$Team , Year = playofftill15$Year ,Prob = predictRf[,2], Result = playofftill15$Playoffs)
TeamprobsRf
library(rpart.plot)
library(rpart)
CART <- rpart(Playoffs ~ fifty.percent + batting.rpo + bowling.rpo + bowling.sr + First.five + First.Seven , data= playofftill15, method="class" , minbucket = 1)
prp(CART)
predictCART <- predict(CART, type="prob")
predictCART[,2]
predictCARTTest <- predict(CART, newdata= playoff16, type="prob")
predictCARTTest[,2]
predictRfTest <- predict(Rf, newdata= playoff16, type="prob")
predictRfTest[,2]
RFtest <- data.frame(playoff16$Team, playoff16$Year , Prob= predictRfTest[,2])
library(e1071)
SVMmodel <- svm( Playoffs ~ fifty.percent + batting.rpo + bowling.rpo + bowling.sr + First.five + First.Seven , data= playofftill15)
summary(SVMmodel)
predictSVM <- predict(SVMmodel, type="prob")
playofftill15$Team
SVMTrain <- data.frame(playofftill15$Team, playofftill15$Year ,playofftill15$Playoffs, predictSVM)
predictSVMTest <- predict(SVMmodel, newdata= playoff16, type="prob")
predictSVMTest
SVMTest <- data.frame(playoff16$Team, playoff16$Year , predictSVMTest)
predictLog <- predict(Log, type= "response")
predictLog
predictLog2 <- predict(Log2, type= "response")
predictLog2
predictLog3 <- predict(Log3, type= "response")
predictLog3
TeamprobsLR <- data.frame(Team = playofftill15$Team , Year = playofftill15$Year ,Prob = predictLog3, Result = playofftill15$Playoffs)
TeamprobsLR
predictLogTest <- predict(Log, newdata= playoff16, type= "response")
predictLogTest
predictLogTest2 <- predict(Log2, newdata= playoff16, type= "response")
predictLogTest2
predictLogTest3 <- predict(Log3, newdata= playoffupdate, type= "response")
predictLogTest3
<file_sep># IPL-16-team-stats and playoff models
ipl 16 stats from cricinfo
Hi all, I have used the XML package here to pull stats from cricinfo. Here are the steps to run a playoff model for the IPL
1. Various stats are computed at a team level - 2016 ipl stats R script
The purpose behind it is to see which factors lead to team success.
We will put these team level stats into a model to check significant factors.
2. Training set is created - playoff16 R script
3. Test set is read in alongwith model creation- playoff R script
<file_sep>library(XML)
#Rising Pune stats
url1="http://stats.espncricinfo.com/indian-premier-league-2016/engine/records/averages/batting_bowling_by_team.html?id=11001;team=5843;type=tournament"
tables=readHTMLTable(url1)
rp2016bat<- tables$"Rising Pune Supergiants batting averages"
rp2016bowl<- tables$"Rising Pune Supergiants bowling averages"
str(rp2016bat)
rp2016bowl$TeamEconomy = sum(as.numeric(levels(rp2016bowl$Runs))[rp2016bowl$Runs],na.rm=TRUE) / sum(as.numeric(levels(rp2016bowl$Overs))[rp2016bowl$Overs],na.rm=TRUE)
rp2016bowl$TeamSR = round(sum(as.numeric(levels(rp2016bowl$Overs))[rp2016bowl$Overs],na.rm=TRUE))*6 / sum(as.numeric(levels(rp2016bowl$Wkts))[rp2016bowl$Wkts],na.rm=TRUE)
rp2016bowl$50 <-make.names(rp2016bowl$50 )
rp2016bat$RPB = sum(as.numeric(levels(rp2016bat$Runs))[rp2016bat$Runs],na.rm=TRUE) / sum(as.numeric(levels(rp2016bat$BF))[rp2016bat$BF],na.rm=TRUE)
rp2016bat$TeamSR = rp2016bat$RPB*100
rp2016bat$TeamRPO = rp2016bat$RPB *6
rp2016bat$Outs= as.numeric(levels(rp2016bat$Inns)[rp2016bat$Inns],na.rm=TRUE)-as.numeric(levels(rp2016bat$NO)[rp2016bat$NO],na.rm=TRUE)
rp2016bat$Avg = sum(as.numeric(levels(rp2016bat$Runs))[rp2016bat$Runs],na.rm=TRUE) / sum(rp2016bat$Outs,na.rm=TRUE)
names(rp2016bat)[10] <- "Hundreds"
names(rp2016bat)[11] <- "Fifties"
names(rp2016bat)[13] <- "Fours"
names(rp2016bat)[14] <- "Sixes"
rp2016bat$Fiftypercent = (2* sum(as.numeric(levels(rp2016bat$Hundreds))[rp2016bat$Hundreds],na.rm=TRUE) + sum(as.numeric(levels(rp2016bat$Fifties))[rp2016bat$Fifties],na.rm=TRUE))/ sum(as.numeric(levels(rp2016bat$Inns))[rp2016bat$Inns],na.rm=TRUE)
rp2016bat$Boundpercent= (sum(as.numeric(levels(rp2016bat$Fours))[rp2016bat$Fours],na.rm=TRUE) + sum(as.numeric(levels(rp2016bat$Sixes))[rp2016bat$Sixes],na.rm=TRUE))/ sum(as.numeric(levels(rp2016bat$BF))[rp2016bat$BF],na.rm=TRUE)
write.csv(rp2016bat, file="rp2016bat.csv",row.names=FALSE)
write.csv(rp2016bowl, file="rp2016bowl.csv",row.names=FALSE)
#Mumbai Indians Stats
url2 = "http://stats.espncricinfo.com/indian-premier-league-2016/engine/records/averages/batting_bowling_by_team.html?id=11001;team=4346;type=tournament"
tables=readHTMLTable(url2)
#tables
mi2016bat<- tables$"Mumbai Indians batting averages"
mi2016bowl<- tables$"Mumbai Indians bowling averages"
mi2016bowl$TeamEconomy = sum(as.numeric(levels(mi2016bowl$Runs))[mi2016bowl$Runs],na.rm=TRUE) / sum(as.numeric(levels(mi2016bowl$Overs))[mi2016bowl$Overs],na.rm=TRUE)
mi2016bowl$TeamSR = round(sum(as.numeric(levels(mi2016bowl$Overs))[mi2016bowl$Overs],na.rm=TRUE))*6 / sum(as.numeric(levels(mi2016bowl$Wkts))[mi2016bowl$Wkts],na.rm=TRUE)
mi2016bat$RPB = sum(as.numeric(levels(mi2016bat$Runs))[mi2016bat$Runs],na.rm=TRUE) / sum(as.numeric(levels(mi2016bat$BF))[mi2016bat$BF],na.rm=TRUE)
mi2016bat$TeamSR = mi2016bat$RPB*100
mi2016bat$TeamRPO = mi2016bat$RPB *6
mi2016bat$Outs= as.numeric(levels(mi2016bat$Inns)[mi2016bat$Inns],na.rm=TRUE)-as.numeric(levels(mi2016bat$NO)[mi2016bat$NO],na.rm=TRUE)
mi2016bat$Avg = sum(as.numeric(levels(mi2016bat$Runs))[mi2016bat$Runs],na.rm=TRUE) / sum(mi2016bat$Outs,na.rm=TRUE)
names(mi2016bat)[10] <- "Hundreds"
names(mi2016bat)[11] <- "Fifties"
names(mi2016bat)[13] <- "Fours"
names(mi2016bat)[14] <- "Sixes"
mi2016bat$Fiftypercent = (2* sum(as.numeric(levels(mi2016bat$Hundreds))[mi2016bat$Hundreds],na.rm=TRUE) + sum(as.numeric(levels(mi2016bat$Fifties))[mi2016bat$Fifties],na.rm=TRUE))/ sum(as.numeric(levels(mi2016bat$Inns))[mi2016bat$Inns],na.rm=TRUE)
mi2016bat$Boundpercent= (sum(as.numeric(levels(mi2016bat$Fours))[mi2016bat$Fours],na.rm=TRUE) + sum(as.numeric(levels(mi2016bat$Sixes))[mi2016bat$Sixes],na.rm=TRUE))/ sum(as.numeric(levels(mi2016bat$BF))[mi2016bat$BF],na.rm=TRUE)
write.csv(mi2016bat, file="mi2016bat.csv",row.names=FALSE)
write.csv(mi2016bowl, file="mi2016bowl.csv",row.names=FALSE)
#KKR stats
url3 = "http://stats.espncricinfo.com/indian-premier-league-2016/engine/records/averages/batting_bowling_by_team.html?id=11001;team=4341;type=tournament"
tables=readHTMLTable(url3)
#tables
kkr2016bat<- tables$"Kolkata Knight Riders batting averages"
kkr2016bowl<- tables$"Kolkata Knight Riders bowling averages"
kkr2016bowl$TeamEconomy = sum(as.numeric(levels(kkr2016bowl$Runs))[kkr2016bowl$Runs],na.rm=TRUE) / sum(as.numeric(levels(kkr2016bowl$Overs))[kkr2016bowl$Overs],na.rm=TRUE)
kkr2016bowl$TeamSR = round(sum(as.numeric(levels(kkr2016bowl$Overs))[kkr2016bowl$Overs],na.rm=TRUE))*6 / sum(as.numeric(levels(kkr2016bowl$Wkts))[kkr2016bowl$Wkts],na.rm=TRUE)
kkr2016bat$RPB = sum(as.numeric(levels(kkr2016bat$Runs))[kkr2016bat$Runs],na.rm=TRUE) / sum(as.numeric(levels(kkr2016bat$BF))[kkr2016bat$BF],na.rm=TRUE)
kkr2016bat$TeamSR = kkr2016bat$RPB*100
kkr2016bat$TeamRPO = kkr2016bat$RPB *6
kkr2016bat$Outs= as.numeric(levels(kkr2016bat$Inns)[kkr2016bat$Inns],na.rm=TRUE)-as.numeric(levels(kkr2016bat$NO)[kkr2016bat$NO],na.rm=TRUE)
kkr2016bat$Avg = sum(as.numeric(levels(kkr2016bat$Runs))[kkr2016bat$Runs],na.rm=TRUE) / sum(kkr2016bat$Outs,na.rm=TRUE)
names(kkr2016bat)[10] <- "Hundreds"
names(kkr2016bat)[11] <- "Fifties"
names(kkr2016bat)[13] <- "Fours"
names(kkr2016bat)[14] <- "Sixes"
kkr2016bat$Fiftypercent = (2* sum(as.numeric(levels(kkr2016bat$Hundreds))[kkr2016bat$Hundreds],na.rm=TRUE) + sum(as.numeric(levels(kkr2016bat$Fifties))[kkr2016bat$Fifties],na.rm=TRUE))/ sum(as.numeric(levels(kkr2016bat$Inns))[kkr2016bat$Inns],na.rm=TRUE)
kkr2016bat$Boundpercent= (sum(as.numeric(levels(kkr2016bat$Fours))[kkr2016bat$Fours],na.rm=TRUE) + sum(as.numeric(levels(kkr2016bat$Sixes))[kkr2016bat$Sixes],na.rm=TRUE))/ sum(as.numeric(levels(kkr2016bat$BF))[kkr2016bat$BF],na.rm=TRUE)
write.csv(kkr2016bat, file="kkr2016bat.csv",row.names=FALSE)
write.csv(kkr2016bowl, file="kkr2016bowl.csv",row.names=FALSE)
# DD stats
url4 = "http://stats.espncricinfo.com/indian-premier-league-2016/engine/records/averages/batting_bowling_by_team.html?id=11001;team=4344;type=tournament"
tables=readHTMLTable(url4)
#tables
dd2016bat<- tables$"Delhi Daredevils batting averages"
dd2016bowl<- tables$"Delhi Daredevils bowling averages"
dd2016bowl$TeamEconomy = sum(as.numeric(levels(dd2016bowl$Runs))[dd2016bowl$Runs],na.rm=TRUE) / sum(as.numeric(levels(dd2016bowl$Overs))[dd2016bowl$Overs],na.rm=TRUE)
dd2016bowl$TeamSR = round(sum(as.numeric(levels(dd2016bowl$Overs))[dd2016bowl$Overs],na.rm=TRUE))*6 / sum(as.numeric(levels(dd2016bowl$Wkts))[dd2016bowl$Wkts],na.rm=TRUE)
dd2016bat$RPB = sum(as.numeric(levels(dd2016bat$Runs))[dd2016bat$Runs],na.rm=TRUE) / sum(as.numeric(levels(dd2016bat$BF))[dd2016bat$BF],na.rm=TRUE)
dd2016bat$TeamSR = dd2016bat$RPB*100
dd2016bat$TeamRPO = dd2016bat$RPB *6
dd2016bat$Outs= as.numeric(levels(dd2016bat$Inns)[dd2016bat$Inns],na.rm=TRUE)-as.numeric(levels(dd2016bat$NO)[dd2016bat$NO],na.rm=TRUE)
dd2016bat$Avg = sum(as.numeric(levels(dd2016bat$Runs))[dd2016bat$Runs],na.rm=TRUE) / sum(dd2016bat$Outs,na.rm=TRUE)
names(dd2016bat)[10] <- "Hundreds"
names(dd2016bat)[11] <- "Fifties"
names(dd2016bat)[13] <- "Fours"
names(dd2016bat)[14] <- "Sixes"
dd2016bat$Fiftypercent = (2* sum(as.numeric(levels(dd2016bat$Hundreds))[dd2016bat$Hundreds],na.rm=TRUE) + sum(as.numeric(levels(dd2016bat$Fifties))[dd2016bat$Fifties],na.rm=TRUE))/ sum(as.numeric(levels(dd2016bat$Inns))[dd2016bat$Inns],na.rm=TRUE)
dd2016bat$Boundpercent= (sum(as.numeric(levels(dd2016bat$Fours))[dd2016bat$Fours],na.rm=TRUE) + sum(as.numeric(levels(dd2016bat$Sixes))[dd2016bat$Sixes],na.rm=TRUE))/ sum(as.numeric(levels(dd2016bat$BF))[dd2016bat$BF],na.rm=TRUE)
write.csv(dd2016bat, file="dd2016bat.csv",row.names=FALSE)
write.csv(dd2016bowl, file="dd2016bowl.csv",row.names=FALSE)
# gl stats
url5 = "http://stats.espncricinfo.com/indian-premier-league-2016/engine/records/averages/batting_bowling_by_team.html?id=11001;team=5845;type=tournament"
tables=readHTMLTable(url5)
#tables
gl2016bat<- tables$"Gujarat Lions batting averages"
gl2016bowl<- tables$"Gujarat Lions bowling averages"
gl2016bowl$TeamEconomy = sum(as.numeric(levels(gl2016bowl$Runs))[gl2016bowl$Runs],na.rm=TRUE) / sum(as.numeric(levels(gl2016bowl$Overs))[gl2016bowl$Overs],na.rm=TRUE)
gl2016bowl$TeamSR = round(sum(as.numeric(levels(gl2016bowl$Overs))[gl2016bowl$Overs],na.rm=TRUE))*6 / sum(as.numeric(levels(gl2016bowl$Wkts))[gl2016bowl$Wkts],na.rm=TRUE)
gl2016bat$RPB = sum(as.numeric(levels(gl2016bat$Runs))[gl2016bat$Runs],na.rm=TRUE) / sum(as.numeric(levels(gl2016bat$BF))[gl2016bat$BF],na.rm=TRUE)
gl2016bat$TeamSR = gl2016bat$RPB*100
gl2016bat$TeamRPO = gl2016bat$RPB *6
gl2016bat$Outs= as.numeric(levels(gl2016bat$Inns)[gl2016bat$Inns],na.rm=TRUE)-as.numeric(levels(gl2016bat$NO)[gl2016bat$NO],na.rm=TRUE)
gl2016bat$Avg = sum(as.numeric(levels(gl2016bat$Runs))[gl2016bat$Runs],na.rm=TRUE) / sum(gl2016bat$Outs,na.rm=TRUE)
names(gl2016bat)[10] <- "Hundreds"
names(gl2016bat)[11] <- "Fifties"
names(gl2016bat)[13] <- "Fours"
names(gl2016bat)[14] <- "Sixes"
gl2016bat$Fiftypercent = (2* sum(as.numeric(levels(gl2016bat$Hundreds))[gl2016bat$Hundreds],na.rm=TRUE) + sum(as.numeric(levels(gl2016bat$Fifties))[gl2016bat$Fifties],na.rm=TRUE))/ sum(as.numeric(levels(gl2016bat$Inns))[gl2016bat$Inns],na.rm=TRUE)
gl2016bat$Boundpercent= (sum(as.numeric(levels(gl2016bat$Fours))[gl2016bat$Fours],na.rm=TRUE) + sum(as.numeric(levels(gl2016bat$Sixes))[gl2016bat$Sixes],na.rm=TRUE))/ sum(as.numeric(levels(gl2016bat$BF))[gl2016bat$BF],na.rm=TRUE)
write.csv(gl2016bat, file="gl2016bat.csv",row.names=FALSE)
write.csv(gl2016bowl, file="gl2016bowl.csv",row.names=FALSE)
# srh stats
url6 = "http://stats.espncricinfo.com/indian-premier-league-2016/engine/records/averages/batting_bowling_by_team.html?id=11001;team=5143;type=tournament"
tables=readHTMLTable(url6)
#tables
srh2016bat<- tables$"Sunrisers Hyderabad batting averages"
srh2016bowl<- tables$"Sunrisers Hyderabad bowling averages"
srh2016bowl$TeamEconomy = sum(as.numeric(levels(srh2016bowl$Runs))[srh2016bowl$Runs],na.rm=TRUE) / sum(as.numeric(levels(srh2016bowl$Overs))[srh2016bowl$Overs],na.rm=TRUE)
srh2016bowl$TeamSR = round(sum(as.numeric(levels(srh2016bowl$Overs))[srh2016bowl$Overs],na.rm=TRUE))*6 / sum(as.numeric(levels(srh2016bowl$Wkts))[srh2016bowl$Wkts],na.rm=TRUE)
srh2016bat$RPB = sum(as.numeric(levels(srh2016bat$Runs))[srh2016bat$Runs],na.rm=TRUE) / sum(as.numeric(levels(srh2016bat$BF))[srh2016bat$BF],na.rm=TRUE)
srh2016bat$TeamSR = srh2016bat$RPB*100
srh2016bat$TeamRPO = srh2016bat$RPB *6
srh2016bat$Outs= as.numeric(levels(srh2016bat$Inns)[srh2016bat$Inns],na.rm=TRUE)-as.numeric(levels(srh2016bat$NO)[srh2016bat$NO],na.rm=TRUE)
srh2016bat$Avg = sum(as.numeric(levels(srh2016bat$Runs))[srh2016bat$Runs],na.rm=TRUE) / sum(srh2016bat$Outs,na.rm=TRUE)
names(srh2016bat)[10] <- "Hundreds"
names(srh2016bat)[11] <- "Fifties"
names(srh2016bat)[13] <- "Fours"
names(srh2016bat)[14] <- "Sixes"
srh2016bat$Fiftypercent = (2* sum(as.numeric(levels(srh2016bat$Hundreds))[srh2016bat$Hundreds],na.rm=TRUE) + sum(as.numeric(levels(srh2016bat$Fifties))[srh2016bat$Fifties],na.rm=TRUE))/ sum(as.numeric(levels(srh2016bat$Inns))[srh2016bat$Inns],na.rm=TRUE)
srh2016bat$Boundpercent= (sum(as.numeric(levels(srh2016bat$Fours))[srh2016bat$Fours],na.rm=TRUE) + sum(as.numeric(levels(srh2016bat$Sixes))[srh2016bat$Sixes],na.rm=TRUE))/ sum(as.numeric(levels(srh2016bat$BF))[srh2016bat$BF],na.rm=TRUE)
write.csv(srh2016bat, file="srh2016bat.csv",row.names=FALSE)
write.csv(srh2016bowl, file="srh2016bowl.csv",row.names=FALSE)
# kxip stats
url7 = "http://stats.espncricinfo.com/indian-premier-league-2016/engine/records/averages/batting_bowling_by_team.html?id=11001;team=4342;type=tournament"
tables=readHTMLTable(url7)
#tables
kxip2016bat<- tables$"Kings XI Punjab batting averages"
kxip2016bowl<- tables$"Kings XI Punjab bowling averages"
kxip2016bowl$TeamEconomy = sum(as.numeric(levels(kxip2016bowl$Runs))[kxip2016bowl$Runs],na.rm=TRUE) / sum(as.numeric(levels(kxip2016bowl$Overs))[kxip2016bowl$Overs],na.rm=TRUE)
kxip2016bowl$TeamSR = round(sum(as.numeric(levels(kxip2016bowl$Overs))[kxip2016bowl$Overs],na.rm=TRUE))*6 / sum(as.numeric(levels(kxip2016bowl$Wkts))[kxip2016bowl$Wkts],na.rm=TRUE)
kxip2016bat$RPB = sum(as.numeric(levels(kxip2016bat$Runs))[kxip2016bat$Runs],na.rm=TRUE) / sum(as.numeric(levels(kxip2016bat$BF))[kxip2016bat$BF],na.rm=TRUE)
kxip2016bat$TeamSR = kxip2016bat$RPB*100
kxip2016bat$TeamRPO = kxip2016bat$RPB *6
kxip2016bat$Outs= as.numeric(levels(kxip2016bat$Inns)[kxip2016bat$Inns],na.rm=TRUE)-as.numeric(levels(kxip2016bat$NO)[kxip2016bat$NO],na.rm=TRUE)
kxip2016bat$Avg = sum(as.numeric(levels(kxip2016bat$Runs))[kxip2016bat$Runs],na.rm=TRUE) / sum(kxip2016bat$Outs,na.rm=TRUE)
names(kxip2016bat)[10] <- "Hundreds"
names(kxip2016bat)[11] <- "Fifties"
names(kxip2016bat)[13] <- "Fours"
names(kxip2016bat)[14] <- "Sixes"
kxip2016bat$Fiftypercent = (2* sum(as.numeric(levels(kxip2016bat$Hundreds))[kxip2016bat$Hundreds],na.rm=TRUE) + sum(as.numeric(levels(kxip2016bat$Fifties))[kxip2016bat$Fifties],na.rm=TRUE))/ sum(as.numeric(levels(kxip2016bat$Inns))[kxip2016bat$Inns],na.rm=TRUE)
kxip2016bat$Boundpercent= (sum(as.numeric(levels(kxip2016bat$Fours))[kxip2016bat$Fours],na.rm=TRUE) + sum(as.numeric(levels(kxip2016bat$Sixes))[kxip2016bat$Sixes],na.rm=TRUE))/ sum(as.numeric(levels(kxip2016bat$BF))[kxip2016bat$BF],na.rm=TRUE)
write.csv(kxip2016bat, file="kxip2016bat.csv",row.names=FALSE)
write.csv(kxip2016bowl, file="kxip2016bowl.csv",row.names=FALSE)
# rcb stats
url8 = "http://stats.espncricinfo.com/indian-premier-league-2016/engine/records/averages/batting_bowling_by_team.html?id=11001;team=4340;type=tournament"
tables=readHTMLTable(url8)
#tables
rcb2016bat<- tables$"Royal Challengers Bangalore batting averages"
rcb2016bowl<- tables$"Royal Challengers Bangalore bowling averages"
rcb2016bowl$TeamEconomy = sum(as.numeric(levels(rcb2016bowl$Runs))[rcb2016bowl$Runs],na.rm=TRUE) / sum(as.numeric(levels(rcb2016bowl$Overs))[rcb2016bowl$Overs],na.rm=TRUE)
rcb2016bowl$TeamSR = round(sum(as.numeric(levels(rcb2016bowl$Overs))[rcb2016bowl$Overs],na.rm=TRUE))*6 / sum(as.numeric(levels(rcb2016bowl$Wkts))[rcb2016bowl$Wkts],na.rm=TRUE)
rcb2016bat$RPB = sum(as.numeric(levels(rcb2016bat$Runs))[rcb2016bat$Runs],na.rm=TRUE) / sum(as.numeric(levels(rcb2016bat$BF))[rcb2016bat$BF],na.rm=TRUE)
rcb2016bat$TeamSR = rcb2016bat$RPB*100
rcb2016bat$TeamRPO = rcb2016bat$RPB *6
rcb2016bat$Outs= as.numeric(levels(rcb2016bat$Inns)[rcb2016bat$Inns],na.rm=TRUE)-as.numeric(levels(rcb2016bat$NO)[rcb2016bat$NO],na.rm=TRUE)
rcb2016bat$Avg = sum(as.numeric(levels(rcb2016bat$Runs))[rcb2016bat$Runs],na.rm=TRUE) / sum(rcb2016bat$Outs,na.rm=TRUE)
names(rcb2016bat)[10] <- "Hundreds"
names(rcb2016bat)[11] <- "Fifties"
names(rcb2016bat)[13] <- "Fours"
names(rcb2016bat)[14] <- "Sixes"
rcb2016bat$Fiftypercent = (2* sum(as.numeric(levels(rcb2016bat$Hundreds))[rcb2016bat$Hundreds],na.rm=TRUE) + sum(as.numeric(levels(rcb2016bat$Fifties))[rcb2016bat$Fifties],na.rm=TRUE))/ sum(as.numeric(levels(rcb2016bat$Inns))[rcb2016bat$Inns],na.rm=TRUE)
rcb2016bat$Boundpercent= (sum(as.numeric(levels(rcb2016bat$Fours))[rcb2016bat$Fours],na.rm=TRUE) + sum(as.numeric(levels(rcb2016bat$Sixes))[rcb2016bat$Sixes],na.rm=TRUE))/ sum(as.numeric(levels(rcb2016bat$BF))[rcb2016bat$BF],na.rm=TRUE)
write.csv(rcb2016bat, file="rcb2016bat.csv",row.names=FALSE)
write.csv(rcb2016bowl, file="rcb2016bowl.csv",row.names=FALSE)
|
0937a127c8c213ebcbf572c6b1efacb8c4a343c9
|
[
"Markdown",
"R"
] | 4
|
R
|
mananshah1/IPL-16-team-stats
|
74a3fd4849e0e224df5793fbaf60eca60c7a1c97
|
2bc52de83b1ba6077a4390965e356ff3db0edf7e
|
refs/heads/master
|
<repo_name>joshua1988/vue-eslint-strict<file_sep>/README.md
# Vue ESLint Strict Rules
[](https://npmjs.com/package/@marvue/eslint-config-vue-strict)
[](https://npmjs.com/package/@marvue/eslint-config-vue-strict)
## Usage
Would you like to make your vue code tight? Follow this guideline.
Create a vue project with Vue CLI (^3.x)
```bash
$ vue create <my-vue>
```
Select these following project options in order
```
Please pick a preset: Manually select features
Check the features needed for your project: Babel, Linter / Formatter
Pick a linter / formatter config: ESLint + Prettier
Pick additional lint features: Lint on Save
Where do you prefer placing config for Babel, ESLint, etc.?: In dedicated config files
Save this as a preset for future projects? n
```
Then, install the npm package
```
$ npm i @marvue/eslint-config-vue-strict
```
Change the eslint config file `.eslintrc`
```js
{
extends: [
'@marvue/vue-strict',
]
}
```
## Rules
- [ESLint Plugin Vue - Recommended](https://eslint.vuejs.org/rules/)
- [ESLint Plugin Import](https://www.npmjs.com/package/eslint-plugin-import)
## License
MIT - CaptainPangyo
<file_sep>/index.js
module.exports = {
extends: [
"plugin:import/errors",
"plugin:import/warnings",
"plugin:vue/recommended"
],
rules: {
/**********************/
/* General Code Rules */
/**********************/
// Enforce import order
"import/order": "error",
// Imports should come first
"import/first": "error",
// Other import rules
"import/no-mutable-exports": "error",
// Allow unresolved imports
"import/no-unresolved": "off",
// Allow async-await
"generator-star-spacing": "off",
// Prefer const over let
"prefer-const": [
"error",
{
destructuring: "any",
ignoreReadBeforeAssign: false
}
],
// No single if in an "else" block
"no-lonely-if": "error",
// Force curly braces for control flow,
// including if blocks with a single statement
curly: ["error", "all"],
// No async function without await
"require-await": "error",
// Force dot notation when possible
"dot-notation": "error",
"no-var": "error",
// Force object shorthand where possible
"object-shorthand": "error",
// No useless destructuring/importing/exporting renames
"no-useless-rename": "error",
/**********************/
/* Vue Rules */
/**********************/
// Disable template errors regarding invalid end tags
"vue/no-parsing-error": [
"error",
{
"x-invalid-end-tag": false
}
],
// Maximum 5 attributes per line instead of one
"vue/max-attributes-per-line": [
"error",
{
singleline: 5
}
],
/***************************/
/* ESLint Vue Plugin Rules */
/***************************/
"vue/html-indent": ["off"],
"vue/order-in-components": [
"error",
{
order: [
"el",
"name",
"parent",
"functional",
["delimiters", "comments"],
["components", "directives", "filters"],
"extends",
"mixins",
"inheritAttrs",
"model",
["props", "propsData"],
"fetch",
"asyncData",
"data",
"computed",
"watch",
"methods",
"LIFECYCLE_HOOKS",
"head",
["template", "render"],
"renderError"
]
}
],
"vue/html-self-closing": ["off"],
// https://eslint.vuejs.org/rules/attributes-order.html
// TODO: 팀 내 기준으로 재조정 필요
"vue/attributes-order": [
"error",
{
order: [
"DEFINITION",
"LIST_RENDERING",
"CONDITIONALS",
"RENDER_MODIFIERS",
"GLOBAL",
"UNIQUE",
"TWO_WAY_BINDING",
"OTHER_DIRECTIVES",
"OTHER_ATTR",
"EVENTS",
"CONTENT"
]
}
],
'vue/require-default-prop': ['off'],
'vue/singleline-html-element-content-newline': ['off'],
}
};
<file_sep>/publish.sh
npm publish --access public
|
479993a0413bd05e1ec158d8b5ff4edb76b767b3
|
[
"Markdown",
"JavaScript",
"Shell"
] | 3
|
Markdown
|
joshua1988/vue-eslint-strict
|
a9b6054aaf34678bf3f9cad79499260ee04a8770
|
6840ae2ebfde762fd692a91240b3186e4b49b286
|
refs/heads/master
|
<repo_name>Contactkislay/ProgrammingAssignment2<file_sep>/cachematrix.R
## Matrix inversion is usually a costly computation and there may be some benefit to caching
## the inverse of a matrix rather than compute it repeatedly.
## This file contains a pair of functions that can be used to cache the inverse of a matrix.
## Example usage:
## > x <- matrix(rnorm(9), nrow= 3) # Create a matrix
## > mcx <- makeCacheMatrix(x) # Create the special matrix
## > mcx$get() # Get the special matrix
## > cacheSolve(mcx) # Return the inverse matrix
## > cacheSolve(mcx) # Return the inverse matrix from cache, while calling cacheSolve(mcx) again
## The function "makeCacheMatrix" creates a special "matrix" object that can cache its inverse.
## It returns list of functions to:
# Set the value of the matrix
# Get the value of matrix
# Set the value of inverse
# Get the value of inverse
makeCacheMatrix <- function(x = matrix()) {
invr <- NULL
# Set the matrix
set <- function(y) {
x <<- y
invr <<- NULL
}
# Get the matrix
get <- function() x
# Set the inverse of matrix
setinverse <- function(inverse) invr <<- inverse
# Get the inverse of matrix
getinverse <- function() invr
# Return the list of functions
list(set = set,
get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## The function "cacheSolve"computes the inverse of the special "matrix" returned by "makeCacheMatrix" above.
## If the inverse has already been calculated (and the matrix has not changed),
## then this function will retrieve the inverse from the cache and return it.
cacheSolve <- function(x, ...) {
invr <- x$getinverse()
# If inverse is already calculated and available in cache, return the cached data.
if(!is.null(invr)) {
message("getting cached inverse matrix data.")
return(invr)
}
# If inverse is not calculated yet, calculate it.
data <- x$get()
invr <- solve(data, ...)
# Cache the inverse
x$setinverse(invr)
# Return the inverse
invr
}
|
a8900c3c096ab168fe4acffa14a7bdc842b652b0
|
[
"R"
] | 1
|
R
|
Contactkislay/ProgrammingAssignment2
|
1d15c0b5df0c69792e8e2fefdf07ca5948cc90b0
|
960cdc34156db4433890fee47aefdcf35751578e
|
refs/heads/master
|
<file_sep>//Topological sorting using DFS
#include<iostream>
#include<stack>
#include<list>
using namespace std;
void topological_sort(list<int> ls[],bool visited[],int src,stack<int> &st){
visited[src] = true;
list<int>::iterator it;
for(it = ls[src].begin(); it != ls[src].end(); it++){
if(!visited[*it]){
topological_sort(ls,visited,*it,st);
}
}
st.push(src);
}
int main(){
int v,e;
cin >> v >> e;
list<int> ls[v+1];
for(int i = 0; i < e; i++){
int a , b;
cin >> a >> b;
ls[a].push_back(b);
}
stack<int> st;
bool visited[v+1];
fill(visited,visited+v+1,false);
for(int i = 1; i <= v; i++)
if(!visited[i])
topological_sort(ls,visited,i,st);
while(!st.empty()){
cout << st.top() << " ";
st.pop();
}
return 0;
}
<file_sep>#include<iostream>
#include<algorithm>
using namespace std;
int my_func(int i , int j){ //it performs the same task as default sort
return i < j;
}
int main(){
int arr[10] = {1,5,8,5,31,5,45,54,78,88};
sort(arr,arr+10);
//my_func is not needed to write if our array is already a sorted one...
if(binary_search(arr,arr+10,8,my_func)){
cout << "found the number " << 8 << endl;
}
else cout << "Not found " << endl;
int *low, *high; //or use iterators if vector is used...
low = lower_bound(arr,arr+10,5);
high = upper_bound(arr,arr+10,5);
cout << "lower index of 5 is " << (low - arr) << endl;
cout << "upper index of 5 is " << (high - arr) << endl;
// 1 ->5 5 5 ->8 31 45 54 78 88 pointing the lower and upper index as above...
//we may use (equal_range) instead of (lower_bound) and (upper_bound) as follow :
pair<int *, int *> bounds;
bounds = equal_range(arr,arr+10,5);
cout << "lower index of 5 is " << (bounds.first - arr) << endl;
cout << "upper index of 5 is " << (bounds.second - arr) << endl;
return 0;
}
<file_sep>#include<iostream>
using namespace std;
class Complex{
private:
int r = 0, i = 0;
public:
Complex(){};
Complex(int a) : r(a) , i(a){} //A way to initialize contructor outside it's block
Complex(int a , int b){
r = a;
i = b;
}
Complex operator+(Complex &x){
Complex temp;
temp.r = r + x.r;
temp.i = i + x.i;
return temp;
}
friend Complex operator-(Complex &x, Complex &y){
Complex temp;
temp.r = x.r - y.r;
temp.i = x.i - y.i;
return temp;
}
friend void display(Complex &x){
if(x.i >= 0)
cout << x.r << " + " << x.i << " i" << endl;
else
cout << x.r << " - " << -x.i << " i " << endl;
}
};
int main(){
Complex x = 4; //Way 1
display(x);
Complex x1 = Complex(5); //Way 2
display(x1);
Complex y = Complex(3,2); //Way 2 for multiple arguements
display(y);
Complex c1(2,4), c2(1,6); //Way 4
display(c1);
display(c2);
cout << "After addition" << endl;
Complex c3;
c3 = c1 + c2; //overloading operatior '+' and using implicit copy constructor
display(c3);
cout << "After subraction" << endl;
Complex c4;
c4 = c1 - c2;
display(c4);
return 0;
}
<file_sep>//Kruskal algo. using disjoint set, union by rank
//to find the minimum spanning tree.
#include <bits/stdc++.h>
#define mp make_pair
using namespace std;
int find(int src,int parent[]){
if(src == parent[src]) return src;
parent[src] = find(parent[src],parent);
return parent[src];
}
void unite(int src,int dest,int parent[],int rank[]){
src = find(src,parent);
dest = find(dest,parent);
if(rank[src] > rank[dest]){
parent[dest] = src;
}
else if(rank[dest] > rank[src]){
parent[src] = dest;
}else{
parent[dest] = src;
rank[src]++;
}
}
void kruskal(pair<int,pair<int,int> > p[],int v,int e){
int parent[v],rank[v];
for(int i = 0; i < v; i++){
parent[i] = i;
rank[i] = 0;
}
int vi = 0,ei = 0;
int min_wt = 0;
while(vi < v-1){
int src = p[ei].second.first;
int dest = p[ei].second.second;
int wt = p[ei].first;
if(find(src,parent) != find(dest,parent)){
unite(src,dest,parent,rank);
min_wt += wt;
vi++;
}
ei++;
}
cout << min_wt << endl;
}
int main() {
int v,e;
cin >> v >> e;
pair<int,pair<int,int>> p[e];
int src,dest,wt;
for(int i = 0; i < e; i++){
cin >> src >> dest >> wt;
p[i] = mp(wt,mp(src-1,dest-1));
}
sort(p,p+e);
kruskal(p,v,e);
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
int KnapSackFunc(int n,int w,int weights[],int values[]){
int table[n+1][w+1];
for(int i = 0; i <= n; i++){
for(int j = 0; j <= w; j++){
if(i == 0 || j == 0){
table[i][j] = 0;
}
else if(weights[i-1] <= j){
table[i][j] = max(values[i-1] + table[i-1][j-weights[i-1]],table[i-1][j]);
}
else{
table[i][j] = table[i-1][j];
}
}
}
return table[n][w];
}
int main() {
int n,w;
cin >> n >> w;
int weights[n],values[n];
for(int i = 0; i < n; i++) cin >> weights[i];
for(int i = 0; i < n; i++) cin >> values[i];
cout << KnapSackFunc(n,w,weights,values) << endl;
return 0;
}
<file_sep>#include<iostream>
#include<vector>
#include<algorithm> //for library swap function
using namespace std;
void print_vector(vector<int> arr){
for(int i = 0;i < arr.size(); i++){
cout << arr[i] << ' ';
}
cout << endl;
}
//void sorting(vector<int> & arr , int n){
// int temp;
// for(int i = 0 ; i < n-1; i++){
// for(int j = i+1; j < n;j++){
// if(arr[i] > arr[j]){
// temp = arr[i];
// arr[i] = arr[j];
// arr[j] = temp;
// }
// }
//
// }
// print_vector(arr);
//}
int main(){
int n , a;
int i = 0;
cout << "Enter size of vector" << endl;
cin >> n;
vector<int> vet(n);
for(int i = 0; i < n; i++){
cout << "Enter a number" << endl;
cin >> vet[i];
}
bool flag = true;
for(int i = 0; i < vet.size() - 1; i++){
if(vet[i] > vet[i+1]){
flag = false;
break;
}
}
if(flag == false){
cout << "Array is unsorted" << endl;
//sorting(vet,n);
sort(vet.begin(),vet.end());
cout << "The sorted vector is:\n";
for(int i = 0; i < n; i++){
cout << vet[i] << endl;
}
}
else{
cout << "Array is sorted" << endl;
}
}
<file_sep>#include<iostream>
using namespace std;
void swap(int a,int b){
a = a + b;
b = a - b;
a = a - b;
}
void swap(int *c , int * d){
*c = *c + *d;
*d = *c - *d;
*c = *c - *d;
}
void swap1(int &a , int &b){
a = a + b;
b = a - b;
a = a - b;
}
int main(){
int a = 30 , b = 60;
swap(a,b); //values are not swapped
cout << "a = " << a << " b = " << b << endl;
swap(&a,&b); //Pass by address
cout << "a = " << a << " b = " << b << endl;
swap1(a,b); //Pass by reference
cout << "a = " << a << " b = " << b << endl;
return 0;
}
<file_sep>#include<iostream>
using namespace std;
class B{
int a; //private members are not inheritable
public:
int b; //All public,protected members are inheritable
void set_ab(void);
int get_a(void);
void show_a(void);
};
//class D : private B //changes visibility of derived members to private
//class D : protected B //changes visibility of derived members to protected
class D : public B{ //Doesn't change visibility of derived members
int c;
public:
void mul(void);
void display(void);
};
void B::set_ab(){
a = 5; b = 10;
}
int B::get_a(){
return a;
}
void B::show_a(){
cout << " a = " << a << endl;
}
void D::mul(){
c = b * get_a();
}
void D::display(){
cout << " a = " << get_a() << endl;
cout << " b = " << b << endl;
cout << " c = " << c << endl;
}
int main(){
D d;
d.set_ab(); //sets a to 5 and b = 10
d.mul();
d.show_a(); //although a is not inherited a can be accessed by inherited member show_a()
d.display();
d.b = 20;
// d.a = 12; //Invalid statement , a is private so not inherited
d.mul();
d.display();
return 0;
}
<file_sep>//naive pattern searching...
#include <bits/stdc++.h>
#define ULL unsigned long long
#define LL long long
#define endl '\n'
#define ALL(v) begin(v), end(v)
#define CONTAINS(container, value) container.find(value) != container.end()
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
string txt,pat;
cin >> txt >> pat;
int j;
for(int i = 0; i <= txt.size()-pat.size(); i++){
for(j = 0; j < pat.size(); j++){
if(txt[i+j] != pat[j]) break;
}
if(j == pat.size()) cout << "found" << endl;
}
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
int v,e;
void alltopo(vector<int> &ans,vector<bool> &visited,list<int> g[],vector<int> &indeg){
bool flag = false;
for(int i = 0; i < v; i++){
if(indeg[i] == 0 && !visited[i]){
for(auto j : g[i]) indeg[j]--;
ans.push_back(i);
visited[i] = true;
alltopo(ans,visited,g,indeg);
visited[i] = false;
ans.erase(ans.end()-1);
for(auto j : g[i]){
indeg[j]++;
}
flag = true;
}
}
if(!flag){
for(int i = 0; i < ans.size(); i++){
printf("%d ",ans[i]);
}
puts("");
}
}
int main() {
scanf("%d%d",&v,&e);
list<int> g[v];
vector<int> indeg(v,0);
int src,dest;
for(int i = 0; i < e; i++){
scanf("%d%d",&src,&dest);
g[src].push_back(dest);
indeg[dest]++;
}
vector<bool> visited(v,false);
vector<int> ans;
alltopo(ans,visited,g,indeg);
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
int main() {
int v,e;
scanf("%d%d",&v,&e);
int src,dest;
vector<int> g[v];
vector<int> indeg(v,0);
for(int i = 0; i < e; i++){
scanf("%d%d",&src,&dest);
src--; dest--;
g[src].push_back(dest);
indeg[dest]++;
}
queue<int> q;
for(int i = 0; i < v; i++)
if(indeg[i] == 0)
q.push(i);
int cnt = 0;
vector<int> ans;
while(!q.empty()){
int u = q.front();
q.pop();
ans.push_back(u);
for(auto it:g[u]){
if(--indeg[it] == 0){
q.push(it);
}
}
cnt++;
}
if(cnt != v){
printf("cycle exists\n");
exit(0);
}
for(int i = 0; i < v; i++){
printf("%d ",ans[i]+1);
}
puts("");
return 0;
}
<file_sep>//Simulating a list through doubly linked list
#include<iostream>
using namespace std;
struct link{
link * prev;
link * next;
int data;
};
link * start = NULL;
void InsertAtBeg(){
link * p = new link();
cout << "\nEnter data: ";
cin >> p->data;
p->prev = NULL;
p->next = start;
if(start != NULL)
start->prev = p;
start = p;
cout << "\n***Successfully inserted***\n";
}
void Traverse(){
link * p = start;
if(start == NULL){
cout << "\nEmpty list\n";
return;
}
int i = 0;
while(p != NULL){
cout << i++ << ". " << p->data << endl;
p = p->next;
}
}
void InsertAtEnd(){
link * p = new link();
cout << "\nEnter data ";
cin >> p->data;
link * q = start;
if(start == NULL){
start = p;
p->next = NULL;
p->prev = NULL;
return;
}
while(q->next != NULL){
q = q->next;
}
p->next = NULL;
q->next = p;
p->prev = q;
cout << "\n***Successfully inserted***\n";
}
void DeleteBeg(){
if(start == NULL){
cout << "\nEmpty list\n";
return ;
}
link * p = start;
start = start->next;
if(start != NULL)
start->prev = NULL;
cout << "\nSuccessfully deleted " << p->data << endl;
delete p;
}
void DeleteEnd(){
link * q = start;
if(start == NULL){
cout << "\nEmpty list\n";
return;
}
while(q->next != NULL){
q = q->next;
}
if(q->prev != NULL)
(q->prev)->next = NULL;
cout << "\nSuccessfully deleted " << q->data << endl;
delete q;
}
void Reverse(){
if(start == NULL){
cout << "\nEmpty list\n";
return;
}
cout << "\nIn reverse order:\n";
link * p = start;
while(p->next != NULL){
p = p->next;
}
while(p != NULL){
cout << p->data << endl;
p = p->prev;
}
}
void InsertSpec(){
int pos;
cout << "\nEnter position :";
cin >> pos;
if(pos == 0){
InsertAtBeg();
return;
}
link * p = new link();
link *q = start;
for(int i = 0; i < pos - 1; i++){
if(q == NULL){
cout << "\nInvalid position\n";
return;
}
q = q->next;
}
cout << "\nEnter data : ";
cin >> p->data;
p->prev = q;
p->next = q->next;
q->next->prev = p;
q->next = p;
cout << "\n***Successfully inserted***\n";
}
void DeleteSpec(){
if(start == NULL){
cout << "\nEmpty list\n";
return;
}
int pos;
cout << "\nEnter position:";
cin >> pos;
if(pos == 0){
DeleteBeg();
return;
}
link * p = start;
for(int i = 0; i < pos; i++){
if(p == NULL){
cout << "\nInvalid range\n";
return;
}
p = p->next;
}
if(p->prev != NULL)
p->prev->next = p->next;
if(p->next != NULL)
p->next->prev = p->prev;
cout << "\nSuccessfully deleted " << p->data << endl;
delete p;
}
int main(){
cout << "\nSimulating a list through a doubly linked list\n";
do{
int opt;
cout << "\nMenu:";
cout << "\n1 Insert 1 item at beginning"
<< "\n2 Insert 1 item at end"
<< "\n3 Traverse list"
<< "\n4 Exit"
<< "\n5 Delete 1 item from beginning"
<< "\n6 Delete 1 item from end"
<< "\n7 Delete 1 item from specific position"
<< "\n8 Insert 1 item at Specific position"
<< "\n9 Reverse display the list";
cout << "\n\nEnter a option:\t";
cin >> opt;
switch(opt){
case 1: InsertAtBeg();
break;
case 2: InsertAtEnd();
break;
case 3: Traverse();
break;
case 4: exit(1);
break;
case 5: DeleteBeg();
break;
case 6: DeleteEnd();
break;
case 7: DeleteSpec();
break;
case 8: InsertSpec();
break;
case 9: Reverse();
break;
default:
cout << "\nEnter valid option.";
}
}while(true);
return 0;
}
<file_sep>#include<iostream>
#include<list>
using namespace std;
void display(list<int> ls){
for(list<int>::iterator it = ls.begin(); it != ls.end(); it++){
cout << *it << " ";
}
cout << endl;
}
int main(){
list<int> list1(5);
int data; //to store the data into list
//put data in list
for(list<int>::iterator it = list1.begin(); it != list1.end();it++){
cin >> data; //get data
*it = data; //put data
}
//basic operations
list1.push_back(10);
list1.push_front(12);
list1.pop_front();
list<int> list2(3,8);
list1.merge(list2); //Merge the lists
list1.sort(); //sorts the list
list1.reverse();
display(list1);
return 0;
}
<file_sep>//Simulating a list through doubly circular linked list
#include<iostream>
using namespace std;
struct link{
link * prev;
link * next;
string data;
};
link * start = NULL;
link * last = NULL;
void Clear(){
link *p = start;
do{
if(start == last){
start = last = NULL;
return;
}
p = start;
start = start->next;
last->next = start;
delete p;
}while(p != start);
}
void InsertAtBeg(){
link * p = new link();
cout << "\nEnter data:";
cin.ignore();
getline(cin,p->data);
if(start == NULL){
start = p;
last = p;
p->prev = p; //start->prev = last
p->next = p; //last->next = start
}
else{
p->next = start;
p->prev = last;
start->prev = p;
last->next = p;
start = p;
}
cout << "\n***Sucessfully inserted***\n";
}
void Traverse(){
if(start == NULL){
cout << "\n***Empty list***\n";
return;
}
cout << "\nThe elements of lists are:\n";
int i = 0;
link * p = start;
do{
cout << i++ << ". " << p->data << endl;
p = p->next;
}while(p != start);
}
void Count(){
int i = 0;
link * p = start;
if(start == NULL){
cout << 0 << endl;
return;
}
do{
i++;
p = p->next;
}while(p != start);
cout << i << endl;
}
void InsertAtEnd(){
link * p = new link();
cout << "\nEnter data:";
cin.ignore();
getline(cin,p->data);
if(last == NULL){
start = last = p;
p->next = p->prev = p;
}
else{
p->next = start;
p->prev = last;
last->next = p;
start->prev = p;
last = p;
}
cout << "\n***Sucessfully inserted***\n";
}
void DeleteBeg(){
if(start == NULL){
cout << "\n***Empty list***\n";
return;
}
else if(start == last){
cout << "\nDeleted item is " << start->data << endl;
start = NULL;
last = NULL;
}
else{
link *p = start;
start = start->next;
start->prev = last;
last->next = start;
cout << "\nDeleted item is " << p->data << endl;
delete p;
}
}
void DeleteEnd(){
if(start == NULL){
cout << "\n***Empty list***\n";
return;
}
else if(start == last){
cout << "\nDeleted item is " << start->data << endl;
start = NULL;
last = NULL;
}
else{
link *p = last;
last = last->prev;
last->next = start;
start->prev = last;
cout << "\nDeleted item is " << p->data << endl;
}
}
void Reverse(){
if(last == NULL){
cout << "\n***Empty list***\n";
return;
}
int i = 0;
cout << "\nReversed version of the list is:\n";
link * p = last;
do{
cout << i++ << " . " << p->data << endl;
p = p->prev;
}while(p != last);
}
void InsertSpec(){
link *p = new link();
int pos;
cout << "\nEnter position : ";
cin >> pos;
if(pos == 0){
InsertAtBeg();
return;
}
link * q = start;
if(q == NULL){
cout << "\nInvalid position\n";
return;
}
for(int i = 0; i < pos - 1; i++){
if(q == start && i != 0){
cout << "\nInvalid position\n";
return;
}
q = q->next;
}
cout << "\nEnter data : ";
cin.ignore();
getline(cin,p->data);
p->prev = q;
p->next =q->next;
if(q != last){
q->next->prev = p;
}
else{
last = p;
start->prev = last;
}
q->next = p;
cout << "\n***Sucessfully inserted***\n";
}
void DeleteSpec(){
if(start == NULL){
cout << "\n***Empty list***\n";
return;
}
int pos;
cout << "\nEnter position:";
cin >> pos;
if(pos == 0){
DeleteBeg();
return;
}
link * q = start;
for(int i = 0; i < pos; i++){
if(i != 0 && q == start){
cout << "\nInvalid range\n";
return;
}
q = q->next;
}
q->prev->next = q->next;
if(q != last){
q->next->prev = q->prev;
}
else{
last = q->prev;
start->prev = last;
}
cout << "\nDeleted item is " << q->data << endl;
delete q;
}
int main(){
cout << "\nSimulating a list through a doubly circular linked list\n";
do{
int opt;
cout << "\nMenu:" << endl <<"`````";
cout << "\n1 <- Insert 1 item at beginning"
<< "\n2 <- Insert 1 item at end"
<< "\n3 <- Insert 1 item at Specific position"
<< "\n4 <- Traverse list"
<< "\n5 <- Delete 1 item from beginning"
<< "\n6 <- Delete 1 item from end"
<< "\n7 <- Delete 1 item from specific position"
<< "\n8 <- Reversely display the list"
<< "\n9 <- Count items"
<< "\n10 <- Clear list"
<< "\n11 <- Exit";
cout << "\n\nEnter a option:\t";
cin >> opt;
switch(opt){
case 1: InsertAtBeg();
break;
case 2: InsertAtEnd();
break;
case 3: InsertSpec();
break;
case 4: Traverse();
break;
case 5: DeleteBeg();
break;
case 6: DeleteEnd();
break;
case 7: DeleteSpec();
break;
case 8: Reverse();
break;
case 9:
cout << "\nNumber of items = "; Count();
break;
case 10:
Clear();
cout << "\n***List cleared***\n";
break;
case 11: exit(1);
break;
default:
cout << "\nEnter valid option.";
}
}while(true);
return 0;
}
<file_sep>#include<iostream>
#include<vector>
using namespace std;
void print_vector(vector<int> arr){
for(int i = 0;i < arr.size(); i++){
cout << arr[i] << ' ';
}
cout << endl;
}
int main(){
vector<int> arr(5,0); //first five location intialized to 0
cout << "arr :\n";
print_vector(arr);
vector<int> arr1(4,1);
arr.insert(arr.end(),arr1.begin(),arr1.end()); //Inserts the arr1 (from begining to end) elements after the last location of arr
cout << "arr with arr1 inserted at last:\n";
print_vector(arr);
int arr2[5] = {1,2,3,4,5};
arr.insert(arr.begin()+5,arr2,arr2+5); //to insert in middle of vector the elements of arr2
cout << "arr with array (arr2) inserted in middle:\n";
print_vector(arr);
arr.erase(arr.end()-4,arr.end());
cout << "Erased the last four elements of arr\n";
print_vector(arr);
cout << "size of arr = " << arr.size() << endl; //size of arr
//Swapping vector ;
vector<int> vector1(5,0); //Orignal vectors
vector<int> vector2(5,1);
cout << "vector1 : ";
print_vector(vector1);
cout << "vector2 : ";
print_vector(vector2);
vector1.swap(vector2); //swaps vector1 and vector2;
cout << "After swapping\n";
cout << "vector1 : ";
print_vector(vector1);
cout << "vector2 : "; //printing the vectors after swapping
print_vector(vector2);
// vector1.reverse(vector1.begin(),vector1.end()); //to reverse the vector within the range
// print_vector(vector1);
vector1.clear(); //to clear the vector1
cout << "\nAfter clear\n";
print_vector(vector1);
bool emp = vector1.empty(); //returns 1(true) if vector1 is empty
cout << emp ;
return 0;
}
<file_sep>#include<iostream>
using namespace std;
class prime{
public:
bool is_prime(int n){
if(n == 1) return false;
for(int i = 2; i*i <= n; i++ ){
if(n % i == 0) return false;
}
return true;
}
};
int main(){
prime obj;
int n;
cout << "Enter a number: ";
cin >> n;
bool x = obj.is_prime(n);
cout << "x = " << x << endl;
if(x) cout << "is prime\n";
else cout << "Not prime" << endl;
return 0;
}
<file_sep> #include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
int main(){
char line[500];
char line2[500];
bool is_different = false;
ifstream fin1,fin2;
fin1.open("op1.txt");
fin2.open("op2.txt");
while(fin1 && fin2){
fin1.getline(line,500);
fin2.getline(line2,500);
// cout << line << endl;
// cout << line2 << endl;
if(strcmp(line,line2)){
is_different = true;
break;
}
}
if(is_different) cout << "differce found" << endl;
else cout << "Duplicate data's on files" << endl;
return 0;
}
<file_sep>#include <bits/stdc++.h>
//to update a range with given value...
using namespace std;
vector<int> st;
vector<int> create(int size){
int h = ceil(log2(size));
int max = 2*pow(2,h) - 1;
vector<int> tt(max,0);
return tt;
}
int get_sum(int start, int end, int qs, int qe,int idx){
if(qs > end || start > qe) return 0;
if(qs <= start && qe >= end) return st[idx];
int mid = start + (end - start)/2;
return get_sum(start,mid,qs,qe,2*idx+1) + get_sum(mid+1,end,qs,qe,2*idx+2);
}
void update(int qs , int qe, int start,int end, int idx,int nv){
if(start > qe || end < qs){
return;
}
if(start == end){
st[idx] = nv;
return;
}
int mid = start + (end - start)/2;
update(qs,qe,start,mid,2*idx+1,nv);
update(qs,qe,mid+1,end,2*idx+2,nv);
st[idx] = st[idx*2 + 1] + st[idx * 2 + 2];
}
int main() {
vector<int> arr(5,0);
int size = 5;
st = create(size);
cout << get_sum(0,size-1,3,4,0) << endl;
//update index 2-4 to 10...
for(int i = 2; i <= 4; i++) arr[i] = 10;
update(2,4,0,size-1,0,10);
for(int i = 0; i < size; i++) cout << arr[i] << " ";
cout << endl;
cout << get_sum(0,size-1,3,4,0) << endl;
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int multiply_5(int x){
cout << "You called me with " << x << endl;
return 5*x;
}
int multiply_3(int a){
cout << "You called me with " << a << endl;
return 3*a;
}
int Func_chooser(int data, int (*f) (int) ){
return (*f)(data);
}
int main(){
int (*a) (int) = multiply_5; //a takes the address of function
cout << Func_chooser(5,a) << endl; //passing data and appropriate function address
cout << Func_chooser(5,multiply_3) << endl;
cout << Func_chooser(4,multiply_5) << endl;
return 0;
}
<file_sep>#include<iostream>
using namespace std;
class Matrix{
private:
int **p;
int d1,d2;
public:
Matrix(int x, int y);
void get_element(int i, int j , int value);
int & put_element(int i, int j);
~Matrix();
};
inline int & Matrix::put_element(int i, int j){
return p[i][j];
}
inline void Matrix::get_element(int i, int j , int value){
p[i][j] = value;
}
Matrix::Matrix(int x , int y){
d1 = x; d2 = y;
p = new int * [d1];
for(int i = 0; i < d1; i++){
p[i] = new int [d2];
}
}
//Using destructor to free allocated memory
Matrix::~Matrix(){
for(int i = 0; i < d1; i++){
delete p[i];
}
delete p;
}
int main(){
int m, n;
cout << "Enter the size of matrix ";
cin >> m >> n;
Matrix mat(m,n);
cout << "Enter matrix elements row by row\n";
int value;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
cin >> value;
mat.get_element(i,j,value);
}
}
//cout << "\n mat[2][2] = " << mat.put_element(2,2);
}
<file_sep>#include<iostream>
using namespace std;
class employee {
private:
int age ;
string name;
int salary;
employee(string n, int a, int s){
name = n;
age = a;
salary = s;
}
};
int main(){
employee emp1("San", 20 , 120000);
//if no constructor
// emp1.age = 20;
// emp1.name = "San";
// emp1.salary = 120000;
//if public can use this
// cout << "Name : " << emp1.name << endl;
// cout << "Age : " << emp1.age << endl;
// cout << "Salary : " <<emp1.salary;
return 0;
}
<file_sep>// DP : Space optimized , edit-distance algorithm
#include <bits/stdc++.h>
#define ull unsigned long long int
#define ll long long int
#define pb(x) push_back(x)
#define ALLONS_Y ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define debug(x) cout << #x << " = " << x << endl
// #define DEBUG 1
using namespace std;
int editDistance(string s1,string s2){
int m = s1.size();
int n = s2.size();
int table[2][n+1];
for(int i = 0; i <= n; i++)
table[0][i] = i;
for(int i = 1; i <= m; i++){
for(int j = 0; j <= n; j++){
if(j == 0){
table[i%2][j] = i;
}
else if(s1[i-1] == s2[j-1]){
table[i%2][j] = table[(i-1) % 2][j-1];
}else{
table[i%2][j] = min(table[(i-1)%2][j-1],table[(i-1)%2][j]);
table[i%2][j] = min(table[i%2][j],table[i%2][j-1]) + 1;
}
}
}
return table[m%2][n];
}
int main() {
ALLONS_Y;
#ifdef DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
string s1,s2;
cin >> s1 >> s2;
cout << editDistance(s1,s2) << endl;
return 0;
}<file_sep>#include<iostream>
#include<vector>
using namespace std;
struct bt{
bt * left;
bt * right;
int data;
};
vector<int> datas;
void inorder(bt * r){
if(r == NULL) return;
else{
inorder(r->left);
// If the given tree is binary search tree then the vector must have sorted data
datas.push_back(r->data);
// cout << r->data << " ";
inorder(r->right);
}
}
bt* getnewnode(int data){
bt * a = new bt();
a->left = NULL;
a->right = NULL;
a->data = data;
return a;
}
bool CheckSorted(vector<int> d){
for(int i = 0; i < d.size() - 1 ; i++){
if(d[i] > d[i+1]){
return false;
}
}
return true;
}
bt* insert(bt * root,int data){
if((root) == NULL){
root = getnewnode(data);
}
else if (data <= root->data){
root->left = insert(root->left,data);
}
else root->right = insert(root->right,data);
return root;
}
int main(){
bt * root = NULL;
root = insert(root,10);
root = insert(root,2);
root = insert(root,12);
root = insert(root,20);
inorder(root);
cout << "\nDatas in vector are :\n";
for(int i = 0; i < datas.size(); i++){
cout << datas[i] << " ";
}
if(CheckSorted(datas)){
cout << "\nGiven tree is a binary search tree\n";
}
else{
cout << "\n Not a binary search tree\n";
}
return 0;
}
<file_sep>#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int random(int i, int j) {
return (rand() % j) + i;
}
int main() {
srand(time(NULL));
for(int i = 1; i <= 1000; i ++) {
cout << random(0, 8) << " " << random(0,8) << endl;
}
return 0;
}
<file_sep>//Singly circular linked list
#include<iostream>
using namespace std;
struct link{
link * next;
int data;
};
link * start = NULL;
link * last = NULL;
void InsertAtBeg(){
link * p = new link();
cout << "\nEnter the data: ";
cin >> p->data;
if(start == NULL){
start = p;
last = p;
p->next = last;
}
else{
p->next = start;
start = p;
last->next = start;
}
cout << "\n***Successfully Inserted***\n";
}
void InsertAtEnd(){
link * p = new link();
cout << "\nEnter data: ";
cin >> p->data;
if(start == NULL){
start = p;
last = p;
p->next = p;
}
else{
last->next = p;
p->next = start;
last = p;
}
cout << "\n***Successfully Inserted***\n";
}
void Traverse(){
if(start == NULL ){
cout << "\nEmpty list\n";
return;
}
cout << "\nThe elements of list are:\n";
link * p = start;
int index = 0;
do{
cout << index++ << ". " << p->data << endl;
p = p->next;
}while(p != start);
}
void DeleteBeg(){
link * p = start;
if(start == NULL){
cout << "\nEmpty list\n";
return;
}
else if(start == last){
start = NULL;
last = NULL;
cout << "\nSucessfully deleted " << p->data << endl;
delete p;
}
else{
start = start->next;
last->next = start;
cout << "\nSucessfully deleted " << p->data << endl;
delete p;
}
}
void DeleteEnd(){
link * p = last;
if(p == NULL){
cout << "\nEmpty list\n";
return;
}
else if( start == last){
start = NULL;
last = NULL;
cout << "\nSuccessfully deleted " << p->data << endl;
delete p;
}
else{
link * q = start;
while(q->next != last){
q = q->next;
}
last = q;
last->next = start;
cout << "\nSuccessfully deleted " << p->data << endl;
delete p;
}
}
void InsertSpec(){
int pos;
cout << "\nEnter the position : ";
cin >> pos;
if(pos == 0){
InsertAtBeg();
return;
}
else{
link * p = new link();
link * q = start;
if(q == NULL){
cout << "\nInvalid range\n";
return;
}
cout << "\nEnter data: ";
cin >> p->data;
for(int i = 0; i < pos - 1; i++){
if(q == start && i != 0){
cout << "\nInvalid range\n";
return;
}
q = q->next;
}
p->next = q->next;
q->next = p;
if(p->next == start) {
last = p;
}
}
cout << "\n***Successfully Inserted***\n";
}
void DeleteSpec(){
if(start == NULL){
cout << "\nEmpty list\n";
return;
}
link *prev , *current;
int pos;
cout << "\nEnter the position: ";
cin >> pos;
if(pos == 0){
DeleteBeg();
return;
}
current = start;
for(int i = 0; i < pos; i++){
prev = current;
current = current->next;
if(current == start){
cout << "\nInvalid position\n";
return;
}
}
prev->next = current->next;
if(current == last) {
last = prev;
}
cout << "\nSuccessfully deleted " << current->data << endl;
delete current;
}
int main(){
cout << "\nSimulating a list through a Singly circular linked list\n";
do{
int opt;
cout << "\nMenu:";
cout << "\n1 Insert 1 item at beginning"
<< "\n2 Insert 1 item at end"
<< "\n3 Traverse list"
<< "\n4 Exit"
<< "\n5 Delete 1 item from beginning"
<< "\n6 Delete 1 item from end"
<< "\n7 Delete 1 item from specific position"
<< "\n8 Insert 1 item at Specific position";
cout << "\n\nEnter a option:\t";
cin >> opt;
switch(opt){
case 1: InsertAtBeg();
break;
case 2: InsertAtEnd();
break;
case 3: Traverse();
break;
case 4: exit(1);
break;
case 5: DeleteBeg();
break;
case 6: DeleteEnd();
break;
case 7: DeleteSpec();
break;
case 8: InsertSpec();
break;
default:
cout << "\nEnter valid option.";
}
}while(true);
return 0;
}
<file_sep>#include<iostream>
using namespace std;
void pattern(int x){
if(x < 1) return;
func(x-1);
for(int i = 0; i < x; i++){
cout << "*" << " " ;
}
cout << endl;
}
int main(){
pattern(5);
}
<file_sep>//About constructors
#include<iostream>
using namespace std;
class Complex{
float x , y;
public: //Constructors must be public member
Complex(){} // Default constructor , set x and y to 0
Complex(float a , float b ){ //Constructor sets x = a and y = b,overloaded constructor
x = a;
y = b;
}
Complex(float a){ //sets both value to a
x = y = a;
}
/*
//Constructor with default arguement,
//it takes single or double variable
//Make cause ambuigity if used,since there will be 2 constructor that takes 2 arguements
Complex(float a,float b = 0){
x = a;
y = b;
}
*/
friend Complex sum(Complex & , Complex &);
friend void show(Complex &);
};
Complex sum(Complex &a,Complex &b){
Complex ans;
ans.x = a.x + b.x;
ans.y = a.y + b.y;
return ans;
}
void show(Complex &c){
cout << c.x << "+" << c.y << "i" << endl;
return;
}
int main(){
Complex c1(3.2,1.5);
Complex c2(8.2);
Complex c3 = sum(c1,c2);
cout << " c1 = "; show(c1);
cout << " c2 = "; show(c2);
cout << " c3 = "; show(c3);
return 0;
}
<file_sep>//Overloading operators
#include<iostream>
using namespace std;
class vector{
private:
int *arr;
int n;
public:
vector(int);
void insert(int, int);
void display();
vector operator + (vector &);
void operator - ();
friend vector operator * (vector & , vector &); //using friend function for binary operator
friend void operator ~ (vector &); //using friend function for unary operator
};
vector::vector(int size){
n = size;
arr = new int[n];
}
void vector::insert(int index, int data){
arr[index] = data;
}
void vector::display(){
//n is of the calling object property
for(int i = 0; i < n ;i++){
cout << arr[i] << " " ;
}
}
vector vector::operator + (vector &c){
vector d(n);
for(int i = 0; i < n; i++){
d.arr[i] = arr[i] + c.arr[i];
}
return d;
}
void vector::operator - (){
for(int i = 0; i < n; i++)
arr[i] = - arr[i];
}
vector operator *(vector &a, vector &b){ //friend function definition
int n = a.n; //since here object is not the one who called so we provide n explictly from any one object
vector c(n);
for(int i = 0; i < n; i++){
c.arr[i] = a.arr[i] * b.arr[i];
}
return c;
}
void operator ~ (vector &a){ //friend function defition
for(int i = 0; i < a.n; i++){
a.arr[i] = - a.arr[i];
}
}
int main(){
int n , index, data;
cout << "Enter the size of the vectors : ";
cin >> n;
vector a(n);
cout << "Enter the data for the vector 1" << endl;
for(int i = 0; i < n; i++){
cin >> data;
a.insert(i,data);
}
vector b(n);
cout << "Enter the data for the vector 2" << endl;
for(int i = 0; i < n; i++){
cin >> data;
b.insert(i,data);
}
vector c(n);
c = a + b; //overloading binary operator "+" that has return type
cout << "\nAfter adding both vectors" << endl;
c.display();
-c; //overloading unary minus
cout << "\nNegating the sum result " << endl;
c.display();
//block for friend function
{
vector d(n);
cout << "\nAfter multiplying both vectors" << endl;
d = a * b;
d.display();
~d; //overloading unary minus using friend
cout <<"\nNegating multiplied result" << endl;
d.display();
}
return 0;
}
<file_sep>#include <bits/stdc++.h>
#define ULL unsigned long long
#define LL long long
#define endl '\n'
#define ALL(v) begin(v), end(v)
#define CONTAINS(container, value) container.find(value) != container.end()
using namespace std;
void kmp(string ,string);
vector<int> compute_lps(string);
int main() {
string txt,pat;
cin >> txt;
cin >> pat;
kmp(txt,pat);
return 0;
}
void kmp(string txt,string pat){
int n = txt.size();
int m = pat.size();
vector<int> lps = compute_lps(pat);
int i = 0,j = 0;
while(i < n){
if(pat[j] == txt[i]){
i++;
j++;
}
if(j == m){
cout << "found at " << i - j << endl;
j = lps[j-1];
}
else if(i < n && txt[i] != pat[j]){
if(j != 0) j = lps[j-1];
else i++;
}
}
}
vector<int> compute_lps(string pat){
int m = pat.size();
vector<int> lps(m);
int len = 0, i =1;
lps[0] = 0;
while(i < m){
if(pat[len] == pat[i]){
len++;
lps[i] = len;
i++;
}
else{
if(len != 0){
len = lps[len-1];
}else{
lps[i] = 0;
i++;
}
}
}
return lps;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
int Accx(int x , int y){
if(x < 1) return y;
return Accx(x-1,x*y);
}
int main(){
int x , y;
cin >> x >> y;
cout << Accx(x,y);
return 0;
}
<file_sep>#include<iostream>
using namespace std;
class Circle{
public:
float perimeter(int radius){
float p = 2 * 3.1415 * radius;
return p;
}
float area(int radius){
float a = 3.1415 * radius * radius;
return a;
}
};
int main(){
Circle c;
float r;
cout << "Enter the radius of circle : ";
cin >> r;
cout << "The perimeter of circle is " << c.perimeter(r) << endl;
cout << "The area of circle is " << c.area(r) << endl;
}
<file_sep>#include<iostream>
using namespace std;
int main(){
int arr[10];
int ar_size;
cout << "Enter array size\t";
cin >> ar_size;
cout << "Enter the array \n";
for(int i = 0; i < ar_size; i++){
cin >> arr[i];
}
int num;
cout << "Enter the number to search : ";
cin >> num;
bool check = true;
for(int i = 0; i < ar_size/2; i++){
if(arr[i] == num){
cout << "Found at index " << i+1 << endl;
check = false;
}
if(arr[ar_size-i] == num){
cout << "Found at indes " << ar_size-i+1 << endl;
check = false;
}
}
if(check) cout << "Not found";
return 0;
}
<file_sep>#include<iostream>
using namespace std;
class Greater{
public:
int greater(int a , int b, int c){
if(a > b && a > c){
return a;
}
else if ( b > c && b > a){
return b;
}
else return c;
}
};
int main(){
int a , b ,c;
cout << "Enter any 3 numbers " ;
cin >> a >> b >> c;
Greater g;
cout << "Greater no. is " << g.greater(a,b,c);
}
<file_sep>#include<iostream>
using namespace std;
void selection_sort(int [], int);
int main(){
int arr[] = {5,4,1,7,9,10};
int size = sizeof(arr)/sizeof(arr[0]);
selection_sort(arr,size);
for(int i = 0; i < size; i++){
cout << arr[i] << ' ';
}
return 0;
}
void selection_sort(int arr[] , int size){
int min , min_index;
for(int i = 0; i < size-1; i++){
for(int j = i+1; j < size; j++){
if(arr[i] > arr[j]){
swap(arr[i],arr[j]);
}
}
}
}
<file_sep>#include<iostream>
#include<vector>
#include<algorithm>
#include<climits>
using namespace std;
int myfunc(int i , int j ) { return i > j; }
//int maxsubarr(vector<int> &arr){
// int ans = INT_MIN;
// for(int size = 1; size <= arr.size(); size++){
// for(int si = 0; si < arr.size(); si++){
// if(si + size > arr.size()) break;
// int sum = 0;
// for(int i = si; i < (size + si); i++){
// sum += arr[i];
// }
// ans = max(sum,ans);
// }
// }
// return ans;
//}
//int maxsubarr(vector<int> &arr){
// int ans = INT_MIN;
// for(int si = 0; si < arr.size(); si++){
// int sum = 0;
// for(int size = 1; size <= arr.size(); size++){
// if(si + size > arr.size()) break;
// sum += arr[si+size-1];
// ans = max(sum,ans);
// }
// }
// return ans;
//}
int maxsubarr(int arr[], int n){
if(n == 1) return arr[0];
int m = n/2;
int left_mss = maxsubarr(arr,m);
int right_mss = maxsubarr(arr+m,n-m);
int left_sum = INT_MIN, right_sum = INT_MIN, sum = 0;
for(int i = m; i < n; i++){
sum += arr[i];
right_sum = max(right_sum,sum);
}
sum = 0;
for(int i = (m-1); i >= 0; i--){
sum += arr[i];
left_sum = max(left_sum,sum);
}
int ans = max(right_mss,left_mss);
return max(ans,left_sum+right_sum);
}
int maxsubseq(int arr[],int size){
sort(arr,arr+size,myfunc);
int max = arr[0];
for(int i = 1; i < size; i++){
if(max + arr[i] > max) max += arr[i];
else break;
}
return max;
}
int main(){
int t;
cin >> t;
while(t--){
int n;
cin >> n;
int arr[n];
for(int i = 0; i < n; i++) cin >> arr[i];
cout << maxsubarr(arr,n) << " ";
cout << maxsubseq(arr,n) << endl;
}
return 0;
}
<file_sep>//Deques unlike vectors they also have push_front ,pop_front and back ones too
#include<iostream>
#include<deque>
using namespace std;
void print_queue(deque<int> dq);
int main(){
//Intialization of deque...
deque<int> dq1(5,3); //intially 5 locations initialized to 3
deque<int> dq2(4); //intially 4 locations intialized to 0
deque<int> dq3;
int el1 = dq1.at(1); //similar as el = dq1[1];
int el2 = dq2[2];
cout << "dq1[1] = " << el1 << " dq2[2] = " << el2 << endl;
bool flag = dq3.empty();
cout << "flag is " << flag << " for dq3 (1 if empty else 0)"<< endl;
dq3.push_back(10); dq3.push_back(20); dq3.push_back(30);
cout << "After push back 10,20,30 on dq3\n";
print_queue(dq3);
dq3.pop_front();
cout << "After pop front on dq3\n";
print_queue(dq3);
dq3.pop_back();
cout << "After pop back on dq3\n";
print_queue(dq3);
dq3.push_front(35);
cout << "After push_front(35) on dq3\n";
print_queue(dq3);
cout << endl << dq3.back() << endl; //rear element of queue
cout << dq3.front(); //front element of queue
return 0;
}
void print_queue(deque<int> dq){
for(int i = 0; i < dq.size(); i++){
cout << dq.at(i) << ' ';
}
cout << endl;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
void sorter() {
vector<int> grida(5);
for(int i = 0; i < 5; i++){
grida[i] = i;
}
sort(grida.begin(),grida.end(),greater<int>());
for(int i = 0; i < 5; i++){
cout << grida[i];
}
}
int main() {
sorter();
return 0;
}
<file_sep>/*
Time : 2019-10-15,Tuesday
Desc : checking if graph is bipartite using BFS.
*/
#include <bits/stdc++.h>
using namespace std;
enum color{
white,
black,
none
};
int main(){
int v, e;
int a, b;
cin >> v >> e;
vector<vector<int>> g(v);
for (int i = 0; i < e; i++){
cin >> a >> b;
g[a].push_back(b);
g[b].push_back(a);
}
vector<color> colors(v, none);
bool isBipartite = true;
queue<int> Q;
Q.push(0);
colors[0] = color::white;
while (!Q.empty()){
int top = Q.front();
Q.pop();
for (auto it : g[top]){
if (colors[it] == color::none){
colors[it] = (color)(1 - colors[top]);
Q.push(it);
}
else if (colors[it] == colors[top]){
isBipartite = false;
break;
}
}
if (!isBipartite) break;
}
if (isBipartite)
cout << "Bipartite" << endl;
else
cout << "Not Bipartite" << endl;
return 0;
}<file_sep>#include<iostream>
class name{
// variables
public :
int x;
int y;
private :
int x1;
int x2;
//Methods
private:
void info(){
std::cout << "\n\nINFO: \nAll the private materials \ncan be accessed \nand used only inside the class \nbut can be used and accessed \nthrough public methods for outside of class\n\n";
}
public :
void set(int a ,int b){ //to set our private var.
this->x1 = a;
this->x2 = b;
}
int sthadd(){ //Adds private var.
int add = this->x1 + this->x2;
this->info();
return add;
}
int *GetPrivateVar(){ //You can't return two var. normally so use pointer and return addr.
int *a;
a = (int *)malloc(2*sizeof(int));
*a = this->x1;
*(a+1) = this->x2;
return a;
}
};
int main(){
name sth;
sth.x = 10; //direct access to a public variable (x,y) allowed
std::cout << "\nThis is our public variable : " << sth.x << std::endl;
sth.set(20,30); //Can't access private variable (x1,x2) so use set (public function)
int *h = sth.GetPrivateVar();
std::cout << "\nPrivate variables are: " << *h << " and " << *(h+1) << std::endl;
int a1 = sth.sthadd(); //adds private variable
std::cout << "Sum of variable is : " << a1 << std::endl; //result of above addition
}
<file_sep>//longest common subsequence , top down recursion with memoization table...
#include <bits/stdc++.h>
using namespace std;
string s1,s2;
vector<vector<int> > table(100,vector<int>(100,-1));
int lcs(int i,int j){
if(table[i][j] != -1) return table[i][j];
if(s1[i] == '\0' || s2[j] == '\0') return 0;
else if(s1[i] == s2[j]){
table[i][j] = 1+lcs(i+1,j+1);
return table[i][j];
}
else{
table[i][j] = max(lcs(i+1,j),lcs(i,j+1));
return table[i][j];
}
}
int main() {
cin >> s1 >> s2;
cout << lcs(0,0) << endl;
return 0;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
int root(int x, int parent[]){
if(parent[x] == -1){
return x;
}
return root(parent[x],parent);
}
void Union(int src, int dest,int parent[]){
int a = root(src,parent);
int b = root(dest,parent);
parent[a] = b;
}
int cycle_detector(pair<int,int> p[],int v, int e){
int parent[v];
fill(parent,parent+v,-1);
for(int i = 0; i < e; i++){
int source = p[i].first;
int dest = p[i].second;
if(root(source,parent) == root(dest,parent)){
return 1;
}
Union(source,dest,parent);
}
return 0;
}
int main(){
int e;
int v;
cin >> v;
cin >> e;
pair<int, int> p[e];
for(int i = 0; i < e; i++){
int src,dest;
cin >> src >> dest;
p[i] = make_pair(src,dest);
}
int status = cycle_detector(p,v,e);
if(status) cout << "Cycle is detected" << endl;
else cout << "Cycle is not detected" << endl;
return 0;
}
<file_sep>
#include<iostream>
#include<vector>
int v;
using namespace std;
int detector(int src, bool visited[],bool rstack[],vector< vector<int> > &graph){
if(!visited[src]){
visited[src] = true;
rstack[src] = true;
for(int i = 0; i < v; i++){
if(graph[src][i]){
if(!visited[i] && detector(i,visited,rstack,graph)) return true;
else if(rstack[i]) return true;
}
}
}
rstack[src] = false;
return false;
}
int main(){
int e;
cin >> v >> e;
vector< vector<int> > graph(v,vector<int> (v,0));
for(int i = 0; i < e; i++){
int a , b;
cin >> a >> b;
graph[a][b] = 1;
}
bool visited[v];
fill(visited,visited+v,false);
bool Rstack[v];
fill(Rstack,Rstack+v,false);
bool flag = false;
for(int i = 0; i < v; i++){
if(detector(i,visited,Rstack,graph)){
flag = true;
break;
}
}
if(flag) cout << "Cycle" << endl;
else cout << "No cycle" << endl;
return 0;
}
<file_sep>#include<iostream>
using namespace std;
void insertion_sort(int arr[],int size);
void print(int arr[],int size){
for(int i = 0; i < size; i++){
cout << arr[i] << " ";
}
}
int main(){
int arr[] = {1,4,3,10};
int size = sizeof(arr)/sizeof(arr[0]);
insertion_sort(arr,size);
for(int i = 0; i < size; i++){
cout << arr[i] << " ";
}
return 0;
}
void insertion_sort(int arr[], int size){
int value , index;
for(int i = 1; i < size; i++){
value = arr[i];
index = i - 1;
while(index >= 0 && value < arr[index]){
arr[index + 1] = arr[index];
index-- ;
}
arr[index+1] = value;
}
}
<file_sep>#include <bits/stdc++.h>
#define ull unsigned long long int
#define endl '\n'
#define mp make_pair
using namespace std;
int dims[100];
int n;
ull matrixChain(){
ull m[n][n];
int q,j;
for(int i = 0; i < n; i++) m[i][i] = 0;
for(int len = 2; len < n; len++){
for(int i = 1; i < n-len+1; i++){
j = i+len-1;
m[i][j] = INT_MAX;
for(int k = i; k <= j-1; k++){
q = m[i][k] + m[k+1][j] + dims[i-1]*dims[k]*dims[j];
if(q < m[i][j]){
m[i][j] = q;
}
}
}
}
return m[1][n-1];
}
int main() {
cout << "Enter the size of matrix array : ";
cin >> n;
cout << "Enter the dimension of matrix array :\n";
for(int i = 0; i < n; i++) cin >> dims[i];
int ans = matrixChain();
cout <<"The minimum possible no. of multiplication is " << ans << endl;
return 0;
}<file_sep>// Unordered sets uses hash tables to store data
// unordered multiset allows multiples data
#include<iostream>
#include<unordered_set>
using namespace std;
int main(){
cout << "\n\nUnordered set\n\n";
unordered_set<int> st2;
for(int j = 0; j <= 4; j++){
st2.insert(j+10);
}
for(auto it = st2.begin(); it != st2.end(); it++){
cout << *it << endl;
}
}
<file_sep>#include<iostream> //for io
#include<iomanip> //for setw
using namespace std;
int main(){
cout << 2017 << " is today's year." << endl; //either do code like this if you write using namespace.. as above
std::cout << 11 << " is today's month." << std::endl; //or do code like this if no namespace std
std::cout << 9 << " is today's date." << std::endl; //using no namespace is good in rare situations.
std::cout << std::setw (5) << 9 << " is today's date." << std::endl;
std::cout << std::setw (10) << 2017 << " is today's year." << std::endl << set::setw();
return 0;
}
//endl is to terminate the line..
<file_sep>/*
Time : 2019-10-15,Tuesday
Desc : checking if graph is bipartite using DFS.
*/
#include <bits/stdc++.h>
#define endl '\n'
#define pb(x) push_back(x)
#define ALLONS_Y ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
using namespace std;
enum color{
white,
black,
none
};
bool DFS(vector<vector<int>> &g, int src , vector<color> &colors,color currentColor = color::white){
for(auto it : g[src]){
if (colors[it] == color::none ){
// * color the node with adjacent color.
colors[it] = (color)(1 - currentColor);
// * recursively color other node with appropriate color.
// * if any single node of graph returns false, then return false until it reaches to main()
// * to avoid checking for unchecked nodes which may return true.
if(!DFS(g, it, colors, colors[it])) return false;
}
else if (colors[it] == currentColor){
// * if parent and child have same color , then it is not bipartite so return false.
return false;
}
}
return true;
}
int main() {
ALLONS_Y;
int v, e;
int src, dest;
cin >> v >> e;
vector<vector<int> > g(v);
for (int i = 0; i < e; i++){
cin >> src >> dest;
g[src].push_back(dest);
g[dest].push_back(src);
}
vector<color> colors(v, color::none);
// * Here 0 is assumed to be source vertex which color is white,
colors[0] = color::white;
bool isBipartite = DFS(g,0,colors);
if(isBipartite) cout << "Bipartite" << endl;
else cout << "Not Bipartite" << endl;
return 0;
}<file_sep>#include <bits/stdc++.h>
using namespace std;
string s1,s2;
int lcs(){
int table[s1.size()+1][s2.size()+1];
for(int i= 0; i <= s1.size(); i++){
for(int j = 0; j <= s2.size(); j++){
if(i == 0 || j == 0){
table[i][j] = 0;
}
else if(s1[i-1] == s2[j-1]){
table[i][j] = table[i-1][j-1] + 1;
}
else{
table[i][j] = max(table[i-1][j],table[i][j-1]);
}
}
}
return table[s1.size()][s2.size()];
}
int main() {
cin >> s1 >> s2;
cout << lcs() << endl;
return 0;
}
<file_sep>//Pointer to function , also known as callback function.
#include<iostream>
typedef void (*FunPtr)(int, int);
using namespace std;
void add(int i , int j){
cout << i << " + " << j << " = " << i+j << endl;
}
void sub(int i , int j){
cout << i << " - " << j << " = " << i-j << endl;
}
int main(){
FunPtr ptr;
ptr = &add;
ptr(1,2);
ptr = ⊂
ptr(3,1 );
//The other way around...
void (*ptr1) (int,int) = add; //can also use &add
ptr1(3,5); //similar to as calling add(3,5)
return 0;
}
<file_sep>#include<iostream>
#include<iomanip>
int main(){
bool a = true;
char c = 'w'; //signed(+ve and -ve ASCII) and unsigned(+ve) form
int n ; //signed and unsigned form and also long,short form
long long jlk ; //really big numbers
float f = 0.5769;
double d;
n = 10;
n = 132; //redeclaration
std::cout << " Number is " << n << std::endl;
int year = 2017,month = 1,date = 9;
std::cout << year << '/' << month << '/' << date << std::endl;
std::cout << year << '/' << std::setw(2) << month << '/' << std::setw(2) << date << std::endl;
std::cout << year << '/' << std::setw(2) << std::setfill('0') << month << '/' << std::setw(2) << std::setfill('0') << date;
//setfill to fill empty space with any character.
}
<file_sep>//finds the all possible combinations with r = 3 and given n.
#include <bits/stdc++.h>
#define ULL unsigned long long
#define LL long long
#define endl '\n'
#define ALL(v) begin(v), end(v)
#define CONTAINS(container, value) container.find(value) != container.end()
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for(int i = 1; i <= n-2; i++){
for(int j = i+1; j <= n-1; j++){
for(int k = j+1; k <= n; k++){
cout << i <<' ' << j<< ' ' << k << endl;
}
}
}
return 0;
}
<file_sep>#include<iostream>
#include<list>
#include<queue>
using namespace std;
int main(){
int v, e;
cin >> v >> e;
//vector< vector<int> > graph(v+1,vector<int>(v+1,0));
list<int> lst[v+1];
for(int i = 1; i <= e; i++){
int a, b;
cin >> a >> b;
lst[a].push_back(b);
lst[b].push_back(a);
}
//BFS logic
int src = 1;
queue<int> q;
vector<bool> visited(v+1,false);
q.push(src);
visited[src] = true;
while(!q.empty()){
int u = q.front();
cout << u << " ";
q.pop();
for(list<int>::iterator it = lst[u].begin(); it != lst[u].end(); it++){
if(!visited[*it]){
q.push(*it);
visited[*it] = true;
}
}
}
return 0;
}
<file_sep>#include<iostream>
#include<algorithm>
using namespace std;
void bubble_sort(int a[],int n){
for(int i = 0; i < n-1; i++){
for(int j = 0; j < n-i-1; j++){
if(a[j] > a[j+1]){
swap(a[j],a[j+1]);
}
}
}
}
int main(){
int arr[] = {5,4,1,7,9,10};
int size = sizeof(arr)/sizeof(arr[0]);
bubble_sort(arr,size);
for(int i = 0; i < size; i++){
cout << arr[i] << ' ';
}
return 0;
}
<file_sep>//Tree inserts the characters as data and traverses it in BFS and DFS...
#include<iostream>
#include<queue>
using namespace std;
struct bt{
bt * left;
bt * right;
char data;
};
void insert(bt ** root, char data);
void BFS(bt * root);
void preorder(bt * root);
int height(bt * root);
int main(){
bt * root = NULL;
char data;
cout << "Enter any 7 characters:\n";
for(int i = 0; i < 7; i++){
cin >> data;
insert(&root,data);
}
cout << "BFS: \n";
BFS(root);
cout << endl;
cout << "DFS(in-order):\n";
preorder(root);
cout << endl << "Height of tree is : " << height(root);
return 0;
}
void BFS(bt * root){
if(root == NULL) return ;
queue<bt *> Q;
Q.push(root);
while(!Q.empty()){
bt * current = Q.front();
cout << current->data << " ";
if(current->left != NULL) Q.push(current->left);
if(current->right != NULL) Q.push(current->right);
Q.pop();
}
}
void insert(bt ** r, char data){
if(*r == NULL){
(*r) = new bt();
(*r)->data = data;
(*r)->left = NULL;
(*r)->right = NULL;
}
else if ( data <= (*r)->data){
insert(&((*r)->left),data);
}
else
insert(&((*r)->right),data);
}
void preorder(bt * root){
if(root == NULL) return;
preorder(root->left);
cout << root->data << " ";
preorder(root->right);
}
int height(bt * root){
if (root == NULL){
return -1;
}
int Lheight = height(root->left);
int Rheight = height(root->right);
int ans = Lheight > Rheight ? Lheight : Rheight;
return ans+1;
}
<file_sep>//Detecting loop in linked list using set(hash table) & Floyd's cycle finding algorithm
/*
Alternative method:
less efficient method (uses more memory) :
-> put a field(visit) in node
-> initialize all isit field to false
-> visit the node one by one
-> if visit field is false change it to true
-> if already true then loop detected
*/
#include<iostream>
#include<unordered_set>
using namespace std;
struct node{
int data;
node * next;
};
void insert(int data, node** head_r){
node * p = new node();
p->data = data;
p->next = *head_r;
*head_r = p;
}
//Hash table method
bool detectLoop(node* head){
node *p = head;
unordered_set<node * > s;
while(p != NULL){
if(s.find(p) != s.end()) return true; //if already inserted
s.insert(p);
p = p->next;
}
return false;
}
//Floyd's cycle finding algorithm
bool detectLoop2(node * head){
node *slow , *fast; //uses fast pointer and slow pointer
fast = head;
slow = head;
while(slow && fast && fast->next){
slow = slow->next;
fast = fast->next->next;
if(slow == fast) return true;
}
return false;
}
int main(){
node * head = NULL;
insert(10,&head);
insert(20,&head);
insert(30,&head);
insert(40,&head);
insert(50,&head);
head->next->next->next->next = head; //Creating a loop in list
if(detectLoop2(head)){
cout << "Loop found" << endl;
}
else cout << "No loop" << endl;
return 0;
}
<file_sep>
#include<iostream>
#include<stack>
#include<queue>
#include<vector>
#define INF INT8_MAX
using namespace std;
int v;
void function(vector< vector<int> > &graph){
int key[v];
fill(key,key+v,INF);
key[0] = 0;
bool flag;
for(int i = 0; i < v - 1; i++){
flag = true;
//use pairs to avoid nested loop below for edge(u,j)...
for(int u = 0; u < v; u++){
for(int j = 0; j < v; j++){
if(graph[u][j] && key[u] != INF && key[j] > graph[u][j] + key[u]){
key[j] = graph[u][j] + key[u];
flag = false;
}
}
}
if(flag){ cout << "broke in" << i << " iterations" << endl; break;}
}
//above iteration should have relaxed every edge if no negative edge cycle present...
for(int u = 0; u < v; u++){
for(int j = 0; j < v; j++){
if(graph[u][j] && key[u] != INF && key[j] > graph[u][j] + key[u]){
cout << "negative cycle detected" << endl;
exit(2);
}
}
}
for(int k = 0; k < v; k++){
cout << k << " " << key[k] << endl;
}
}
int main(){
int e;
cin >> v >> e;
vector< vector<int> > graph(v,vector<int>(v,0));
for(int i = 0; i < e; i++){
int a, b,c;
cin >> a >> b >> c;
graph[a][b] = c;
}
function(graph);
return 0;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
int v,e;
cin >> v >> e;
int a,b;
list<int> l[v];
for(int i = 0; i < e; i++){
cin >> a >> b;
l[a-1].push_back(b-1);
l[b-1].push_back(a-1);
}
vector<bool> visited(v,false);
queue<int> Q;
Q.push(0);
visited[0] = true;
int search;
cin >> search;
vector<int> dist(v);
while(!Q.empty()){
int u = Q.front();
Q.pop();
if(u == search-1) cout << dist[u]; //distance from the source vertex...
for(list<int>::iterator it = l[u].begin(); it != l[u].end(); it++){
if(!visited[*it]){
Q.push(*it);
visited[*it] = true;
dist[*it] = dist[u] + 1;
}
}
}
return 0;
}
<file_sep>#include<iostream>
#include<vector>
using namespace std;
void functions(vector<vector<int>> vets);
int main(){
vector<vector<int>> vet;
for(int i = 0; i < 3; i++){
vector<int> temp;
for(int j = 0; j < 3; j++){
temp.push_back(i);
}
vet.push_back(temp);
}
for(int i = 0 ; i < vet.size(); i++){
for(int j = 0 ; j < vet[i].size(); j++){
cout << vet[i][j] << " ";
}
cout << endl;
}
cout << "\nBy using the functions\n";
functions(vet);
return 0;
}
//passing by value
void functions(vector<vector<int>> vets){
for(int i = 0; i < vets.size(); i++){
for(int j = 0; j < vets[i].size(); j++){
cout << vets[i][j] << " ";
}
cout << endl;
}
}
<file_sep>//segment Tree to find the max value in a given segment...
#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
int getMid(int start, int end){
return start+(end-start)/2;
}
int constructUtil(int arr[],int* st, int size, int start, int end,int idx){
if(start == end){
st[idx] = arr[start];
return arr[start];
}
int mid = getMid(start,end);
st[idx] =
constructUtil(arr,st,size,start,mid,2*idx+1)^
constructUtil(arr,st,size,mid+1,end,2*idx+2);
return st[idx];
}
int* construct(int arr[],int size){
int h = ceil(log2(size));
int m = 2* pow(2,h) -1;
int *st = new int[m];
constructUtil(arr,st,size-1,0,size-1,0);
return st;
}
int getmax(int* st, int qs , int qe,int start,int end,int idx){
if(qs <= start && qe >= end ){
return st[idx];
}
if(qs > end || qe < start) return 0;
int mid = getMid(start,end);
return getmax(st,qs,qe,start,mid,2*idx+1) ^
getmax(st,qs,qe,mid+1,end,2*idx+2);
}
int main(){
int t;
cin >> t;
while(t--){
int s;
cin >> s;
int arr[s];
int data;
for(int i = 0; i < s; i++){
cin >> data;
arr[i] = data;
}
int* st = construct(arr,s);
int q;
cin >> q;
while(q--){
int l,r;
cin >> l >> r;
cout << getmax(st,l,r,0,s-1,0) << endl;
}
}
return 0;
}
<file_sep>/*
Time : 2019-10-18,Friday
Desc : no description
*/
#include <bits/stdc++.h>
#define endl '\n'
#define ALLONS_Y ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define pii pair<int,int>
using namespace std;
int prims(vector<pii> g[],int v){
priority_queue<pii, vector<pii>,greater<pii> > pq;
vector<bool> visited(v,false);
int minCost = 0;
pq.push({0,0});
while(!pq.empty()){
pii top = pq.top();
pq.pop();
if(visited[top.second]){
continue;
}
minCost += top.first;
visited[top.second] = true;
for(auto it : g[top.second]){
if(!visited[it.second]){
pq.push(it);
}
}
}
return minCost;
}
int main() {
ALLONS_Y;
int v,e;
cin >> v >> e;
vector<pii> g[v];
int src,dest,wt;
for(int i = 0; i < e; i++){
cin >> src >> dest >> wt;
g[src].push_back({wt,dest});
g[dest].push_back({wt,src});
}
cout << prims(g,v) << endl;
return 0;
}<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef pair<int,long long int> mypair;
#define endl '\n'
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
int v,e;
int src,dest,start;
long long int wt;
cin >> t;
while(t--){
cin >> v >> e;
list<mypair> l[v];
for(int i = 0; i < e; i++){
cin >> src >> dest >> wt;
l[src-1].push_back(make_pair(dest-1,wt));
l[dest-1].push_back(make_pair(src-1,wt));
}
cin >> start;
start--;
vector<long long int> key(v,INT_MAX);
key[start] = 0;
vector<bool> visited(v,false);
priority_queue<mypair,vector<mypair>, greater<mypair> > pq;
pq.push(make_pair(0,start));
while(!pq.empty()){
int u = pq.top().second;
visited[u] = true;
pq.pop();
for(list<mypair>::iterator it = l[u].begin(); it != l[u].end(); it++){
if(key[u] + it->second < key[it->first]){
key[it->first] = key[u] + it->second;
pq.push(make_pair(key[it->first],it->first));
}
}
}
vector<long long int> result;
for(int i = 0; i < v; i++){
if(i != start){
if(key[i] != INT_MAX)
result.push_back(key[i]);
else result.push_back(-1);
}
}
for (int i = 0; i < result.size(); i++) {
cout << result[i];
if (i != result.size() - 1) {
cout << " ";
}
}
cout << endl;
}
return 0;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
int min_key(list<pair<int,int> > g[],vector<bool> &visited,vector<int> &key){
int min_idx = -1, min_val = INT_MAX;
for(int i = 0; i < visited.size(); i++){
if(!visited[i] && key[i] < min_val){
min_val = key[i];
min_idx = i;
}
}
return min_idx;
}
void dijks(list<pair<int,int> >lists[],int v){
int start = 0;
vector<bool> visited(v,false);
vector<int> parent(v);
vector<int> key(v,INT_MAX);
parent[start] = -1;
key[start] = 0;
for(int i = 0; i < v; i++){
int u = min_key(lists,visited,key);
visited[u] = true;
list<pair<int,int> >::iterator it;
for(it = lists[u].begin(); it != lists[u].end(); it++){
if(!visited[it->first] && key[u] + it->second < key[it->first]){
key[it->first] = key[u] + it->second;
parent[it->first] = u;
}
}
}
cout << endl << "node," << " parent " << " and " << " wt from index 1 : " << endl;
for(int i = 1; i < v; i++){
cout << i << "-> " << parent[i] << " : " << key[i] << endl;
}
}
int main(){
int v,e;
cin >> v >> e;
list<pair<int,int> > list[v];
int src,dest,wt;
for(int i = 0; i < e; i++){
cin >> src >> dest >> wt;
list[src].push_back(make_pair(dest,wt));
list[dest].push_back(make_pair(src,wt));
}
dijks(list,v);
return 0;
}
<file_sep>/*
In this program of segment tree , we update the old nodes in the range [l,r] to a new value
we may also increment the value with certain diff. value instead of updating with a new value.
*/
#include <bits/stdc++.h>
#define endl '\n'
int *lazy;
using namespace std;
int construct_util(int *st, int arr[],int ss, int se, int idx){
if(ss == se){
st[idx] = arr[ss];
return arr[ss];
}
int mid = ss + (se - ss)/2;
st[idx] = construct_util(st,arr,ss,mid,2*idx+1) + construct_util(st,arr,mid+1,se,2*idx+2);
return st[idx];
}
int *construct(int arr[], int size){
int h = ceil( log2(size));
int m = 2*pow(2,h) - 1;
int *st = new int[m];
lazy = new int[m];
construct_util(st,arr,0,size-1,0);
return st;
}
int get_sum(int *st,int ss, int se, int qs, int qe,int idx){
if(lazy[idx] != 0){
st[idx] = (se - ss + 1)*lazy[idx]; //use += if updating with only diff
if(ss != se){
lazy[2*idx+1] = lazy[idx]; //here too and some other places...
lazy[2*idx+2] = lazy[idx];
}
lazy[idx] = 0;
}
if(qs > se || qe < ss) return 0;
if(qs <= ss && qe >= se){
return st[idx];
}
int mid = ss + (se - ss)/2;
return get_sum(st,ss,mid,qs,qe,2*idx+1) +
get_sum(st,mid+1,se,qs,qe,2*idx+2);
}
void update(int *st, int ss,int se, int qs,int qe,int idx ,int nv){
if(lazy[idx] != 0){
st[idx] = (se - ss + 1) * lazy[idx];
if(ss != se){
lazy[2*idx+1] = lazy[idx];
lazy[2*idx+2] = lazy[idx];
}
lazy[idx] = 0;
}
if(qe < ss || qs > se) return ;
if(qs <= ss && qe >= se){
st[idx] = (se - ss + 1) * nv;
if(ss != se){
lazy[2*idx+1] = nv;
lazy[2*idx+2] = nv;
}
return ;
}
int mid = ss + (se - ss)/2;
update(st,ss,mid,qs,qe,2*idx+1,nv);
update(st,mid+1,se,qs,qe,2*idx+2,nv);
st[idx] = st[2*idx+1] + st[2*idx+2];
}
int main() {
int arr[] = {1,2,3,4,5,6,7,8};
int size = sizeof(arr)/sizeof(arr[0]);
for(int i = 0; i < size; i++) cout << arr[i] << " ";
cout << endl;
int *st = construct(arr,size);
cout << get_sum(st,0,size-1,3,7,0) << endl;
update(st,0,size-1,3,5,0,8); //ss,se,qs,qe,idx,nv
for(int i = 3; i <= 5; i++) arr[i] = 8;
for(int i = 0; i < size; i++) cout << arr[i] << " ";
cout << endl;
cout << get_sum(st,0,size-1,3,7,0) << endl;
return 0;
}
<file_sep>#include<iostream>
#include<vector>
using namespace std;
int v;
int minKey(bool visited[],int key[]){
int min = INT_MAX, minidx = -1;
for(int i = 0; i < v; i++){
if(!visited[i] && key[i] <= min){
min = key[i];
minidx = i;
}
}
return minidx;
}
void dijkstra(vector<vector<int> > &graph){
int src = 0;
bool visited[v];
fill(visited,visited+v,false);
int key[v];
fill(key,key+v,INT_MAX);
key[src] = 0;
for(int i = 1; i < v - 1; i++){
int u = minKey(visited,key);
visited[u] = true;
for(int j = 1; j < v; j++){
if(graph[u][j] && !visited[j] && key[u] != INT_MAX
&& graph[u][j] + key[u] < key[j]){
key[j] = graph[u][j] + key[u];
}
}
}
cout << endl;
cout << "src" << "| dis" << endl;
cout << "--------" << endl;
for(int a = 0 ; a < v; a++){
cout << " " << a << " | " << key[a] << endl;
}
}
int main(){
int e;
cin >> v >> e;
vector< vector<int> > graph(v,vector<int>(v,0));
for(int i = 1; i <= e; i++){
int src,dest,wt;
cin >> src >> dest >> wt;
graph[src][dest] = wt;
graph[dest][src] = wt;
}
dijkstra(graph);
return 0;
}
<file_sep>#include<iostream>
#include<vector>
using namespace std;
void print_vector(vector<int> arr){
for(int i = 0;i < arr.size(); i++){
cout << arr[i] << '\t';
}
cout << endl;
}
int main(){
vector<int> arr; //vector are like arrays and uses larger memory and is dynamic
arr.push_back(10); //add a integer location and puts 10 in that location;
arr.push_back(20);
arr.push_back(30);
arr.push_back(40);
print_vector(arr);
arr.pop_back(); //Pops the last added integer location
print_vector(arr);
int el = arr.at(1); // or el = arr[1];
cout << el;
return 0;
}
<file_sep>//Functions in cpp
#include<iostream>
using namespace std;
inline int adder(int a,int b); //Inline function as like macro use for one or two line function
int add(int,int);
double add(double , double);
int add(int,int,int);
int mul(int a, int b, int c = 100); //c is 100 by default ,here c is default arguement
int main(){
//Function overloading and polymorphism
cout << add(10,20) << endl;
cout << add(23.23,34.78) << endl;
cout << add(10,20,30) << endl;
cout << mul(10,20) << endl; //Only two arguements instead of three
cout << mul(10,20,30) << endl; //Giving all the arguements
cout << adder(20 , 10); //Inline function adder
return 0;
}
int add(int a , int b){
return a+b;
}
double add(double a,double b){
return a+b;
}
int add(int a , int b, int c){
return a+b+c;
}
int mul(int a , int b , int c ){ //If c in not passed 100 is by default as per function definition;
return a*b*c;
}
inline int adder(int a , int b){
return a+b;
}
<file_sep>#include<iostream>
#include<vector>
using namespace std;
void DFS(vector<vector<int> > &graph, int src, bool visited[]){
visited[src] = true;
// cout << src << " ";
for(int i = 1; i < graph.size(); i++){
if(visited[i] == false && graph[src][i]){
DFS(graph,i,visited);
}
}
}
int main(){
int v;
int e;
int a, b;
cin >> v >> e;
bool visited[v+1];
fill(visited,visited+v+1,false);
vector<vector<int> > graph(v + 1, vector<int> (v + 1,0));
for(int i = 0; i < e; i++){
cin >> a >> b;
graph[a][b] = 1;
graph[b][a] = 1;
}
int count = 0;
for(int i = 1; i <= v; i++){
if(visited[i] == false){
DFS(graph,i,visited);
count++;
}
}
cout << count << " is the no. of components ";
return 0;
}
<file_sep>#include<iostream>
using namespace std;
class Code{
int id;
public:
Code(){
}
Code(int a){
id = a;
}
Code(const Code & a){ //Reference to object, copies the data of passed object
id = a.id;
}
void display(void){
cout << id << endl;
}
};
int main(){
Code a(10);
Code b(a); //invokes copy constructor
Code c = a; //invokes copy constructor
Code d;
d = c; //doesn't invokes copy constructor but uses overloaded '='
cout << "Id of a = " ; a.display();
cout << "Id of b = " ; b.display();
cout << "Id of c = " ; c.display();
cout << "Id of d = " ; d.display();
return 0;
}
<file_sep>#include <bits/stdc++.h>
#define ull unsigned long long int
#define ll long long int
#define endl '\n'
#define pb(x) push_back(x)
#define mp make_pair
#define ALLONS_Y ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
using namespace std;
int main() {
ALLONS_Y;
int n,e;
cin >> n >> e;
// vector< vector<int> > v(n);
list<int> v[n];
for(int i = 0; i < e; i++){
int src,dest;
cin >> src >> dest;
v[src-1].pb(dest-1);
v[dest-1].pb(src-1);
}
queue<int> Q;
Q.push(0);
int visited[n] = {0}; // false == 0
visited[0] = 1; // true == 1
while(!Q.empty()){
int top = Q.front();
Q.pop();
cout << top+1 << " ";
for(auto it = v[top].begin(); it != v[top].end(); it++){
if(!visited[*it]){
Q.push(*it);
visited[*it] = 1;
}
}
}
return 0;
}
<file_sep>#include<iostream>
using namespace std;
class fact{
int f = 1;
public:
fact(int a){
for(int i = 1; i <= a; i++)
f = f * i;
}
fact(fact & c){
f = c.f;
}
int display(){
return f;
}
};
int main(){
fact a(3);
fact b(a);
cout << b.display() << endl;
cout << a.display();
return 0;
}
<file_sep>#include<iostream>
int main(){
int n1,n2,n3,n4,n5;
std::cout << "Enter any five integers seprated by space :" << std::endl;
std::cin >> n1 >> n2 >> n3 >> n4 >> n5;
int sum = (n1 + n2 + n3 + n4 + n5);
// sum and 5 is both int so sum/5 also gives int , hence we use 5.0f to get float point
float avg = sum/5.0f;
std::cout << "The sum is " << sum << " and the average is " << avg ;
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
int minkey(bool visited[], int keys[], int v)
{
int min = 1000, min_idx = -1;
for (int i = 0; i < v; i++)
{
if (!visited[i])
{
if (min > keys[i])
{
min = keys[i];
min_idx = i;
}
}
}
return min_idx;
}
void printparent(int u,int parent[]){
if(u != -1){
cout << u << " ";
printparent(parent[u],parent);
}
}
void shortestPath(int v, int e, list<pair<int, int>> nodes[])
{
int source = 0;
bool visited[v];
int keys[v];
int parent[v];
for (int i = 0; i < v; i++)
{
visited[i] = false;
keys[i] = 1000;
parent[i] = -1;
}
keys[source] = 0;
for (int i = 0; i < v-1; i++)
{
int u = minkey(visited, keys, v);
visited[u] = true;
for (auto i : nodes[u])
{
if (!visited[i.first] && keys[u] + i.second < keys[i.first])
{
keys[i.first] = keys[u] + i.second;
parent[i.first] = u;
}
}
}
for(int i = 0; i < v; i++){
cout << "keys[" << i << "] = " << keys[i] << endl;
}
// printparent(5,parent);
cout << endl;
}
int main()
{
int v, e;
int src, dest, wt;
cin >> v >> e;
list<pair<int, int>> nodes[v];
for (int i = 0; i < e; i++)
{
cin >> src >> dest >> wt;
nodes[src].push_back(make_pair(dest, wt));
nodes[dest].push_back(make_pair(src, wt));
}
shortestPath(v, e, nodes);
return 0;
}<file_sep>//To put the records (name) and keys (weight) in order with respect to keys...
#include<iostream>
#include<vector>
#include<string>
using namespace std;
void bubble_sort(int wt[], string name[],int size){
for(int i = 0; i < size-1; i++){
for(int j = 0; j < size-i-1; j++){
if(wt[j] > wt[j+1]){
swap(wt[j],wt[j+1]);
swap(name[j],name[j+1]);
}
}
}
}
int main(){
int wt[5];
string name[5];
int size = 5;
cout << "Enter the 5 names and their weights respectively :\n";
cout << "\n\nName\t\t" << "Weight\n";
for(int i = 0; i < 5; i++){
cin >> name[i] ;
cin >> wt[i] ;
}
bubble_sort(wt,name,size);
cout << "\n\nAfter sorting:\n\n";
cout << "\n\nName\t\t" << "Weight\n";
for(int i = 0; i < 5; i++){
cout << name[i] << "\t\t" << wt[i] << endl;
}
return 0;
}
<file_sep>#include<iostream>
#include<fstream>
using namespace std;
/*
file modes :
-----------------
ios::app Append to end-of-file
ios::ate go to end of file on opening
ios::binary binary file
ios::in open file for reading only
ios::out open file for writing only
ios::trunc Delete content of file if exists
etc...
*/
int main(){
ofstream fout;
//using bitwise or(|) we may combine modes...
fout.open("new file.txt",ios::binary|ios::app); //open binary file and append date to it's end
fout << "hello " << endl;
fout.close();
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
//bottom up solutions for coin change...
int no_of_ways(int total,int size,int coins[]){
int table[total+1][size];
for(int i = 0; i < size; i++) table[0][i] = 1;
for(int i = 1; i < total+1; i++){
for(int j = 0; j < size; j++){
int x = (i - coins[j]) >= 0 ? table[i-coins[j]][j] : 0;
int y = (j > 0) ? table[i][j-1] : 0;
table[i][j] = x+y;
}
}
return table[total][size-1];
}
//another space optimized bottom up solution for coin change...
int no_of_ways2(int total,int size,int coins[]){
int table[total+1] = {1};
for(int i = 0; i < size; i++){
for(int j = coins[i]; j < total+1; j++){
table[j] += table[j-coins[i]];
}
}
return table[total];
}
int main() {
int n;
scanf("%d",&n);
int k;
scanf("%d",&k);
int coins[k];
for(int i = 0; i < k; i++) scanf("%d",&coins[i]);
cout << no_of_ways(n,k,coins) << endl;
cout << no_of_ways2(n,k,coins) << endl;
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
void dfs(vector<int> g[],int src,vector<bool> &visited,stack<int> &st){
visited[src] = true;
for(auto it : g[src]){
if(!visited[it]) dfs(g,it,visited,st);
}
st.push(src);
}
void dfs2(vector<int> g[],int src,vector<bool> &visited){
visited[src] = true;
cout << src << " ";
for(auto it : g[src]){
if(!visited[it]) dfs2(g,it,visited);
}
}
int main() {
int nodes,edges;
cin >> nodes >> edges;
vector<int> g[nodes];
int src,dest;
for(int i = 0; i < edges; i++){
cin >> src >> dest;
g[src].push_back(dest);
}
vector<bool> visited(nodes,false);
stack<int> st;
for(int i = 0; i < nodes; i++)
if(!visited[i])
dfs(g,i,visited,st);
//upto here it is same as topological sort algorithm...
//a new graph , graph gi is invert of graph g
vector<int> gi[nodes];
for(int i = 0; i < nodes; i++){
for(auto it : g[i]){
gi[it].push_back(i);
}
}
//all vertices of gi are unvisited...
for(int i = 0; i < nodes; i++) visited[i] = false;
while(!st.empty()){
//use dfs using stack top on gi...
int top = st.top();
st.pop();
//only call dfs for unvisited node, for others just pop only...
if(!visited[top]){
dfs2(gi,top,visited); //prints all connected components using dfs...
cout << endl;
}
}
return 0;
}
<file_sep>//Simulating a list through doubly circular linked list
#include<iostream>
using namespace std;
class link{
private:
link * prev;
link * next;
int data;
link * start;
link * last;
public:
link(){
this->start = NULL;
this->last = NULL;
}
void clear();
void push_front(int data);
void push_back(int data);
void display();
void pop_front();
void pop_back();
void reverse();
int length();
};
void link::clear(){
link *p = start;
do{
if(start == last){
start = last = NULL;
return;
}
p = start;
start = start->next;
last->next = start;
delete p;
}while(p != start);
}
void link::push_front(int data){
link * p = new link();
p->data = data;
if(start == NULL){
start = p;
last = p;
p->prev = p; //start->prev = last
p->next = p; //last->next = start
}
else{
p->next = start;
p->prev = last;
start->prev = p;
last->next = p;
start = p;
}
}
void link::display(){
if(start == NULL){
cout << "\n***Empty list***\n";
return;
}
cout << "\nThe elements of lists are:\n";
int i = 0;
link * p = start;
do{
cout << i++ << ". " << p->data << endl;
p = p->next;
}while(p != start);
}
int link::length(){
int i = 0;
link * p = start;
if(start == NULL){
cout << 0 << endl;
return i;
}
do{
i++;
p = p->next;
}while(p != start);
return i;
}
void link::push_back(int data){
link * p = new link();
p->data = data;
if(last == NULL){
start = last = p;
p->next = p->prev = p;
}
else{
p->next = start;
p->prev = last;
last->next = p;
start->prev = p;
last = p;
}
}
void link::pop_front(){
if(start == NULL){
cout << "\n***Empty list***\n";
return;
}
else if(start == last){
start = NULL;
last = NULL;
}
else{
link *p = start;
start = start->next;
start->prev = last;
last->next = start;
delete p;
}
}
void link::pop_back(){
if(start == NULL){
cout << "\n***Empty list***\n";
return;
}
else if(start == last){
start = NULL;
last = NULL;
}
else{
link *p = last;
last = last->prev;
last->next = start;
start->prev = last;
}
}
void link::reverse(){
if(last == NULL){
cout << "\n***Empty list***\n";
return;
}
int i = 0;
cout << "\nReversed version of the list is:\n";
link * p = last;
do{
cout << i++ << " . " << p->data << endl;
p = p->prev;
}while(p != last);
}
int main(){
link A;
A.push_back(3);
A.push_back(12);
A.push_back(15);
A.push_front(100);
A.display();
A.reverse();
cout << "\nNo. of datas are: " << A.length();
A.pop_front();
A.clear();
return 0;
}
<file_sep>#include <bits/stdc++.h>
#define ull unsigned long long int
#define ll long long int
#define endl '\n'
#define all(v) begin(v), end(v)
#define pb(x) push_back(x)
#define mp make_pair
#define ALLONS_Y ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define contains(container, value) container.find(value) != container.end()
#define rep(i,a,b) for(int i = a; i < b; i++)
using namespace std;
int rod[100];
int rod_cut(int l,int arr[]){
if(l < 1) return 0;
if(rod[l] != -1) return rod[l];
int m = 0;
for(int i = 0; i < l; i++){
m = max(m,arr[i] + rod_cut(l-i-1,arr));
}
rod[l] = m;
return rod[l];
}
int main() {
ALLONS_Y;
int l;
cin >> l;
int arr[l];
fill(rod,rod+100,-1);
for(int i =0; i< l; i++){
cin >> arr[i];
}
cout << rod_cut(l,arr) << endl;
return 0;
}
<file_sep>#include<iostream>
#include<map>
using namespace std;
int main(){
// Let's create a map with key int and data int;
map<int,int> dictionary; // name of the map is dictionary;
dictionary.insert(make_pair(1,2)); //way to insert a data (d =2 ) with key (k = 1)
dictionary.insert(make_pair(2,21));
dictionary.insert(pair<int,int>(9,0)); //other way to insert
dictionary[3] = 12; //Also maps are associative containers so next way to insert data
dictionary.insert(make_pair(10,21)); //No duplicate key are allowed if used duplicate keys previous values are replace;
cout << dictionary[3] << endl << endl << endl;
//let's iterate the map
for(map<int,int>::iterator it = dictionary.begin(); it != dictionary.end(); it++){
cout << "dictionary[ " << it->first << " ] = " << it->second << endl;
}
// size of map
cout << endl << "size = " << dictionary.size() << endl;
//let's clear the map
dictionary.clear();
//to check if map is empty
bool emp = dictionary.empty();
cout << "\n\n" << emp << endl << endl;
map<string,string> animals;
animals["cat"] = "small";
animals["elephant"] = "big";
animals.insert(pair<string,string>("horse","medium"));
for(auto it = animals.begin(); it != animals.end(); it++){
cout << "Size of " << it->first << " is " << it->second << endl;
}
emp = animals.empty();
cout << "\n\n" << emp << endl << endl << endl;
auto it = animals.find("cat");
cout << it->second << endl << endl;
//to delete a element of map use above it and then..
animals.erase(it);
//After deletint the data for cat
for(auto it = animals.begin(); it != animals.end(); it++){
cout << "Size of " << it->first << " is " << it->second << endl;
}
animals.clear();
return 0;
}
<file_sep>#include <bits/stdc++.h>
//get the prime factorization of an integer.
using namespace std;
int main() {
int n;
cout << " Factorize : ";
cin >> n;
int num = n;
vector<int> fact;
cout << endl;
for(int i = 2; i*i <= n; i++){
if(n % i == 0){
do{
n = n/i;
fact.push_back(i);
}while(n % i == 0);
}
}
if(n != 1)
fact.push_back(n);
cout << num << " = ";
for(int i = 0; i < fact.size(); i++){
cout << fact[i];
i != fact.size()-1 ? cout << " * " : cout << endl;
}
return 0;
}
<file_sep>//File handling in cpp
//create a file booklist with book name and it's price...
//then read the file
#include<iostream>
#include<fstream>
using namespace std;
int main(){
ofstream fout;
char filename[30];
cout << "Enter file name" << endl;
cin >> filename;
fout.open(filename); //opening using open() member function
//useful when multiple o/p files.
fout << "Book list" << endl;
cout << "Enter the name of 5 books and their price" << endl;
for(int i = 0; i < 5; i++){
string book_name; float price;
cin >> book_name >> price;
fout << book_name << " - " << price << endl;
}
fout.close(); //close before opening another file..
/*
//to open another file with same object..
fout.open("Another_file_name");
fout << "Write something in file " << endl;
fout.close(); */
//To open the file..
cout << endl << endl;
ifstream fin;
fin.open(filename);
char line[30];
while(fin){ //check of EOF
fin.getline(line,30);
cout << line << endl;
}
fin.close();
//for simultaneous r/w create two different object..
//like -> ifstream fin1,fin2; ofstream fout1,fout2;
return 0;
}
<file_sep>// Counts the occurence of letters in given number of strings and displays
// them in sorted order of their count
// If both have same number of count put them in alphabeticall order
// i.e. if both A and U have count 1 then list A first .
// Sample input given below...
/*
3
Hello how are you?
what !!!
okay got it.
*/
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<map>
using namespace std;
struct mapper{
char c;
int in;
};
//int mycomp(const void *a , const void *b){
// struct mapper *a1 = (struct mapper *) a;
// struct mapper *b1 = (struct mapper *) b;
// return a1->i <= b1->i;
//}
void sort(struct mapper datas[],int size){
int temp;
char temps;
for(int i = 0; i < size - 1; i++){
for(int j = i+1; j < size ;j++){
//Sorts accoriding to count
if(datas[i].in < datas[j].in){
temp = datas[i].in;
temps = datas[i].c;
datas[i].in = datas[j].in;
datas[i].c = datas[j].c;
datas[j].in = temp;
datas[j].c = temps;
}
//For same count sort accoriding to alphabets
else if(datas[i].c > datas[j].c && datas[i].in == datas[j].in){
temp = datas[i].in;
temps = datas[i].c;
datas[i].in = datas[j].in;
datas[i].c = datas[j].c;
datas[j].in = temp;
datas[j].c = temps;
}
}
}
for(int j = 0; j < size; j++){
cout << datas[j].c << " " << datas[j].in << endl;
}
}
int main(){
int n;
cin >> n;
string s;
map<char,int> data;
vector<int> vec;
cin.ignore();
for(int i = 1; i <= n; i++){
getline(cin,s);
for(int j = 0; j < s.size(); j++){
if(isalpha(s[j])){
s[j] = toupper(s[j]);
if(data.find(s[j]) != data.end()){
data[s[j]]++;
}
else{
data.insert(make_pair(s[j],1));
}
}
}
}
int size = data.size();
mapper datas[size];
int j = 0;
for(map<char,int>::iterator it = data.begin(); it != data.end(); it++){
// cout << it->first << " " << it->second << endl;
datas[j].c = it->first;
datas[j].in = it->second;
j++;
}
// qsort(datas,size,sizeof(datas[0]),mycomp);
sort(datas,size);
// for(int j = 0; j < data.size(); j++){
// cout << datas[j].c << " " << datas[j].in << endl;
// }
return 0;
}
<file_sep>//program to calculate nth fibonacci number : 0 1 1 2 3 5 8 ...
#include<iostream>
using namespace std;
//Normal recursive method: O(2^n) ...top down approach
int fibo(int n){
if(n <= 1) return n;
return fibo(n-1) + fibo(n - 2);
}
//bottom up approach : O(n)
int fibo2(int n){
if(n <= 1) return n;
int arr[50];
arr[0] = 0 ; arr[1] = 1;
for(int i = 2; i <= n; i++){
arr[i] = arr[i-1] + arr[i-2];
}
return arr[n];
}
//space optimized bottom up approach : O(n)
int fibo3(int n){
if(n <= 1) return n;
int a = 0,b = 1,c;
for(int i = 2; i <= n; i++){
c = a+b;
a = b;
b = c;
}
return c;
}
int main(){
int n;
cin >> n;
cout << fibo2(n) << endl;
cout << fibo3(n) << endl;
return 0;
}
<file_sep>#include<iostream>
using namespace std;
template<class T>
class vector{
T *v;
int size;
public:
vector(int m){ //intialize m elements as 0
v = new T[size = m];
for(int i = 0; i < size; i++) v[i] = 0;
}
// vector(T *a){ //intialize vector with array
// for(int i = 0; i < size; i++){
// v[i] = a[i];
// }
// }
T at(int index){ //to get value of vector at given index
if(index < size) return v[index];
else return 0;
}
T operator*(vector &y){ //for scalar product
T sum = 0;
for(int i = 0; i < size; i++){
sum += this->v[i] * y.v[i];
}
return sum;
}
void operator=(T *a){ //intialize vector with other vector/array
for(int i =0 ; i < size; i++){
this->v[i] = a[i];
}
}
};
int main(){
float x[3] = {3.45,6.2,9.11};
float y[3] = {1.01,7.77,2.0};
vector<float> v1(3);
vector<float> v2(3);
v1 = x;
v2 = y;
cout << v1 * v2 << endl;
return 0;
}
<file_sep>#include <iostream>
#define PI 3.1415 //Macro constant
int main(){
const float pi = 3.1415; //here pi is read only , you cannot change it's value
//float const pi = 3.1415 <- Also valid
// pi = 6 <- causes error
float c(5.3); //new method for assigning a variable
std::cout << c;
}
<file_sep>#include<iostream>
#include<queue>
using namespace std;
int main(){
int n,e,a,b;
cin >> n >> e;
int graph[n][n];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
graph[i][j] = 0;
}
}
for(int i = 0; i < e; i++){
cin >> a >> b;
graph[a-1][b-1] = 1;
graph[b-1][a-1] = 1;
}
int start = 0;
queue<int> q;
q.push(start);
bool visited[n];
fill(visited,visited+n,false);
visited[0] = true;
while(!q.empty()){
int u = q.front();
q.pop();
cout << u+1 << " " ;
for(int i = 0; i < n; i++){
if(graph[u][i] && !visited[i]){
q.push(i);
visited[i] = true;
}
}
}
return 0;
}
<file_sep>//Here we pass two objects to a function as arguements
#include<iostream>
using namespace std;
class Time{
int h , m;
public:
void gettime(int a , int b){ //for very short function declare in class, it will be inline.
h = a , m = b;
}
void puttime(){
cout << h << ":" << m << endl;
}
//Declaring a sum function
void sum(Time , Time ); //add * and replace . by -> , it will be pass by address
//add & it will be pass by reference
};
void Time::sum(Time t1 , Time t2){ //Here also
int ho = t1.m + t2.m;
h = t1.h + t2.h + (ho / 60);
m = ho % 60;
}
int main(){
Time t1,t2,t3;
t1.gettime(2,30);
t2.gettime(3,55);
t3.sum(t1,t2); //pass by value
t1.puttime();
t2.puttime();
t3.puttime();
return 0;
}
<file_sep>#include <bits/stdc++.h>
#define endl '\n'
#define ALLONS_Y ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define mp make_pair
#define pb(x) push_back(x)
using namespace std;
//function to select the min key for unvisited nodes.
int minKey(int key[],int n,bool visited[]){
int min_value = INT_MAX,min_idx = -1;
for(int i = 0; i < n; i++){
if(!visited[i] && min_value > key[i]){
min_value = key[i];
min_idx = i;
}
}
return min_idx;
}
void Prims(vector<pair<int,int> > nodes[],int n,int e){
bool visited[n];
int key[n];
int parent[n];
//initially all nodes are unvisited,
//no node has parent and key of each node is initialize to inf.
for(int i = 0; i < n; i++){
visited[i] = false;
parent[i] = -1;
key[i] = INT_MAX;
}
//source vertex is 0.
key[0] = 0;
for(int i = 0; i < n; i++){
//get the minimum key among all the unvisited nodes.
int u = minKey(key,n,visited);
//select the node and mark it as visited.
visited[u] = true;
//for each nodes adjacent to choosen node, minimize the nodes key if possible.
for(auto i : nodes[u]){
if(!visited[i.first] && i.second < key[i.first]){
//minimize key value,
key[i.first] = i.second;
//mark 'u' as parent of this node
parent[i.first] = u;
}
}
}
//print the graph obtained the prims algo.
cout << "A | B | wt" << endl;
for(int i = 1; i < n; i++){
cout << i << " " << parent[i] << " " << key[i] << endl;
}
}
int main() {
ALLONS_Y;
int n,e;
//no. of nodes and edges,
cin >> n >> e;
//list/array of src and dest pairs along with edge wt.
//uses adjacency list representation.
vector<pair<int,int> > nodes[n];
int src,dest,wt;
for(int i = 0; i < e; i++){
cin >> src >> dest >> wt;
nodes[src].pb(mp(dest,wt));
nodes[dest].pb(mp(src,wt));
}
Prims(nodes,n,e);
return 0;
}
<file_sep>#include<iostream>
#include<map>
using namespace std;
bool is_prime(int num){
bool isprime = true;
for(int i = 2; i*i <= num; i++){
if(num % i == 0){
isprime = false;
break;
}
}
return isprime;
}
int main(){
int k;
map<int,int> prime;
cout << "Enter the maximum range of numbers :\n";
int n;
cin >> n;
int m = 1;
for(int i = 2; i <= n; i++){
if(is_prime(i)){
prime.insert(make_pair(m,i));
m++;
}
}
cout << "Enter the index : ";
cin >> k;
cout << "The " << k << " th prime number is " << prime[k];
return 0;
}
<file_sep>#include <iostream>
int main(){
//for each loop
int arr[] = {1,432,3,4,5};
for(int i : arr)
std::cout << i << std::endl;
//above for each loop is equivalent to:
std::cout << '\n' ;
std::cout << '\n' ;
for(int i = 0; i<=4 ;i++)
std::cout << arr[i] << std::endl;
return 0;
}
<file_sep>#include <bits/stdc++.h>
//Kadane algorithm , to find the max sum of contiguous subarray in 1D array.
using namespace std;
int maxSubarrSum(int arr[],int size){
int max_sum = arr[0];
int max_ans = arr[0];
for(int i= 1; i < size; i++){
max_sum = max(arr[i],max_sum+arr[i]);
max_ans = max(max_ans,max_sum);
}
return max_ans;
}
int main() {
int n;
cin >> n;
int arr[n];
for(int i = 0; i < n; i++) cin >> arr[i];
cout << maxSubarrSum(arr,n) << endl;
return 0;
}
<file_sep>//bit manipulation in cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int a , b;
cout << "Enter the value for a" << endl;
cin >> a;
cout << " part with - " << 2 << endl;
cout << (a >> 1) << endl; // divide by 2^1
cout << (a << 1) << endl; // multiply by 2^1
cout << " part with - " << 16 << endl;
cout << (a >> 4) << endl; // divide by 2^4
cout << (a << 4) << endl; // multiply by 2^4
cout << " part with - " << 4 << endl;
cout << (a << 2) << endl; // divide by 2^2
cout << (a >> 2) << endl; // multiply by 2^2
cout << "Enter value for b" << endl;
cin >> b;
cout << " a * 2^b = " << ( a << b) << endl;
cout << " a & b = " << (a & b) << endl;
cout << " a | b = " << (a | b) << endl;
cout << " a ^ b = " << (a ^ b) << endl;
cout << " ~a = " << ~a << endl;
return 0;
}
<file_sep>#include<iostream>
#include<vector>
using namespace std;
void print_vector(vector<int> arr){
for(int i = 0;i < arr.size(); i++){
cout << arr[i] << ' ';
}
cout << endl;
}
int main(){
vector<int> vet;
int a;
do{
cout << "Enter a number : " << endl;
cin >> a;
if(a == 0) break;
vet.push_back(a) ;
}while(1);
int sum = 0;
for(int i = 0 ; i < vet.size() ; i++)
sum = sum + vet[i];
cout << sum;
}
<file_sep>//representing the 2d maze graph into matrix adjacency list.
#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n,m,num;
cin >> n >> m;
int nodes = (n * m);
cout << "no of nodes " << nodes << endl;
list<int> g[nodes];
char c;
vector<char> cv(nodes);
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cin >> c;
num = m*i+j;
cv[num] = c;
if(c == '.'){
if(m*(i-1)+j >= 0){
if(cv[m*(i-1)+j] == '.'){
g[m*i+j].push_back(m*(i-1)+j);
g[m*(i-1)+j].push_back(m*i+j);
}
}
if((m*i+j)%m != 0){
if(cv[m*i+(j-1)] == '.'){
g[m*i+j].push_back(m*i+(j-1));
g[m*i+(j-1)].push_back(m*i+j);
}
}
}
}
}
for(int i = 0; i < nodes; i++){
list<int>::iterator it;
cout << i << "-> ";
for(it = g[i].begin(); it != g[i].end(); it++){
cout << *it << " ";
}
cout << endl;
}
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
int ks(int n,int values[],int wt,int weight[]){
if(n == 0 || wt == 0) return 0;
if(wt < weight[n-1]) return 0;
int ans = max( ks(n-1,values,wt,weight), values[n-1] + ks(n-1,values,wt-weight[n-1],weight) );
return ans;
}
int main() {
int n,wt;
cin >> n >> wt;
int values[n],weight[n];
for(int i = 0; i < n; i++) cin >> values[i];
for(int i = 0; i < n; i++) cin >> weight[i];
cout << ks(n,values,wt,weight) << endl;
return 0;
}
<file_sep>#include<iostream>
#include <map>
using namespace std;
map<int, long long int> memo;
long long int chance(int i , int n){
n = n - i;
if(n == 0){
return 1;
}
else if(n < 0){
return 0;
}
else{
if(memo.find(n) != memo.end()) {
return memo[n];
} else {
long long int sum = chance(1,n) + chance(2,n) + chance(3,n);
memo.insert(make_pair(n, sum));
return sum;
}
}
}
int main(){
int n;
cin >> n;
cout << chance(1,n) + chance(2,n) + chance(3,n);
return 0;
}
<file_sep>#include <bits/stdc++.h>
#define ull unsigned long long int
#define ll long long int
#define endl '\n'
#define pb(x) push_back(x)
#define mp make_pair
#define ALLONS_Y ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
using namespace std;
void dfs(int src, vector< vector<int> > &v,int visited[]){
cout << src << " ";
visited[src] = 1;
for(auto it = v[src].begin(); it != v[src].end(); it++){
if(!visited[*it]){
dfs(*it,v,visited);
}
}
}
int main() {
ALLONS_Y;
int n,e;
cin >> n >> e;
vector< vector<int> > v(n);
int src,dest;
for(int i = 0; i < e; i++){
cin >> src >> dest;
// src--; dest--;
v[src].pb(dest);
v[dest].pb(src);
}
int s = 0;
int visited[n] = {0};
dfs(s,v,visited);
cout << endl;
return 0;
}
<file_sep>#include<iostream>
using namespace std;
void Demo(int a){
if(a < 1) return;
else{
cout << a << " " ;
Demo(a-1);
cout << a << " " ;
}
}
int main(){
int x;
cin >> x;
Demo(x);
return 0;
}
<file_sep>//Recursive approach to coin change problem...
#include <bits/stdc++.h>
#define ull unsigned long long int
#define ll long long int
#define endl '\n'
#define all(v) begin(v), end(v)
#define pb(x) push_back(x)
#define mp make_pair
#define ALLONS_Y ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define contains(container, value) container.find(value) != container.end()
#define rep(i,a,b) for(int i = a; i < b; i++)
using namespace std;
ull find1(int n,int coins[],int k,int s_i){
if(n == 0) return 1;
if(n < 0) return 0;
ull sum = 0;
for(int i = s_i; i < k; i++){
sum += find1(n-coins[i],coins,k,i);
}
return sum;
}
ull find2(int sum,int arr[],int m){
if(sum == 0) return 1;
if(sum < 0) return 0;
if(m <= 0 && sum > 0) return 0;
return find2(sum,arr,m-1) + find2(sum-arr[m-1],arr,m);
}
int main() {
int n,k;
scanf("%d%d",&n,&k);
int coins[k];
for(int i = 0; i < k ;i++){
scanf("%d",&coins[i]);
}
cout << find1(n,coins,k,0) << endl; //first approach...
cout << find2(n,coins,k) << endl; //second approach...
return 0;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
bool compare(pair<int,int> a, pair<int,int> b){
return a.second < b.second;
}
int main(){
int n;
cin >> n;
pair<int,int> p[n];
for(int i = 0; i < n; i++){
int start , end;
cin >> start >> end;
p[i] = make_pair(start,end);
}
sort(p,p+n,compare); //this sorts the pair with end time
int k = 0;
cout << p[k].first << " " << p[k].second << endl;
for(int i = 1; i < n; i++){
if(p[k].second <= p[i].first){
cout << p[i].first << " " << p[i].second << endl;
k = i;
}
}
return 0;
}
<file_sep>/* Multilevel inheritance:
class A; <- parent/base class
class B : public A; <- intermediate base class
class C : public B; <- derived class
*/
#include<iostream>
using namespace std;
class Student{
protected:
int roll_number;
string name;
public:
void initialize_detail(){
roll_number = 5;
name = "Abcd";
}
void details(){
cout << "Roll number of " << name << " is " << roll_number << endl;
}
};
class Teacher : public Student{
protected:
string f_name,m_name;
string phone_no;
string marks;
public:
void details(){
cout << "call " << f_name << "/" << m_name << " at " << phone_no << endl;
}
void get_details(){
cout << "faters name " << endl;
cin >> f_name;
cout << "mothers name" << endl;
cin >> m_name;
cout << "phone number" << endl;
cin >> phone_no;
}
};
class Principal:public Teacher{
public:
void details(){
cout << "Good student" << endl;
}
};
int main(){
Principal p;
Teacher t;
Student s;
//s,p,t are different objects , we must initialize each of them seprately
cout << "For principal " << endl;
p.get_details(); //p uses the method of class teacher as it doesn't have it's own
p.details(); //p uses it's own method(details) since it has it's own
cout << "\nFor teacher " << endl;
t.initialize_detail(); //inheriting the method of parent class(student)
t.get_details(); //since t is different object we again call this method and give different value
t.details(); //t uses it's own method not of student i.e. overriding
t.Student::details(); //now t uses it's parent(Student)method valid if already initialized through t
cout << "\nFor student" << endl;
s.initialize_detail();
s.details(); //it uses it's method
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
int mcr(int arr[],int init,int fin){
if(init == fin){
return 0;
}
int ans = INT_MAX;
for(int i = init; i < fin; i++){
ans = min(ans,mcr(arr,init,i) + mcr(arr,i+1,fin) + arr[init-1]*arr[i]*arr[fin]);
}
return ans;
}
int main() {
int n;
cin >> n;
int arr[n];
for(int i = 0; i< n; i++) cin >> arr[i];
cout << mcr(arr,1,n-1) << endl;
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int log_2(int a){
if(a == 1) return 0; //no log2 of -ve values
return 1 + log_2(a/2); //put /3 to get log3 and similar for others
}
int main(){
int n;
cin >> n;
cout << log_2(n);
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
int n,m;
cin >> n >> m;
int a,b,c;
vector<int> array(n,0);
for(int i = 0; i < m; i++){
cin >> a >> b >> c;
array[a-1] += c;
if(b < n)
array[b] -= c;
}
for(int i = 1; i < n; i++){
array[i] = array[i-1] + array[i];
}
m = array[0];
for(int i = 0; i < n; i++){
m = max(m,array[i]);
}
cout << m << endl;
return 0;
}
<file_sep>//Singly linked list:
#include<iostream>
using namespace std;
struct link{
int data;
link *next;
};
link * head = NULL;
void InsertAtBeg(){
int data;
cout << "\nEnter data:\t";
cin >> data;
link * p = new link();
p->data = data;
p->next = head;
head = p;
cout << "\n***Success***\n";
}
void InsertAtEnd(){
int data;
cout << "\nEnter data:\t";
cin >> data;
link * p = new link();
p->data = data;
p->next = NULL;
if(head == NULL){
head = p;
}
else{
link * q = head;
while(q->next != NULL){
q = q->next;
}
q->next = p;
}
cout << "\n***Success***\n";
}
void Traverse(){
link * p = head;
if(head == NULL){
cout << "\nEmpty list\n";
return;
}
cout << "\nThe elements are listed below:\n";
int index = 0;
while(p != NULL){
cout << index++ <<". " << p->data << endl;
p = p->next;
}
cout << "\n***Success***\n";
}
void DeleteBeg(){
if(head == NULL){
cout << "\nEmpty list\n";
return ;
}
else{
link * p = head;
head = head->next;
cout << "\nSuccessfully deleted " << p->data << endl;
delete p;
}
}
void DeleteEnd(){
if(head == NULL){
cout << "\n Empty list\n";
return ;
}
else if(head->next == NULL){
link * p = head;
head = NULL;
delete p;
}
else{
link *p , *q;
p = head;
q = head->next;
while(q->next != NULL){
p = q;
q = q->next;
}
p->next = NULL;
cout << "\nSuccessfully deleted " << q->data << endl;
delete q;
}
}
void InsertSpec(){
int pos;
cout << "Enter the position to insert\n";
cin >> pos;
link *p;
p = head;
if(pos == 0){
InsertAtBeg();
return;
}
for(int i = 0; i < pos - 1; i++){
if(p == NULL) {
cout << "invalid" << endl;
return;
}
p = p->next;
}
link * q = new link();
cout << "ENter data " ;
cin >> q->data;
q->next = p->next;
p->next = q;
cout << "\n***Success***\n";
}
void DeleteSpec(){
if(head == NULL){
cout << "\n Empty list\n";
return ;
}
link *current , *previous;
int pos;
cout << "Enter the position to delete" << endl;
cin >> pos;
if(pos == 0){
DeleteBeg();
return;
}
current = head;
for(int i = 0; i < pos; i++){
if(current == NULL){
cout << "Invalid range" << endl;
return;
}
previous = current;
current = current->next;
}
previous->next = current->next;
cout << "\nSuccessfully deleted " << current->data << endl;
delete current;
}
int main(){
cout << "Simulating a list through singly linked list\n";
do{
cout << "\n";
int opt;
cout << "Menu:";
cout << "\n1 Insert at beginning"
<< "\n2 Insert at end"
<< "\n3 Traverse"
<< "\n4 Exit"
<< "\n5 Delete 1 item from beginning"
<< "\n6 Delete 1 item from end"
<< "\n7 Delete 1 item from specific position"
<< "\n8 Insert at Specific position";
cout << "\n\nEnter a option:\t";
cin >> opt;
switch(opt){
case 1: InsertAtBeg();
break;
case 2: InsertAtEnd();
break;
case 3: Traverse();
break;
case 4: exit(1);
break;
case 5: DeleteBeg();
break;
case 6: DeleteEnd();
break;
case 7: DeleteSpec();
break;
case 8: InsertSpec();
break;
default:
cout << "\nEnter valid option.";
}
}while(true);
return 0;
}
<file_sep>//File handling in cpp
#include<iostream>
#include<fstream>
using namespace std;
int main(){
ofstream outfile("file_name.txt"); //opening a file using constructor of ofstream
//this method is useful when only one ofstream file is in the system
//for multiple file stream we use open()
cout << "Enter a name" << endl;
char name[20];
cin >> name;
outfile << name << endl;
outfile.close();
//input file created below....
ifstream inf("file_name.txt");
inf >> name;
cout << "data in the file is "<< name << endl;
inf.close();
return 0;
}
<file_sep>#include<iostream>
#include<string>
using namespace std;
class employee {
private:
int age ;
string name;
int salary;
public :
employee(string n, int a, int s){
name = n;
age = a;
salary = s;
}
int getAge(){
return age;
}
string getName(){
return name;
}
string getDetails(){
string details = "Name: " + name;
details += "Age : " + to_string(age);
details += "Salary : " + to_string(salary);
}
};
int main(){
employee emp1("San", 20 , 120000);
cout << emp1.getAge() << endl;
cout << emp1.getName() << endl;
cout << emp1.getDetails() << endl;
return 0;
}
<file_sep>//Using friend function to access private member outside of class...
#include<iostream>
using namespace std;
class two;
class one {
int roll ;
string name;
public:
void getroll(int n){ roll = n;}
void getname(string names){ name = names;}
void putdata(){cout << name << " - " << roll << endl;}
friend void swaproll(one &, two &);
};
class two {
int roll ;
string name;
public:
void getroll(int n){ roll = n;}
void getname(string names){ name = names;}
void putdata(){ cout << name << " - " << roll << endl;}
friend void swaproll(one &, two &);
};
void swaproll(one &a,two &b){
int temp = a.roll;
a.roll = b.roll;
b.roll = temp;
}
int main(){
one a;
two b;
a.getname("San");
a.getroll(2);
b.getname("xyz");
b.getroll(1);
a.putdata();
b.putdata();
swaproll(a,b); //pass by reference
cout << "\nAfter exchanging the roll number\n";
a.putdata();
b.putdata();
}
<file_sep>
#include<iostream>
#include<stack>
using namespace std;
int main(){
stack<char> stk;
char st[50] ;
cin >> st ;
char a;
int i = 0;
while(st[i] != '\0'){
switch(st[i]){
case '(':
stk.push(st[i]);
i++;
break;
case '{':
stk.push(st[i]);
i++;
break;
case '[':
stk.push(st[i]);
i++;
break;
case ']':
a = stk.top();
stk.pop();
if(a == '['){
i++;
}
else{
cout << "Not correct\n";
return 1;
}
break;
case '}':
a = stk.top();
stk.pop();
if(a == '{'){
i++;
}
else{
cout << "Not correct\n";
return 1;
}
break;
case ')':
a = stk.top();
stk.pop();
if(a == '('){
i++;
}
else{
cout << "Not correct\n";
return 1;
}
break;
default :
i++;
}
}
if(stk.empty()) cout << "correct \n";
return 0;
}
<file_sep>#include<iostream>
#include<vector>
#include<stack>
using namespace std;
int main(){
int v;
int e;
int a, b;
cin >> v >> e;
stack<int> st;
bool visited[v+1];
fill(visited,visited+v+1,false);
vector<vector<int> > graph(v + 1, vector<int> (v + 1,0));
for(int i = 0; i < e; i++){
cin >> a >> b;
graph[a][b] = 1;
graph[b][a] = 1;
}
st.push(1);
visited[1] = true;
while(!st.empty()){
int a = st.top();
cout << a << " ";
st.pop();
for(int i = 1; i <= v; i++){
if(visited[i] == false && graph[a][i]){
st.push(i);
visited[i] = true;
}
}
}
return 0;
}
<file_sep>#include<iostream>
#include<string>
using namespace std;
int main(){
string str = ("hello hello");
cout << str << endl;
cout << str.size() << endl; //size of string
cout << str.at(1) << str[6] << endl; //characters at given index
bool emp = str.empty(); //true if empty
cout << emp << " <- string is not empty\n";
str.push_back('e'); //pushing a character in string str
cout << str << endl;
str.pop_back();
cout << str << endl;
//for string concatenation
string s1 = "Butter";
string s2 = "fly";
cout << s1+s2+'\n' << s1+" and "+s2 << endl;
//to read a entire line of string
cout << "\n\nEnter a line of string:\n";
string s;
getline(cin,s);
cout << "You have entered ( " << s << " )" << endl << endl;
cout << "After inserting a new string , we get\n";
string a = " Good Good";
s.insert(s.end(),a.begin(),a.end()); //inserting nice in string s
cout << s << endl;
//to clear the 5 characters from the string starting from index 3
cout << "After deleting 5 characters starting from index 3 :\n\n";
s.erase(3,5);
cout << s << endl << "size " << s.size() << endl;
cout << endl ;
cout << (int)'A' << endl;
cout << (int)'Z';
return 0;
}
<file_sep>//find the all possible comibinations with given n and r...
#include <bits/stdc++.h>
#define ULL unsigned long long
#define LL long long
#define endl '\n'
#define ALL(v) begin(v), end(v)
#define CONTAINS(container, value) container.find(value) != container.end()
using namespace std;
int c;
void get_combinations(int n, int a, int r,vector<int> vec){
vec.push_back(a);
if(vec.size() == r){
for(int i = 0; i < r; i++) cout << vec[i] << " ";
cout << endl;
c++;
}
else{
for(int i = a+1; i <= n; i++){
get_combinations(n,i,r,vec);
}
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n,r;
cin >> n >> r;
if(n < r){
cout << "improper values !!!" << endl;
exit(0);
}
vector<int> vec;
for(int i = 1; i <= n-r+1; i++)
get_combinations(n,i,r,vec);
string v;
if(c != 1) v = "are";
else v = "is";
cout << "There " << v << " " << c << " combination." << endl;
return 0;
}
<file_sep>
#include<iostream>
#include<cmath>
double sqrt(int x);
int main(){
int num;
std::cout << "Enter a number\n";
std::cin >> num;
double result;
try{
result = sqrt(num);
}
catch(const char *text){
std::cout << "Error !!!" << text << std::endl;
return 1;
}
std::cout << "The square root is " << result;
return 0;
}
double sqrt(int x){
if(x < 0)
throw " Negative number ";
return pow(x,0.5);
}
<file_sep>#include<iostream>
using namespace std;
class Swap{
public :
void swapper(int a , int b){
a = a + b;
b = a - b;
a = a - b;
cout << "After swapping a = " << a << " and b = " << b;
}
};
int main(){
Swap s;
int a , b;
cout << "Enter two numbers a and b to swap " << endl;
cin >> a >> b;
s.swapper(a,b);
return 0;
}
<file_sep>//Let's have a look at call by reference and return by reference
#include<iostream>
int & smaller(int &s , int &w){ //set reference of a & b to s & w
if(s > w) return w; //return reference
else return s;
}
int main(){
int a,b;
std::cout << "a = ";
std::cin >> a;
std::cout << "b = ";
std::cin >> b;
smaller(a,b) = -10; //assigns the returned reference
std::cout << "a = " << a << " b = " << b << std::endl;
return 0;
}
<file_sep>/*
Type conversions:
1.basic to class (by constructor)
2.class to basic (by casting operator)
3.one class to another class ( by casting operator in src class , or constructor in dest class)
*/
#include<iostream>
using namespace std;
//incase if we use casting operator for one class to another class conversion we must declare dest class
//Our source class
class Ticket{
int no_of_passenger = 0;
float ticket_price = 0;
int dest_no = 0;
public:
Ticket(){}
//we may use initalization list or assign inside block or do both in constructor
Ticket(int x, float y ,int z):no_of_passenger(x),ticket_price(y){
dest_no = z; //may use this also in intialization list
//or assign the data inside this block; block can be empty
}
int get_passenger_no(){return no_of_passenger;}
float get_price(){return ticket_price;}
int get_dest(){return dest_no;}
operator float(){ return no_of_passenger * ticket_price;}
//if we assign the object to float data type by = operator float() is called
//i.e. float a = object_of_Ticket; //this is class to basic type conversion
//this is same as float , or operator overloading for unary operator but
//Action of converting to another class is performed by using constructor in another class
// operator Counter_info(){ //using casting operator but declare dest class first
// float f = get_price() * get_passenger_no();
// int dest = get_dest();
// Counter_info temp(dest_no,f); //creating the object
// return temp;
// }
};
//Our dest class
class Counter_info{
int dest_no;
float total_value;
public:
Counter_info(){ dest_no = 0; total_value = 0;}
Counter_info(int x, float y):dest_no(x),total_value(y){}
Counter_info(Ticket &t){ //use instead of casting operator but declare src class first
dest_no = t.get_dest();
total_value = t.get_price() * t.get_passenger_no();
}
void show_data(){
cout << "dest_no : " << dest_no << endl;
cout << "total_value : " << total_value << endl;
}
};
int main(){
Ticket t1(2,1.5,2); //this constructor converts basic type(int,float) into class type (dest_no,ticket_price)
float total_price;
total_price = t1; //here we convert class to basic type
//or total_price = (float) t1;
cout << total_price << endl;
Counter_info i = t1; //here we perform one class to another class type conversion
i.show_data();
return 0;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
int partition(int arr[],int low ,int high){
int pivot = arr[high];
int low_idx = low;
int temp;
for(int i = low; i < high; i++){
if(arr[i] < pivot){
temp = arr[low_idx];
arr[low_idx] = arr[i];
arr[i] = temp;
low_idx++;
}
}
temp = arr[low_idx];
arr[low_idx] = arr[high];
arr[high] = temp;
return low_idx;
}
void QuickSort(int arr[], int low , int high){
if(low < high){
int pi = partition(arr,low,high);
QuickSort(arr,low,pi-1);
QuickSort(arr,pi+1,high);
}
}
int main(){
int n;
cin >> n;
int arr[n];
for(int i = 0; i < n; i++) cin >> arr[i];
QuickSort(arr,0,n-1);
for(int i = 0; i < n; i++){
cout << arr[i] << " ";
}
cout << endl;
return 0;
}<file_sep>#include<iostream>
using namespace std;
class Static{
int var1,var2;
static int count; //count is static and private
public:
void getdata(int a , int b){
var1 = a , var2 = b;
count++;
}
void putdata(){
cout << var1 << " " << var2 << endl;
}
void getcount(){ //to get the count
cout << "count = " << count << endl;
}
static void inr_count(){ //Static method can have only static properties(func or var)
count = count + 10;
}
};
int Static::count;
int main(){
Static s , a, t;
s.getdata(4,30); //After each getdata() , count is increamented;
t.getdata(5,20);
a.getdata(4,20);
s.putdata();
t.putdata();
t.getcount(); //count is same for all objects(s,a,t)
Static::inr_count(); //Increases count by 10 using static function
s.getcount();
return 0;
}
<file_sep>#include <bits/stdc++.h>
/*
* segmentation tree, used to find the sum of given segment in an array
* time complexity : O(log2(n)) for searching and updating both...
*/
#define ULL unsigned long long int
#define LL long long int
#define endl '\n'
#define allons_y ios_base::sync_with_stdio(0); cin.tie(0)
using namespace std;
int getsumUtil(int *st,int start,int end,int qs,int qe,int idx){
if(qs <= start && qe >= end){
return st[idx];
}
if(end < qs || start > qe){
return 0;
}
int mid = start + (end - start)/2;
return getsumUtil(st,start,mid,qs,qe,2*idx+1)+
getsumUtil(st,mid+1,end,qs,qe,2*idx+2);
}
int getsum(int *st,int n,int qs,int qe){
if(qs < 0 || qe >= n || qs > qe){
cout << "invalid input" << endl;
return 0;
}
return getsumUtil(st,0,n-1,qs,qe,0);
}
int constructUtil(int arr[],int *st,int start, int end,int current){
if(start == end){
st[current] = arr[start];
return arr[start];
}
int mid = start + (end - start)/2;
st[current] = constructUtil(arr,st,start,mid,current*2+1) + constructUtil(arr,st,mid+1,end,current*2+2);
return st[current];
}
int* construct_st(int arr[],int size){
int height = (int) ceil(log2(size));
int max_size = 2*pow(2,height) - 1;
int *st = new int[max_size];
constructUtil(arr,st,0,size-1,0);
return st;
}
void update(int* st,int ss,int se,int i_t_u, int diff, int idx){
if(i_t_u < ss || i_t_u > se){
return;
}
st[idx] = st[idx] + diff;
if(se != ss){
int mid = ss + (se - ss)/2;
update(st,ss,mid,i_t_u,diff,2*idx+1);
update(st,mid+1,se,i_t_u,diff,2*idx+2);
}
}
int main() {
allons_y;
int arr[] = {1,2,3,4,5,6};
int size = sizeof(arr)/sizeof(arr[0]);
int* st = construct_st(arr,size);
cout << getsum(st,size,0,3) << endl;
//to update the value in array and also in our seg tree.
int idx_to_update = 2,
new_value = 8, //old value = 4
diff = new_value - arr[idx_to_update];
arr[idx_to_update] = new_value; //we update the arr
update(st,0,size-1,idx_to_update,diff,0); //to update the data in seg tree
//st,ss,se,idx_to_update,diff,current_idx
cout << getsum(st,size,0,3) << endl;
return 0;
}
<file_sep>//Topological sort using BFS
#include<iostream>
#include<queue>
using namespace std;
int v;
void T_sort(vector< vector<int > > & graph, int in_deg[]){
bool visited[v+1];
fill(visited, visited+v+1,false);
queue<int> q;
for(int i = 1; i < v+1; i++){
if(in_deg[i] == 0){
q.push(i);
visited[i] = true;
}
}
while(!q.empty()){
int u = q.front();
q.pop();
cout << u << " " ;
for(int i = 1; i <= v; i++){
if(graph[u][i] && !visited[i]){
in_deg[i]--;
if(in_deg[i] == 0){
q.push(i);
visited[i] = true;
}
}
}
}
}
int main(){
/*
7 7
4 1
4 5
4 6
1 2
2 3
5 3
6 7
*/
int e;
cin >> v >> e;
vector< vector<int > > graph(v+1, vector<int> ( v+1,0));
int in_deg[v+1];
fill(in_deg,in_deg+v+1,0);
for(int i = 0; i < e; i++){
int a,b;
cin >> a >> b;
graph[a][b] = 1;
in_deg[b]++;
}
T_sort(graph,in_deg);
return 0;
}
<file_sep>#include<iostream>
#include<set>
using namespace std;
//auto = set<int> :: iterator it =
//sets sorts the data on insertion i.e. it uses binary tree so search is fast
//and no need to sort manually
int main(){
cout << "\nOrdered set\n\n";
set<int> st;
for(int i = 10; i >=1; i--)
st.insert(i);
cout << "output :: \n";
for(auto it = st.begin(); it != st.end(); it++){
cout << *it << " ";
}
// to search a data from set
auto it = st.find(4);
cout << "\n\nFound element : " << *it << endl;
// to delete the searched data
st.erase(it);
// set contains only unique values so repeated data are ignored for more than one time
st.insert(1);
st.insert(1);
cout << "\nAfter deleting the 4 and inserting 1 three times:\n";
for(auto it = st.begin(); it != st.end(); it++){
cout << *it << " ";
}
// Multiset
cout << "\n\n Multiset allows repeated datas\n\n";
multiset<int> a;
a.insert(1);
a.insert(2);
a.insert(1);
a.insert(2);
cout << "Multiset -> ";
for(auto it = a.begin(); it != a.end(); it++){
cout << *it << " ";
}
return 0;
}
<file_sep>#include <bits/stdc++.h>
#define ull unsigned long long int
#define endl '\n'
#define ALLONS_Y ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
ull prices[100009];
int n;
using namespace std;
int bin_search(ull spend){
int left = 0;
int right = n-1;
int mid;
int idx = -1;
while(left <= right){
mid = left + (right-left)/2;
if(prices[mid] <= spend){
idx = mid;
left = mid+1;
}
else{
right = mid -1;
}
}
return idx;
}
int main() {
ALLONS_Y;
int q;
cin >> n; //no. of elements in array...
for(int i = 0; i<n; i++) cin >> prices[i]; //array on which we search...
sort(prices,prices+n); //sort the array...
cin >> q; //no. of elements to search...
ull today; //variable for element to search...
for(int i = 0; i < q; i++){
cin >> today; //search this element
cout << bin_search(today)+1 << endl; //custom method to get upper_bound
cout << upper_bound(prices,prices+n,today); //library method to get upper_bound
cout << lower_bound(prices,prices+n,today); //library method to get lower_bound
}
return 0;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
class String{
char *p;
int len;
public:
String (){len = 0; p = 0;}
String (const char *p);
String (const String &s);
~String () {delete p;}
friend String operator+(const String &s,const String &t);
// friend int operator <= (const String &s,const String &t);
friend void show(const String &s);
void operator = (const char *s);
};
String::String(const char *s){
cout << "not from = " << endl;
len = strlen(s);
p = new char[len + 1];
strcpy(p,s);
}
String::String(const String &s){
len = s.len;
p = new char[len + 1];
strcpy(p,s.p);
}
void String::operator = (const char *s){
cout << "from = " << endl;
len = strlen(s);
p = new char[len+1];
strcpy(p,s);
}
String operator+(const String &s,const String &t){
String temp;
temp.len = s.len + t.len;
temp.p = new char(temp.len + 1);
strcpy(temp.p,s.p);
strcat(temp.p,t.p);
return temp;
}
void show (const String &s){
cout << s.p;
}
int main(){
String s1("New ");
String s2 = "Nepal"; //s1 and s2 are invoked by same constructor
String s3 = s1 + s2;
String s4;
s4 = "hello";
const char *a; //if no const then it violets the nature of string
a = "this is "; //nature : strings character at index i contents cannot be modifed
cout << endl;show(s4);
cout << endl;show(s1);
cout << endl;show(s2);
cout << endl;show(s3);
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
vector<int> ans;
void topological_dfs(int src,vector<int> g[],vector<bool> &visited){
visited[src] = true;
for(auto it : g[src]){
if(!visited[it]){
topological_dfs(it,g,visited);
}
}
ans.push_back(src);
}
int main() {
int v,e;
scanf("%d%d",&v,&e);
vector<int> g[v];
int src,dest;
for(int i = 0; i < e; i++){
cin >> src >> dest;
src--; dest--;
g[src].push_back(dest);
}
vector<bool> visited(v,false);
for(int i = 0; i < v; i++){
if(visited[i] == true) continue;
topological_dfs(i,g,visited);
}
//reversely display the vector
for(int i = ans.size()-1; i >= 0; i--){
printf("%d ",ans[i]+1);
}
puts(""); //inplace of \n
return 0;
}
<file_sep>#include <bits/stdc++.h>
#define ULL unsigned long long
#define LL long long
#define endl '\n'
#define ALL(v) begin(v), end(v)
#define CONTAINS(container, value) container.find(value) != container.end()
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int x;
cin >> x;
assert(("x is positvie",x > 0));
return 0;
}
<file_sep>/*
A priority queue is just a regular container, such as a vector, which is
sorted based on a certain criterion each time a new item is added. So, if a
vector is used internally to store the elements, that means that particular
priority queue has all the properties of a vector
*/
#include<iostream>
#include<queue>
using namespace std;
void show(priority_queue<int,vector<int>,greater<int> > pq){
while(!pq.empty()){
cout << pq.top() << " " ;
pq.pop();
}
}
int main(){
// vector is used to store the data and is sorted by functor (function object)
priority_queue<int,vector<int>,greater<int> > pq;
pq.push(10); pq.push(5); pq.push(1);
pq.push(20); pq.push(18);
cout << "Size of queue : " << pq.size() << endl;
cout << "The priority queue is\n";
show(pq);
const int *vec = &(pq.top());
cout << endl << "The intial vector used for priority queue is" << endl;
for(int i = 0 ; i < pq.size(); i++)
cout << vec[i] << " ";
return 0;
}
<file_sep>#include<iostream>
#include<set>
using namespace std;
int main(){
//elements in set are always in sorted order
set<int,greater<int> > s;
//greater is just to arrange in descending order...
//if greater not uses then it is arrange in ascending order...
s.insert(10);
s.insert(50);
s.insert(12); //values are keys themself so no multiple values are stored
s.insert(20);
s.insert(50);
cout << "\nElements of s\n";
set<int, greater<int> >::iterator itr;
for(itr = s.begin(); itr != s.end(); itr++) cout << *itr << " ";
cout << endl;
cout << "\nElements of s2\n";
set<int> s2(s.begin(),s.end()); //initalizing the s2 with s1 values;
set<int>::iterator it;
for(it = s2.begin(); it != s2.end(); it++) cout << *it << " ";
cout << endl;
cout << "\nAfter deleting values from begin to 12 in s" << endl;
s.erase(s.begin(),s.find(12));
for(it = s.begin(); it != s.end(); it++) cout << *it << " ";
cout << endl;
cout << "\nAfter deleting values from begin to 12 in s2" << endl;
s2.erase(s2.begin(),s2.find(12));
for(it = s2.begin(); it != s2.end(); it++) cout << *it << " ";
cout << endl;
int num = s2.erase(20); //20 is erased so num = 1;
cout << "\nErase 20 in s2\n";
for(it = s2.begin(); it != s2.end(); it++) cout << *it << " ";
cout << endl;
num = s2.erase(10); //10 absent in s2 so can't erase and num = 0
s.insert(10);
s.insert(50);
s.insert(40);
s.insert(0);
s.insert(112);
cout << "\nElements in s\n";
for(itr = s.begin(); itr != s.end(); itr++) cout << *itr << " " ;
cout << endl;
cout << "\n\nLower bound after 15 in s\n";
cout << *s.lower_bound(15) << endl;
set<int> s3(s.begin(),s.end());
set<int>::iterator i;
cout << "\n\nElements in s3\n";
for(i = s3.begin(); i != s3.end(); i++) cout << *i << " " ;
cout << "\n\nLower bound after or from possible position of 15 in s3\n";
cout << *s3.lower_bound(15) << endl;
cout << "\n\nLower bound after or from possible position of 12 in s3\n";
cout << *s3.lower_bound(12) << endl;
return 0;
}
<file_sep>#include<iostream>
#include<stack>
using namespace std;
int main(){
stack<int> st;
if(st.empty()) cout << "Stack is empty\n";
else cout << "Stack is not empty\n";
for(int i = 0; i < 5; i++){
st.push(i);
}
while(!st.empty()){
cout << "Size of stack is " << st.size() << endl;
cout << "Top = " << st.top() << endl;
st.pop();
}
return 0;
}
<file_sep>#include <bits/stdc++.h>
#define endl '\n'
#define ALLONS_Y ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
using namespace std;
int main() {
ALLONS_Y;
int n;
cin >> n;
bool isPrime = true;
int i;
for(i = 2; i*i <= n; i++){
if(n % i == 0){
isPrime = false;
break;
}
}
if(isPrime)
cout << n << " is a prime number." << endl;
else
cout << n << " is divisible by " << i << endl;
return 0;
}
<file_sep>#include<iostream>
using namespace std;
void swap1(int &a , int &b); //uses a new name a and b to passed arguements
void swap2(int *a , int *b); //Assigns original address of passed arguemens
int main(){
int a = 10 , b = 20;
cout << "Before swapping " << a << " " << b << endl;
swap2(&a , &b);
cout << "After swapping using c - pointer method : " << a << " " << b << endl;
swap1(a,b);
cout << "After swapping using c++ & method : " << a << " " << b << endl << endl;
//More about &
int data = 100;
int &c = data; //Assign a new name to data
cout << "data is " << data << " c is " << c << endl;
c+= 300; //if altered the value of c then data is also altered simultaneusly
cout << "data is " << data << " c is " << c << endl;
return 0;
}
void swap1(int &a , int &b){
int t = a;
a = b;
b = t;
}
void swap2(int *a ,int *b){
int t = *a;
*a = *b;
*b = t;
}
<file_sep>//program to calculate nth fibonacci number : 0 1 1 2 3 5 8 ...
//using memoization technique
#include<iostream>
using namespace std;
int fibo(int n,int memo[]){
if(memo[n] != -1) return memo[n];
memo[n] = fibo(n-1,memo) + fibo(n - 2,memo);
return memo[n];
}
int main(){
int memo[40];
fill(memo,memo+40,-1);
memo[0] = 0; memo[1] = 1;
int n;
cin >> n;
cout << fibo(n,memo) << endl;
return 0;
}
<file_sep>/*
Time : 2019-10-19,Saturday
Desc : no description
*/
#include <bits/stdc++.h>
#define ull unsigned long long int
#define ll long long int
#define endl '\n'
#define pb(x) push_back(x)
#define ALLONS_Y ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define debug(x) cout << #x << ' = ' << x << endl
#define pii pair<int,int>
#define DEBUG 1
using namespace std;
int find(int parent[],int src){
if(parent[src] == src) return src;
parent[src] = find(parent,parent[src]);
return parent[src];
}
void unite(int parent[],int rank[],int src,int dest){
int s = parent[src];
int d = parent[dest];
if(rank[s] < rank[d]){
parent[s] = d;
}else if(rank[s] > rank[d]){
parent[d] = s;
}else{
rank[s]++;
parent[d] = s;
}
}
int krus(pair<int,pii> g[],int v,int e){
int parent[v];
int rank[v];
for(int i = 0; i < v; i++){
parent[i] = i;
rank[i] = 0;
}
int min_cost = 0;
for(int i = 0; i < e; i++){
int src = g[i].second.first;
int dest = g[i].second.second;
int wt = g[i].first;
if(find(parent,src) != find(parent,dest)){
unite(parent,rank,src,dest);
min_cost += wt;
}
}
return min_cost;
}
int main() {
ALLONS_Y;
#ifdef DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int v,e;
cin >> v >> e;
pair<int,pii> g[e];
int src,dest,wt;
for(int i = 0; i < e; i++){
cin >> src >> dest >> wt;
g[i] = {wt,{src,dest}};
}
sort(g,g+e);
cout << krus(g,v,e) << endl;
return 0;
}<file_sep>#include<iostream>
using namespace std;
struct bt{
bt * left;
bt * right;
int data;
};
bool search(bt* root,int data){
if(root == NULL){
return false;
}
else if(root->data == data){
return true;
}
else if (data <= root->data){
return search(root->left,data);
}
else{
return search(root->right,data);
}
}
void insert(bt **sr, int data){
if(*sr == NULL){
*sr = new bt();
(*sr)->left = NULL;
(*sr)->right = NULL;
(*sr)->data = data;
}
else if(data <= (*sr)->data){
insert(&((*sr)->left),data);
}
else{
insert(&((*sr)->right),data);
}
return;
}
void preorder(bt * r){
if(r != NULL){
cout << r->data << " ";
preorder(r->left);
preorder(r->right);
}
}
void FindMax(bt * root){
if(root != NULL){
while(root->right != NULL){
root = root->right;
}
cout << root->data << endl;
}
else{
cout << "NULL" << endl;
}
}
/* Iterative way to find the min data in tree*/
//void FindMin(bt * root){
// if(root != NULL){
// while(root->left != NULL){
// root = root->left;
// }
// cout << root->data << endl;
// }
// else{
// cout << "NULL" << endl;
// }
//}
/*Recursive way to find the min data in tree*/
int FindMin(bt * root){
if(root == NULL){
cout << "Empty tree\n";
return -1;
}
else if(root -> left == NULL){
return root->data;
}
else
return FindMin(root->left);
}
int height(bt* root){
if(root == NULL){
return -1;
}
else{
int lheight = height(root->left);
int rheight = height(root->right);
return max(lheight,rheight) + 1;
}
}
int main(){
bt * root = NULL;
insert(&root,30);
insert(&root,20);
insert(&root,10);
insert(&root,40);
insert(&root,05);
cout <<"Prorder traversal of tree\n";
preorder(root);
int data;
cout << endl << "Enter data to search : \t";
cin >> data;
if(search(root,data)){
cout << "Found" << endl ;
}
else cout << "Not found" << endl;
cout << "Max data is ";
FindMax(root);
cout << "Min data is ";
cout << FindMin(root) << endl;
cout << "Height of tree is " << height(root);
return 0;
}
<file_sep>
#include<iostream>
#include<cstring>
using namespace std;
class String{
char * name;
int length;
public:
String(){ //Constructor-1
length = 0;
name = new char(length+1);
}
String(char * s){ //Constructor-2
length = strlen(s);
name = new char(length+1);
strcpy(name,s);
}
void display(void){
cout << name << endl;
}
void join(String &a , String &b);
};
void String::join(String &a , String &b){
length = a.length + b.length; //join is member function so possible to access private data
delete name;
name = new char[length + 1];
strcpy(name,a.name);
strcat(name,b.name);
};
int main(){
char a[] = "San ";
char b[] = "Neupane ";
char c[] = "Words ";
String name1(a), name2(b) , name3(c), s1 , s2;
s1.join(name1,name2);
s2.join(s1,name3);
name1.display();
name2.display();
name3.display();
s1.display();
s2.display();
return 0;
}
|
73dd85be1397814f63fd0be42b656e97e7fb9400
|
[
"C++"
] | 134
|
C++
|
San0330/C-Codes
|
fc37890c72eb8f7f81491fd177985c80f8bb0740
|
818441bf0b06e52c943dd12af6795fd59dd74df3
|
refs/heads/master
|
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { CompanyService } from '../shared';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';
@Component({
selector: 'app-company',
templateUrl: './company.component.html',
styleUrls: [ './company.component.css' ]
})
export class CompanyComponent implements OnInit {
company: ICompany;
departments: IDepartment[];
showSquares = true;
constructor(private _companyService: CompanyService,
private _activatedRoute: ActivatedRoute,
private _router: Router) {
}
ngOnInit() {
this._router.events.subscribe(() => this._updateSquares());
Observable.forkJoin(
this._companyService.getCompany(),
this._companyService.getDepartments()
).subscribe((data: [ ICompany, IDepartment[] ]) => {
const [ company, departments ] = data;
this.company = company;
this.departments = departments;
});
this._updateSquares();
}
private _updateSquares() {
this.showSquares = !this._activatedRoute.children.length;
}
}
<file_sep>import { Component, OnDestroy, OnInit } from '@angular/core';
import { CompanyService } from '../shared';
import { Subscription } from 'rxjs/Subscription';
import { ActivatedRoute, Router } from '@angular/router';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AbstractControl } from '@angular/forms/src/model';
@Component({
selector: 'app-member-form',
templateUrl: './member-form.component.html',
styleUrls: [ './member-form.component.css' ]
})
export class MemberFormComponent implements OnInit, OnDestroy {
form: FormGroup;
canUndo = false;
private _dataSubscription: Subscription;
private _history;
constructor(private _companyService: CompanyService,
private _activatedRoute: ActivatedRoute,
private _router: Router,
private _formBuilder: FormBuilder) {
}
ngOnInit() {
if (!this._activatedRoute.snapshot.params.memberId) {
this._makeForm();
return;
}
this._dataSubscription = this._activatedRoute.params.switchMap(() => this._companyService.getMember(
this._activatedRoute.snapshot.parent.params.departmentId,
this._activatedRoute.snapshot.params.memberId
)).subscribe((member: IMember) => this._makeForm(member));
}
ngOnDestroy() {
if (this._dataSubscription) {
this._dataSubscription.unsubscribe();
}
}
save() {
console.log(this.form.value);
if (this.form.invalid) {
console.log('fail!');
return;
}
const departmentId = this._activatedRoute.snapshot.parent.params.departmentId;
const {job, description, skills, gender, name} = this.form.value;
const _skills = {};
(skills as ISkill[]).forEach((skill: ISkill) => {
_skills[ skill.name ] = skill.level;
});
if (this._activatedRoute.snapshot.data.isAddForm) {
this._companyService.postMember(
departmentId,
{job, description, gender, name, skills: _skills}
).subscribe(() => {
this._router.navigate([ `/${departmentId}` ]);
console.log('POST is successful!');
});
return;
}
this._companyService.putMember(
departmentId,
this._activatedRoute.snapshot.params.memberId,
{job, description, gender, name, skills: _skills}
).subscribe(() => {
console.log('PUT is successful!');
});
}
undo() {
if (!this._history) {
return;
}
const skillsForm = this.form.get('skills') as FormArray;
const {name, gender, description, job, skills} = this._history;
while (skillsForm.length !== 0) {
skillsForm.removeAt(0);
}
this.form.setValue({name, gender, description, job, skills: []}, {
emitEvent: false
});
(skills as ISkill[]).forEach((skill: ISkill) => this.addSkill(skill));
this.canUndo = false;
}
addSkill(skill?: ISkill) {
const skills = this.form.get('skills') as FormArray;
if (!skill) {
skills.push(this._makeSkillForm());
return;
}
const {name, level} = skill;
skills.push(this._makeSkillForm(name, level));
}
removeSkill(index: number) {
const skills = this.form.get('skills') as FormArray;
skills.removeAt(index);
}
private _makeForm(member: IMember = {name: '', gender: 'M', job: '', description: '', skills: {}}) {
const skillsForm = this._formBuilder.array([]);
const {name, gender, skills, description, job} = member;
Object.keys(skills).forEach((key: string) => {
skillsForm.push(this._makeSkillForm(key, skills[ key ]));
});
this.form = this._formBuilder.group({
name: [ name, [
Validators.required,
Validators.maxLength(100)
] ],
gender: [ gender, [
Validators.required,
Validators.maxLength(1),
(c: AbstractControl) => [ 'F', 'M' ].indexOf(c.value) === -1 ? {error: 'Not match'} : null
] ],
job: [ job, [
Validators.required,
Validators.maxLength(100)
] ],
description: [ description, [
Validators.maxLength(255)
] ],
skills: skillsForm
});
this._history = this.form.value;
this.form.valueChanges.subscribe(() => this.canUndo = true);
}
private _makeSkillForm(name: string = '', level: number = 0): FormGroup {
return this._formBuilder.group({
name: [ name, [
Validators.required,
Validators.maxLength(100)
] ],
level: [ level, [
Validators.required,
(c: AbstractControl) => c.value > 100 || c.value < 0 ? {error: 'Not match'} : null
] ]
});
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../environments/environment';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class CompanyService {
private _host = environment.restApiEndpoint;
constructor(private _http: HttpClient) {
}
getCompany(): Observable<ICompany> {
return this._http.get<ICompany>(
`${this._host}/company`);
}
getDepartments(): Observable<IDepartment[]> {
return this._http.get<IDepartment[]>(
`${this._host}/company/departments`
);
}
getDepartment(departmentId: string): Observable<IDepartment> {
return this._http.get<IDepartment>(
`${this._host}/company/departments/${departmentId}`
);
}
getMembers(departmentId: string): Observable<IMember[]> {
return this._http.get<IMember[]>(
`${this._host}/company/departments/${departmentId}/members`
);
}
getMember(departmentId: string, memberId: string): Observable<IMember> {
return this._http.get<IMember>(
`${this._host}/company/departments/${departmentId}/members/${memberId}`
);
}
putMember(departmentId: string, memberId: string, member: IMember): Observable<IMember> {
return this._http.put<IMember>(
`${this._host}/company/departments/${departmentId}/members/${memberId}`,
member
);
}
postMember(departmentId: string, member: IMember): Observable<IMember> {
return this._http.post<IMember>(
`${this._host}/company/departments/${departmentId}/members`,
member
);
}
getSkills(departmentId: string, memberId: string): Observable<IMember> {
return this._http.get<IMember>(
`${this._host}/company/departments/${departmentId}/members/${memberId}/skills`
);
}
putSkills(departmentId: string, memberId: string, skills: ISkills): Observable<IMember> {
return this._http.put<IMember>(
`${this._host}/company/departments/${departmentId}/members/${memberId}/skills`,
skills
);
}
deleteSkills(departmentId: string, memberId: string, skills: ISkills): Observable<IMember> {
return this._http.delete<IMember>(
`${this._host}/company/departments/${departmentId}/members/${memberId}/skills`,
skills
);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { CompanyService } from '../shared';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';
import { ActivatedRoute, Params } from '@angular/router';
import 'rxjs/add/operator/switchMap';
@Component({
selector: 'app-department',
templateUrl: './department.component.html',
styleUrls: [ './department.component.css' ]
})
export class DepartmentComponent implements OnInit {
department: IDepartment;
members: IMember[];
showLeaderInfo = true;
constructor(private _companyService: CompanyService,
private _activatedRoute: ActivatedRoute) {
}
ngOnInit() {
this._activatedRoute.url.subscribe(() => {
this.showLeaderInfo = !this._activatedRoute.children.length;
});
this._activatedRoute.params.switchMap(({departmentId}) => Observable.forkJoin(
this._companyService.getDepartment(departmentId),
this._companyService.getMembers(departmentId)
)).subscribe((data: [ IDepartment, IMember[] ]) => {
const [ department, members ] = data;
this.department = department;
members.unshift(department.teamLeader);
this.members = members;
});
}
}
<file_sep>import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { CompanyService } from '../shared';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/operator/switchMap';
@Component({
selector: 'app-member',
templateUrl: './member.component.html',
styleUrls: [ './member.component.css' ]
})
export class MemberComponent implements OnInit, OnDestroy {
@Input()
member: IMember;
@Input()
isTeamLead = false;
get title(): 'Mr.' | 'Ms.' {
if (!this.member) {
return;
}
return this.member.gender === 'F' ? 'Ms.' : 'Mr.';
}
get skills(): ISkill[] {
if (!this.member) {
return [];
}
return Object.keys(this.member.skills)
.map((name: string) => ({name, level: this.member.skills[ name ]}))
.sort((s1: ISkill, s2: ISkill) => s1.level > s2.level ? -1 : 1);
}
private _dataSubscription: Subscription;
constructor(private _companyService: CompanyService,
private _activatedRoute: ActivatedRoute) {
}
ngOnInit() {
if (!this._activatedRoute.snapshot.params.memberId) {
return;
}
this._dataSubscription = this._activatedRoute.params.switchMap(() => this._companyService.getMember(
this._activatedRoute.snapshot.parent.params.departmentId,
this._activatedRoute.snapshot.params.memberId
)).subscribe((member: IMember) => this.member = member);
}
ngOnDestroy() {
if (this._dataSubscription) {
this._dataSubscription.unsubscribe();
}
}
}
<file_sep>import { Routes } from '@angular/router';
import { CompanyComponent } from '../company/company.component';
import { DepartmentComponent } from '../department/department.component';
import { MemberComponent } from '../member/member.component';
import { MemberFormComponent } from '../member-form/member-form.component';
export const rootRoutes: Routes = [
{
path: '',
component: CompanyComponent,
children: [
{
path: ':departmentId',
component: DepartmentComponent,
children: [
{
path: 'add-member',
component: MemberFormComponent,
data: {
isAddForm: true
}
},
{
path: ':memberId',
component: MemberComponent
},
{
path: ':memberId/edit',
component: MemberFormComponent
}
]
}
]
}
];
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { ReactiveFormsModule } from '@angular/forms';
import { rootRoutes } from './routers';
import { CompanyService } from './shared';
import { AppComponent } from './app.component';
import { CompanyComponent } from './company/company.component';
import { DepartmentComponent } from './department/department.component';
import { MemberComponent } from './member/member.component';
import { MemberFormComponent } from './member-form/member-form.component';
import { HttpClientModule } from '@angular/common/http';
import { InitialsPipe } from './shared/initials.pipe';
@NgModule({
declarations: [
AppComponent,
CompanyComponent,
DepartmentComponent,
MemberComponent,
MemberFormComponent,
InitialsPipe
],
imports: [
BrowserModule,
HttpClientModule,
RouterModule.forRoot(rootRoutes, {useHash: true}),
ReactiveFormsModule
],
providers: [ CompanyService ],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
<file_sep>/* SystemJS module definition */
declare var module: NodeModule;
interface NodeModule {
id: string;
}
interface ICompany {
name: string;
description: string;
departments: IDepartment[];
}
interface IDepartment {
id: string;
name: string;
description?: string;
teamLeader?: IMember;
members?: IMember[];
}
interface IMember {
id?: string;
name: string;
gender: 'M' | 'F';
job: string;
description: string;
skills: ISkills;
}
interface ISkills {
[key: string]: number;
}
interface ISkill {
name: string;
level: number;
}
<file_sep>export const environment = {
production: true,
restApiEndpoint: 'https://private-ff3a9-companyorganisation.apiary-mock.com'
};
|
02b7079ea69335b82acbd6bfb5156153ddfda849
|
[
"TypeScript"
] | 9
|
TypeScript
|
constantant/ubitricity-frontend-task
|
4533e44cf007cc63a19dec10c81b5a4da27a1d70
|
d447a3907ba1f62d98a299eb34d27ec57feff352
|
refs/heads/master
|
<repo_name>germainperdigal/greenmapping-bo<file_sep>/src/app/dashboard/dashboard.component.ts
import { Component, OnInit } from "@angular/core";
import * as Chartist from "chartist";
import { ApiService } from "app/services/api.service";
import { ToastrService } from "ngx-toastr";
const Chart = require("chart.js");
@Component({
selector: "app-dashboard",
templateUrl: "./dashboard.component.html",
styleUrls: ["./dashboard.component.css"],
})
export class DashboardComponent implements OnInit {
userCount = 0;
pinCount = 0;
constructor(private api: ApiService, private toastr: ToastrService) {}
ngOnInit() {
this.loadCityUsers();
this.loadPin();
const testChart = new Chart(document.getElementById("userChart"), {
type: "bar",
data: {
labels: ["10/29", "10/30", "10/31", "11/01", "11/02", "11/03"],
datasets: [
{
label: "Number of users",
data: [1, 3, 8, 12, 18, 43],
backgroundColor: [
"rgba(0, 135, 1, 0.33)",
"rgba(0, 135, 1, 0.33)",
"rgba(0, 135, 1, 0.33)",
"rgba(0, 135, 1, 0.33)",
"rgba(0, 135, 1, 0.33)",
"rgba(0, 135, 1, 0.33)",
],
borderColor: [
"rgba(0, 135, 1, 1)",
"rgba(0, 135, 1, 1)",
"rgba(0, 135, 1, 1)",
"rgba(0, 135, 1, 1)",
"rgba(0, 135, 1, 1)",
"rgba(0, 135, 1, 1)",
],
borderWidth: 1,
},
],
},
options: {
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
},
});
const ideasChart = new Chart(document.getElementById("ideasChart"), {
type: "line",
data: {
labels: ["10/29", "10/30", "10/31", "11/01", "11/02", "11/03"],
datasets: [
{
label: "Ideas per day",
data: [12, 25, 8, 1, 7, 6],
fill: true,
borderColor: "#008701",
backgroundColor: "rgba(0, 135, 1, 0.33)",
},
],
},
});
}
loadCityUsers() {
this.api.getCityUsers(40).then((users: any) => {
this.userCount = users.length;
});
}
loadPin() {
this.api.loadIdeas(40).then((pin: any) => {
this.pinCount = pin.length;
});
}
}
<file_sep>/src/app/ideas/ideas.component.ts
import { Component, OnInit } from '@angular/core';
import { ApiService } from 'app/services/api.service';
import { Router } from '@angular/router';
import 'rxjs/add/observable/interval';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
declare var global: any;
declare var require: any;
var geocoder = require('geocoder-fr');
@Component({
selector: 'app-ideas',
templateUrl: './ideas.component.html',
styleUrls: ['./ideas.component.css']
})
export class IdeasComponent implements OnInit {
ideas;
sub;
searchText;
range = 30;
constructor(private api: ApiService, public router: Router) { }
ngOnInit() {
this.loadIdeas();
}
loadIdeas() {
this.api.loadIdeas(this.range).then((result:any) => {
this.ideas = result;
this.ideas.forEach(pin => {
geocoder.reverse(pin.location.coordinates[0], pin.location.coordinates[1]).then((coords)=> pin.address = (coords.features[0].properties.label));
});
});
}
deletePin(id) {
this.api.deletePin(id).then(deleted => {
this.loadIdeas();
})
}
valueChanged(e) {
this.range = e;
this.loadIdeas();
}
}
<file_sep>/src/app/layouts/admin-layout/admin-layout.routing.ts
import { Routes } from '@angular/router';
import { DashboardComponent } from '../../dashboard/dashboard.component';
import { UsersComponent } from '../../users/users.component';
import { IdeasComponent } from '../../ideas/ideas.component';
import { LoginComponent } from 'app/login/login.component';
import { AuthGuardService } from 'app/services/auth-guard.service';
import { BillingComponent } from 'app/billing/billing.component';
export const AdminLayoutRoutes: Routes = [
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuardService] },
{ path: 'users', component: UsersComponent, canActivate: [AuthGuardService] },
{ path: 'pins', component: IdeasComponent, canActivate: [AuthGuardService] },
{ path: 'billing', component: BillingComponent, canActivate: [AuthGuardService] },
{ path: 'login', component: LoginComponent },
];
<file_sep>/src/app/psnfilter.pipe.ts
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({
name: 'psnfilter',
})
export class PsnfilterPipe implements PipeTransform {
transform(items: any[], searchText: string): any[] {
if (!items) return [];
if (!searchText) return items;
searchText = searchText.toLowerCase();
return items.filter(item => {
if(item.player1.psn && item.player1.psn.toLowerCase().includes(searchText)) {
return true;
}
if(item.player2.psn && item.player2.psn.toLowerCase().includes(searchText)) {
return true;
}
});
}
}<file_sep>/src/app/users/users.component.ts
import { Component, OnInit } from "@angular/core";
import { ApiService } from "app/services/api.service";
@Component({
selector: "app-users",
templateUrl: "./users.component.html",
styleUrls: ["./users.component.css"],
})
export class UsersComponent implements OnInit {
users;
p;
searchText;
range = 30;
constructor(private api: ApiService) {}
ngOnInit() {
this.loadUsers();
}
loadUsers() {
this.api.getCityUsers(this.range).then((result) => {
this.users = result;
});
}
delUser(id) {
this.api.deleteUser(id).then((result) => {
this.loadUsers();
});
}
valueChanged(e) {
this.range = e;
this.loadUsers();
}
}
<file_sep>/src/app/filter.pipe.ts
import {Pipe, PipeTransform} from "@angular/core";
@Pipe({
name: 'filter',
})
export class FilterPipe implements PipeTransform {
transform(items: Array<any>, term: any) {
if (Array.isArray(items) && items.length && term && term.length) {
return items.filter(item => {
let keys = Object.keys(item);
if (Array.isArray(keys) && keys.length) {
for (let key of keys) {
if (item.hasOwnProperty(key) && item[key] && item[key].length && (item[key].toString().toLowerCase().replace(/ /g, '')).includes((term.toString().toLowerCase().replace(/ /g, '')))) {
return true;
}
}
return false;
} else {
return false;
}
});
} else {
return items;
}
}
}<file_sep>/README.md
# Back Office for Green Mapping App
<file_sep>/src/app/psnfilter.pipe.spec.ts
import { PsnfilterPipe } from './psnfilter.pipe';
describe('PsnfilterPipe', () => {
it('create an instance', () => {
const pipe = new PsnfilterPipe();
expect(pipe).toBeTruthy();
});
});
<file_sep>/src/app/services/api.service.ts
import { Injectable } from "@angular/core";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Router } from "@angular/router";
import { ToastrService } from "ngx-toastr";
@Injectable({
providedIn: "root",
})
export class ApiService {
//apiBaseUrl = "http://localhost:4321/";
apiBaseUrl = "https://greenmapping.herokuapp.com/";
token: string = "Bearer ";
constructor(
private httpClient: HttpClient,
private router: Router,
private toastr: ToastrService
) {}
loadIdeas(range) {
let headers = new HttpHeaders({
"Content-Type": "application/json",
Authorization: localStorage.getItem("adminToken"),
});
let options = { headers: headers };
return new Promise((resolve, reject) => {
this.httpClient.get(this.apiBaseUrl + "pin/" + range, options).subscribe(
(data) => {
resolve(data);
},
(err) => {
this.toastr.error("Error loading pins !");
}
);
});
}
getUsers() {
let headers = new HttpHeaders({
"Content-Type": "application/json",
Authorization: localStorage.getItem("adminToken"),
});
let options = { headers: headers };
return new Promise((resolve, reject) => {
this.httpClient.get(this.apiBaseUrl + "user/user", options).subscribe(
(data) => {
resolve(data);
},
(err) => {
this.toastr.error("Error loading pins !");
}
);
});
}
updateUserAsso(asso) {
let headers = new HttpHeaders({
"Content-Type": "application/json",
Authorization: localStorage.getItem("adminToken"),
});
let options = { headers: headers };
return new Promise((resolve, reject) => {
this.httpClient
.patch(
this.apiBaseUrl + "user/association",
{ association: asso },
options
)
.subscribe(
(data) => {
resolve(data);
this.toastr.success(String(data));
},
(err) => {
console.log(err);
this.toastr.error("Error while setting association !");
}
);
});
}
deleteUser(id) {
let headers = new HttpHeaders({
"Content-Type": "application/json",
Authorization: localStorage.getItem("adminToken"),
});
let options = { headers: headers };
return new Promise((resolve, reject) => {
this.httpClient.delete(this.apiBaseUrl + "user/" + id, options).subscribe(
(data) => {
resolve(data);
this.toastr.success(String(data));
},
(err) => {
console.log(err);
this.toastr.error("Error while deleting this user !");
}
);
});
}
deletePin(id) {
let headers = new HttpHeaders({
"Content-Type": "application/json",
Authorization: localStorage.getItem("adminToken"),
});
let options = { headers: headers };
return new Promise((resolve, reject) => {
this.httpClient.delete(this.apiBaseUrl + "pin/" + id, options).subscribe(
(data) => {
resolve(data);
this.toastr.success(String(data));
},
(err) => {
console.log(err);
this.toastr.error("Error while deleting this pin !");
}
);
});
}
getCityUsers(range) {
let headers = new HttpHeaders({
"Content-Type": "application/json",
Authorization: localStorage.getItem("adminToken"),
});
let options = { headers: headers };
return new Promise((resolve, reject) => {
this.httpClient
.get(this.apiBaseUrl + "user/city/" + (range ? range : ""), options)
.subscribe(
(data) => {
resolve(data);
},
(err) => {
this.toastr.error("Loading failed !");
}
);
});
}
loginUser(username, password) {
let headers = new HttpHeaders({
"Content-Type": "application/json",
});
let options = { headers: headers };
var postData = { username, password };
return new Promise((resolve, reject) => {
this.httpClient
.post(this.apiBaseUrl + "user/login", postData, options)
.subscribe(
(data: any) => {
if (data.role === "administrative") {
this.token += data["token"];
localStorage.setItem("adminToken", this.token);
this.router.navigateByUrl("/dashboard");
this.toastr.success("Welcome !");
} else {
this.toastr.error("Forbidden !");
}
resolve(data);
},
(err) => {
this.toastr.error("Error thrown during login !");
}
);
});
}
}
|
1271054438f3362d311377448a7452d20776eb8b
|
[
"Markdown",
"TypeScript"
] | 9
|
TypeScript
|
germainperdigal/greenmapping-bo
|
f2e79d2c29b65c6d04f3eb878e236281777ce86d
|
754f2c4d3377422a8357b35c24d6229ff3017cd7
|
refs/heads/master
|
<file_sep>import { Component, OnInit } from '@angular/core';
import {User} from '../_models/index';
import {LoginserviceService} from '../loginservice.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
currentUser: User;
users: User[] = [];
isLoggedIn: boolean = false;
constructor(private _loginservice:LoginserviceService) {
this.currentUser=JSON.parse(localStorage.getItem('currentUser'));
}
ngOnInit() {
this.isLoggedIn=true;
}
logout()
{
localStorage.removeItem('currentUser');
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import {LoginserviceService} from '../loginservice.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
model: any = {};
loading = true;
returnUrl: string;
IsLogin:string;
constructor(private route: ActivatedRoute,
private router: Router,private _loginservice:LoginserviceService) { }
ngOnInit() {
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
localStorage.removeItem('currentUser');
}
Done():void
{
if(this.IsLogin!="")
{
alert('logged In Successfully');
}
else
{
alert('InVaild user and Password');
}
}
login()
{
this._loginservice.Login(this.model).subscribe(data=>{this.IsLogin=data,
this.loading=false,
localStorage.setItem('currentUser',JSON.stringify(data)),
this.router.navigate(['./home']);
// this.Done();
})
}
}
<file_sep>import { Injectable } from '@angular/core';
import { Http, Response,Headers,RequestOptions,RequestMethod} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import { Input } from '@angular/core/src/metadata/directives';
import { User } from './_models/index';
@Injectable()
export class LoginserviceService {
private _baseurl='http://localhost:62622/api/user/';
constructor(private _http:Http) { }
Register(model:User)
{
var body=JSON.stringify(model);
var ho=new Headers({'Content-Type':'application/json'});
var ro=new RequestOptions({method:RequestMethod.Post,headers:ho});
return this._http.post( this._baseurl+'Registeruser',body,ro)
.map(x=>x.json());
}
Login(model:User)
{
var body=JSON.stringify(model);
var ho=new Headers({'Content-Type':'application/json'});
var ro=new RequestOptions({method:RequestMethod.Post,headers:ho});
return this._http.post( this._baseurl+'VaildateUser',body,ro)
.map(x=>x.json());
}
}
<file_sep>import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login/login.component';
import {RegisterComponent} from './register/index';
import { AuthGuard } from './_guards/index';
import {HomeComponent} from './home/home.component';
const appRoutes: Routes = [
{ path:'home', component: HomeComponent, canActivate: [AuthGuard] },
{ path:'login', component:LoginComponent },
{ path:'register', component: RegisterComponent },
// otherwise redirect to home
{ path: '**', redirectTo: '' }
];
export const routing = RouterModule.forRoot(appRoutes);
|
b6997ccc300f73355823d9add287a3a8c68fafc4
|
[
"TypeScript"
] | 4
|
TypeScript
|
nwbabu/AngularLoginApp
|
166cddd1540befa3d59c54e0b2e48c9e53a31e02
|
dbbda17efab9967755190cd77e9c29a2f1e62f4f
|
refs/heads/master
|
<repo_name>sramako/QTest-Backend-Service<file_sep>/app.py
import os
from flask import Flask
from flask import request
import json
from flask_cors import CORS, cross_origin
import pymongo
import sys
from werkzeug import secure_filename
import pandas as pd
import time
import random
import string
import requests
from datetime import datetime
from datetime import timedelta
from dateutil import parser
import copy
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
# DATABASE CONNECTION
try:
DB_USER = 'ako'
DB_PASSWORD = '<PASSWORD>'
db_client = pymongo.MongoClient('mongodb://' + DB_USER + ':' + DB_PASSWORD + '@ds<EMAIL>.<EMAIL>.com:60749/sramako_qtest?retryWrites=false')
db = db_client["sramako_qtest"]
except:
print("DB Access FAILED.")
# UPLOAD TEST
@app.route('/uploader', methods = ['POST', 'GET'])
def upload_file():
if request.method == 'POST':
# Parse Data
f = request.files['file']
group = request.values['group']
test = request.values['test']
# Save File
f.save('upload/file.xlsx')
# Parse File
f = pd.read_excel('upload/file.xlsx', header=None)
data = []
for i, r in f.iterrows():
q = dict()
q['id'] = i+1
q[ 'question' ] = r[0]
q[ 'answers' ] = [
{ 'id' : 1, 'value' : r[1] },
{ 'id' : 2, 'value' : r[2] },
{ 'id' : 3, 'value' : r[3] },
{ 'id' : 4, 'value' : r[4] },
]
data.append(q)
n = len(data)
# Save to DB : metadata, questions, group, test
db_col = db["Tests"]
db_col.insert_one({
'metadata' : n,
'questions' : data,
'group' : group,
'test' : test
})
return 'Test has been registered.'
return " \
<title>Upload Test</title> \
<h1>Upload Test</h1> \
<form action='' method='POST' enctype='multipart/form-data'><p> \
<input type='file' name='file'><br/><br/> \
Test<br/><input type='text' name='test'><br/> \
Group<br/><input type='text' name='group'><br/><br/> \
<input type='submit' value='Upload'> \
</p></form>"
# GET USER'S AVAILABLE TESTS
@app.route('/tests', methods = ['POST'])
def tests():
if request.method == 'POST':
# Parse Data
# email = request.values['email']
# name = request.values['name']
# imageUrl = request.values['imageUrl']
# googleId= request.values['googleId']
email = ''
data = json.loads(request.data);
if 'email' in data:
email = data["email"]
# Check if user is registered
# TODO
# Get groups that are relevant
db_col = db["Groups"]
res = db_col.find( { 'EMAIL' : email }, { '_id':0, 'GROUP':1 } )
groups = []
for i in res:
groups.append(i['GROUP'])
groups = list(set(groups))
print(groups)
# Get tests for relevant groups
db_col = db["Tests"]
tests = []
for group in groups:
temp = db_col.find( { 'group' : group }, { '_id':0, 'test':1 } )
for i in temp:
tests.append(( group, i['test'] ))
tests = list(set(tests))
# REMOVE COMPLETED/ACTIVE TESTS
# TODO
return json.dumps(tests)
@app.route('/status', methods = ['POST'])
def status():
if request.method == 'POST':
# Parse Data
# name = request.values['name']
# imageUrl = request.values['imageUrl']
# googleId= request.values['googleId']
data = json.loads(request.data)
keys = ['email', 'test', 'group', 'answer']
statusData = dict()
for key in keys:
if key in data:
statusData[key] = data[key]
else:
return "Invalid Payload"
# Build Collection Record
query = {
'EMAIL' : statusData['email'],
'TEST' : statusData['test'],
'GROUP' : statusData['group']
}
record = copy.deepcopy(query)
# Check Test State
db_col = db["TestResponses"]
res = db_col.find(
query,
{
'_id' : 0,
'ANSWER' : 1,
'CLIMAX' : 1
}
)
# Pending Test
if res.count()==0:
climaxHours = 1
climaxMinutes = 1
climax = datetime.now() + timedelta( hours=climaxHours, minutes=climaxMinutes )
record['CLIMAX'] = str(climax)
record['ANSWER'] = statusData['answer'] # TODOx: Safe copy
# Write to DB
db_col.insert_one(
record
)
for i in range(0, len(record["ANSWER"])):
record["ANSWER"][i] = str(record["ANSWER"][i] )
return json.dumps({ 'ANSWER' : record["ANSWER"], 'CLIMAX' : record["CLIMAX"] })
else:
record = res.next()
# Active Test
if parser.parse(record['CLIMAX']) > datetime.now():
# record['ANSWER'] = statusData['answer'] # TODOx: Safe copy
for i in range(0, len(statusData['answer'])):
if int(statusData['answer'][i]) != -1:
record['ANSWER'][i] = statusData['answer'][i]
# Write to DB
db_col.update_one(
query,
{
"$set" : { 'ANSWER' : record['ANSWER'] }
},
upsert = False
)
for i in range(0, len(record["ANSWER"])):
record["ANSWER"][i] = str(record["ANSWER"][i] )
return json.dumps({ 'ANSWER' : record["ANSWER"], 'CLIMAX' : record["CLIMAX"] })
# Completed Test
else:
return "Test Completed"
# FETCH THE EXAM
@app.route('/metadata', methods = ['POST'])
def metadata():
if request.method == 'POST':
data = json.loads(request.data)
keys = ['email', 'test', 'group']
statusData = dict()
for key in keys:
if key in data:
statusData[key] = data[key]
else:
return "Invalid Payload"
# Build Collection Record
query = {
'test' : statusData['test'],
'group' : statusData['group']
}
record = copy.deepcopy(query)
# Check Test State
db_col = db["Tests"]
res = db_col.find(
query,
{
'_id' : 0,
'metadata' : 1,
'questions' : 1
}
)
data = res.next()
return json.dumps(data)
@app.route('/authenticate', methods = ['POST'])
def authenticate():
data = json.loads(request.data)
email = data['email']
db_col = db["Users"]
res = db_col.find(
{ 'email' : email },
{ 'email' : 1 }
)
# Login
if res.count()>0:
keys = ['email', 'password']
statusData = dict()
for key in keys:
if key in data:
statusData[key] = data[key]
else:
return "Invalid Payload"
# Build Collection Record
query = {
'email' : statusData['email'],
'password' : statusData['password']
}
# Check Test State
db_col = db["Users"]
values = ["googleId", "imageUrl", "email", "name", "givenName", "familyName", "password"]
returnValues = dict()
returnValues['_id'] = 0
for val in values:
returnValues[val] = 1
res = db_col.find(
query,
returnValues
)
if res.count==0:
json.dumps({"state":"error"})
data = res.next()
returnData = dict()
for val in values:
if val!="password":
returnData[val] = data[val]
return json.dumps(returnData)
else:
keys = ["googleId", "imageUrl", "email", "name", "givenName", "familyName", "<PASSWORD>"]
statusData = dict()
for key in keys:
statusData[key] = data[key]
db_col.insert_one(
statusData
)
return json.dumps({"state":"success"})
@app.route('/health', methods = ['GET'])
def health():
return "Ok"
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
# app.config['CORS_HEADERS'] = 'Content-Type'
app.run(host='0.0.0.0', port=port, debug=True)
# app.run()<file_sep>/requirements.txt
certifi==2019.11.28
chardet==3.0.4
Click==7.0
Cython==0.29.15
Flask==1.0.2
Flask-Cors==3.0.8
idna==2.9
itsdangerous==1.1.0
Jinja2==2.11.1
MarkupSafe==1.1.1
numpy==1.18.1
pandas==1.0.1
pymongo==3.10.1
python-dateutil==2.8.1
pytz==2019.3
requests==2.23.0
six==1.14.0
urllib3==1.25.8
Werkzeug==0.14
|
c4f490aa3467cd27bc8d08586ffd07f0b2d45bad
|
[
"Python",
"Text"
] | 2
|
Python
|
sramako/QTest-Backend-Service
|
472cb964c969b8ae1dcebf3769ce202d90564e12
|
2d8fa79ff285f48c06fbb6d9957ed0d7b40a7ccf
|
refs/heads/master
|
<file_sep>/**
* Created by Julien on 09/12/2016.
*/
'use strict';
angular.module('eklabs.angularStarterPack.upload',['ngFileUpload'])
.service('uploadImage', function($timeout, Upload){
return function(file, path,token,callback){
file.upload = Upload.upload({
url : 'http://91.134.241.60:3080/data',
method : 'POST',
headers : {
'Authorization' : token
},
file : file,
fields : { type : file.type.split('/')[1]}
});
file.upload.then(function(response){
$timeout(function () {
file.result = response.data;
return callback(response.data);
});
}, function(reason){
return callback(reason);
});
file.upload.progress(function(evt){
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
})
}
});<file_sep>'use strict';
angular.module('eklabs.angularStarterPack.user',[]);<file_sep>describe('demoOfferController', function() {
var $rootScope,
$scope,
Controller;
beforeEach(function(){
module('offer');
inject(function($injector){
$rootScope = $injector.get('$rootScope');
$scope = $rootScope.$new();
Controller = $injector.get('$Controller')("demoOfferController", {$scope: $scope});
});
});
it('should set save function', function() {
expect($scope.save).toBeDefined();
});
});
describe('demoOfferController', function() {
//…
it('should call /api/foo.json on $scope.save()', inject(function($httpBackend) {
$scope.save();
$httpBackend.expectPOST('/api/foo.json').respond();
$httpBackend.flush();
}));
});
describe('demoOfferController', function() {
//…
beforeEach(inject(function ($rootScope, $controller) {
//…
$location = jasmine.createSpyObj('$location', ['url']);
controller = $controller('demoOfferController', {
$scope: $scope,
$location: $location
});
}));
//…
it('should redirect to /redirect/to/url', inject(function($httpBackend) {
$scope.save();
$httpBackend.whenPOST('/api/foo.json').respond(200);
$httpBackend.flush();
expect($location.url).toHaveBeenCalledWith('/redirect/to/url');
}));
});<file_sep>'use strict';
angular.module('demoApp')
.config(function ($urlRouterProvider, $stateProvider) {
$stateProvider
// ------------------------------------------------------------------------------------------------
// HOMEPAGE - Init the current value
// ------------------------------------------------------------------------------------------------
.state('default', {
url : '/',
controller : 'homepageCtrl',
templateUrl : "pages/_homepage/homepageView.html"
})
// ------------------------------------------------------------------------------------------------
// DEMO EDITOR Component
// ------------------------------------------------------------------------------------------------
.state('jsonEditor', {
url : '/json-editor',
controller : 'demoEditorCtrl',
templateUrl : "pages/demoEditor/demoEditorView.html"
})
.state('myForm', {
url : '/my-form',
controller : 'demoFormCtrl',
templateUrl : "pages/demoform/demoFormView.html"
})
.state('myForm2', {
url : '/my-form-classique',
controller : 'demoUserCtrl',
templateUrl : "pages/demoUser/demoUserView.html"
})
/*
MY OFFER COMPONENT
*/
.state('myOffer', {
url : '/my-offer',
controller : 'demoOfferCtrl',
templateUrl : "pages/demoOffer/demoOfferView.html"
})
// Route de la création de l'offre
.state('addOffer', {
url : '/my-offer/add',
controller : 'addOfferCtrl',
templateUrl : "pages/demoOffer/addOfferView.html"
})
// Route de la suppression de l'offre
.state('removeOffer', {
url : '/my-offer/remove',
controller : 'removeOfferCtrl',
templateUrl : "pages/demoOffer/removeOfferView.html"
})
;
$urlRouterProvider.otherwise('/my-offer');
});<file_sep>'use strict';
angular.module('eklabs.angularStarterPack.offer')
.directive('removeOffer',function($log, $location, Offers){
return {
templateUrl : 'eklabs.angularStarterPack/modules/offers/views/MyRemoveOfferView.html',
scope : {
offer : '=?',
callback : '=?',
listOffer : '='
},link : function(scope, attr, $http) {
// Initialisation du constructeur
var offersCreation = new Offers();
// Supprimer une offre de stage
scope.deleteOffer = function(idOfferToDelete) {
offersCreation.deleteOffer(idOfferToDelete).then(idOfferToDelete);
alert("L\'annonce a bien été supprimer. Vous allez être redirigé sur la page d'accueil. ");
};
}
}
})
<file_sep>'use strict';
angular.module('demoApp')
.controller('demoOfferCtrl', function($scope,$mdDialog,$http,$timeout,$log,Offers){
var offers = new Offers();
var newOffer = {};
// Récupérer toutes les offres de stage
offers.getAllOffers().then(function(items){
$scope.offers = items;
})
$scope.page = {
title : 'Directive My Offer',
haveCodeSource : true,
code : [{
link : 'pages/demoOffer/code/directive.html',
language : 'html',
title : 'Code HTML de la directive demo-offer'
},{
link : 'pages/demoOffer/code/params.json',
language : 'json',
title : 'Params available for the directive demo-offer'
}]
};
/**
* MODE Fullscreen
*/
$scope.fullScreenMode = true;
$scope.hideParams = false;
$scope.fullScreen = function(){
$scope.hideParams = !$scope.hideParams;
};
});
<file_sep>describe("true",function() {
it("Should be true", function() {
expect(true).toBeTruthy();
});
});
describe('demoOfferController', function() {
var $rootScope,
$scope,
Controller;
beforeEach(function(){
module('offer');
inject(function($injector){
$rootScope = $injector.get('$rootScope');
$scope = $rootScope.$new();
Controller = $injector.get('$Controller')("demoOfferController", {$scope: $scope});
});
});
});
describe('demoOfferController', function() {
//…
it('should call /api/foo.json on $scope.save()', inject(function($httpBackend) {
$scope.save();
$httpBackend.expectPOST('/api/foo.json').respond();
$httpBackend.flush();
}));
});<file_sep>'use strict';
angular.module('eklabs.angularStarterPack.offer')
.directive('addOffer',function($log, $mdDialog, $mdMedia, $location, Offers, $http, uploadImage){
return {
templateUrl : 'eklabs.angularStarterPack/modules/offers/views/MyAddOfferView.html',
scope : {
offer : '=?',
callback : '=?',
listOffer : '='
},link : function(scope, attr, $http, uploadImage) {
// Initialisation du constructeur
var offersCreation = new Offers();
// Contenu du scope pour la création de l'offre
var dataToCreateOffer = '';
// Soumission du formulaire d'ajout d'une offre
scope.submit = function() {
// On ajoute la date et logo manuellement
scope.newOffer.publicationdate = new Date();
console.log(scope.newOffer.logo);
if(scope.newOffer.logo != undefined) {
scope.newOffer.logo.upload('','http://172.16.31.10:3080/data');
}
else {
scope.newOffer.logo = "images/logo-offer/default.png";
}
dataToCreateOffer = scope.newOffer;
dataToCreateOffer = JSON.stringify(dataToCreateOffer);
// On crée l'offre, et on l'a rentre dans l'API
offersCreation.createOffer(dataToCreateOffer).then(dataToCreateOffer);
$location.path('/my-offer');
alert("L\'annonce pour le stage à bien été ajouté. Vous allé être redirigé sur la page d'accueil ");
};
}
}
})
<file_sep>/**
* Created by Julien on 19/11/2016.
*/
angular.module('eklabs.angularStarterPack.offer')
.factory('Offers',function($http, $q){
/*
Si tu veux tester l'upload de fichier :
[POST] http://172.16.31.10:3080/data
Cela te retournera le lien du fichier disponible sur le serveur.
Vous pouvez aussi utiliser cette API pour faire vos elements CRUD de votre composant ( je reviendrais dessus jeudi après midi )
[GET] http://172.16.31.10:3080/resources/nom_de_votre_resource/ => Liste de toutes les ressources nom_de_votre_resource
[POST] http://91.134.241.60:3080/resources/nom_de_votre_resource/ => Créer une ressource -> retourne l'ID de la resource
[GET] http://172.16.31.10:3080/resourc…/nom_de_votre_resource/:id => retourne une resource
[PUT] http://91.134.241.60:3080/resourc…/nom_de_votre_resource/:id => update une resource
[DELETE] http://91.134.241.60:3080/resourc…/nom_de_votre_resource/:id => supprime une resource
*/
var configOffer = {defaultUrl : 'http://172.16.31.10:3080/resources/offers'};
var offers = function(data) {
this.items = data;
}
offers.prototype = {};
offers.prototype.constructor = offers;
// Récupérer toutes les offres de stage
offers.prototype.getAllOffers = function () {
var defer = $q.defer();
var self = this;
$http.get(configOffer.defaultUrl).then(function(response) {
self.items = response.data;
defer.resolve(response.data);
})
return defer.promise;
}
/*
deffer.resolve(response);
}, function(error) {
defer.reject(error)
}
return defer.promise;
*/
// Créer une offre de stage
offers.prototype.createOffer = function(data) {
var defer = $q.defer();
console.log(data);
$http.post(configOffer.defaultUrl, data).then(function(res) {
defer.resolve(res);
})
return defer.promise;
}
// Envoyer une image à l'api
// Supprimer une offre
offers.prototype.deleteOffer = function(id){
var defer = $q.defer();
$http.delete(configOffer.defaultUrl + '/' + id)
.success(function(res){
defer.resolve(res);
})
.error(function(err, status){
defer.reject(err);
})
return defer.promise;
}
return offers;
})
|
7522e471e86bb6649260aa588768fa89ea494b40
|
[
"JavaScript"
] | 9
|
JavaScript
|
julienbnr/InternMe
|
d1143e491de69b1f11a15581ed8515cb22e698dd
|
4b0e8bb4196a73e755453167603eb38532a71fa9
|
refs/heads/master
|
<file_sep>#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright 2018- <<EMAIL>>
""" find word in current directory """
import sys
import os
sys.path.append('.')
import util
def help_msg():
print("Brief:")
print(" find [word] in current directory")
print("Usage:")
print(" %s [word]" % util.get_command_name())
print("Try again")
exit(1)
if __name__ == '__main__':
util.check_help_message(help_msg)
if len(sys.argv) != 2:
help_msg()
os.system('ag -w --smart-case --depth -1 -p %s %s .' %
(util.get_ag_ignore_file(), util.get_sys_args_one_line()))
<file_sep>#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright 2018- <<EMAIL>>
""" delete *.[suffix] files in current directory """
import sys
import os
sys.path.append('.')
import util
def help_msg():
print("Brief:")
print(" 1. delete *.[suffix] file")
print(" 2. delete file which has no suffix")
print("Usage:")
print(" 1. %s [suffix]" % util.get_command_name())
print(" 2. %s" % util.get_command_name())
print("Try again")
exit(1)
def delete_suffix(file_list, suffix):
suffix = '.%s' % suffix
for f in file_list:
assert isinstance(f, str)
relname = os.path.relpath(f)
if relname.startswith('.'):
continue
if relname.endswith(suffix):
print('[boostscript] remove %s' % f)
os.remove(f)
def delete_no_suffix(file_list):
for f in file_list:
assert isinstance(f, str)
relname = os.path.relpath(f)
if relname.startswith('.'):
continue
if relname.find('.') < 0:
print('[boostscript] remove %s' % f)
os.remove(f)
if __name__ == '__main__':
util.check_help_message(help_msg)
if len(sys.argv) > 2:
help_msg()
file_list = util.recursive_list_dir('.')
if len(sys.argv) <= 1:
delete_no_suffix(file_list)
else:
suffix = util.trim_quotation(sys.argv[1])
delete_suffix(file_list, suffix)
<file_sep>#! /usr/bin/env sh
# Copyright 2018- <<EMAIL>>
python3 ~/.boostscript/command/ipv6str.py $@
<file_sep>#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright 2018- <<EMAIL>>
""" git discard all changes """
import sys
import os
import re
sys.path.append('.')
import util
def help_msg():
print("Brief:")
print(" 1. git discard all changes")
print(" 2. git discard the specified [filename/directory]")
print("Usage:")
print(" 1. %s" % util.get_command_name())
print(" 2. %s [filename/directory]" % util.get_command_name())
print("Try again")
exit(1)
def discard_all():
branch = util.get_git_current_branch()
util.check_user_confirm(
"[boostscript] git discard all changes on \'%s\', yes? " % (branch))
save_dir = os.getcwd()
os.chdir(util.get_git_root())
modifies = util.get_git_modified_files()
untracts = util.get_git_untract_files()
discard_file_impl(modifies, modifies, untracts)
discard_file_impl(untracts, modifies, untracts)
if os.path.exists(save_dir):
os.chdir(save_dir)
def discard_file_impl(file_list, modifies, untracts):
for i in file_list:
if i in modifies:
print('[boostscript] discard: %s' % (i + ' '))
os.system('git checkout %s' % (i + ' '))
elif i in untracts:
print('[boostscript] remove: %s' % (i + ' '))
os.system('rm %s' % (i + ' '))
def discard_file(file_name):
branch = util.get_git_current_branch()
util.check_user_confirm(
"[boostscript] git discard file \'%s\' on \'%s\', yes? " %
(file_name, branch))
save_dir = os.getcwd()
os.chdir(util.get_git_root())
modifies = util.get_git_modified_files()
untracts = util.get_git_untract_files()
discard_file_impl([file_name], modifies, untracts)
if os.path.exists(save_dir):
os.chdir(save_dir)
def discard_dir(dir_name):
branch = util.get_git_current_branch()
util.check_user_confirm(
"[boostscript] git discard folder \'%s\' on \'%s\', yes? " %
(dir_name, branch))
save_dir = os.getcwd()
os.chdir(util.get_git_root())
file_list = util.recursive_list_dir_relative(dir_name)
modifies = util.get_git_modified_files()
untracts = util.get_git_untract_files()
discard_file_impl(file_list, modifies, untracts)
if os.path.exists(save_dir):
os.chdir(save_dir)
if __name__ == '__main__':
util.check_help_message(help_msg)
util.check_git_repository()
if len(sys.argv) > 2:
help_msg()
if len(sys.argv) <= 1:
discard_all()
else:
target = util.get_sys_args_one_line()
if os.path.isfile(target):
discard_file(target)
else:
discard_dir(target)
<file_sep>#! /usr/bin/env sh
# Copyright 2018- <<EMAIL>>
python3 ~/.boostscript/command/ipv6u128.py $@
<file_sep>#!/usr/bin/env bash
echo [boostscript] Install BoostScript for MacOS
# Prepare Environment
touch ~/.bashrc
touch ~/.zshrc
# Software
brew update
brew upgrade
brew install git python3 unzip zip p7zip wget the_silver_searcher
sudo pip3 install pyOpenSSL chardet
if [ -d ~/.config ]; then
sudo chmod -R +rwx ~/.config
sudo chown -R $USER ~/.config
fi
# Git Config
git config core.filemode false
# Variable
cd ~/.boostscript/command
chmod +x *
echo "export PATH=\$PATH:~/.boostscript/command" >> ~/.bashrc
echo "export PATH=\$PATH:~/.boostscript/command" >> ~/.zshrc
source ~/.bashrc
source ~/.zshrc
<file_sep>#! /usr/bin/env bash
# Copyright 2018- <<EMAIL>>
python3 ~/.boostscript/command/filecode.py $@
<file_sep>#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright 2018- <<EMAIL>>
""" boostscript help document """
import sys
import os
import time
import datetime
sys.path.append('.')
import util
def auto_echo(command_home):
os.chdir(command_home)
sys.path.append('.')
echo = list()
command_list = [x for x in os.listdir('.') if x.endswith('.py')]
command_list.sort()
space_cnt = max(
[len(x)
for x in command_list if util.get_file_name_suffix(x) == 'py']) - 2
for i in command_list:
if util.get_file_name_suffix(i) != 'py':
continue
command_name = util.get_file_name_base(i)
command_module = __import__(command_name)
command_doc = command_module.__doc__
if command_doc is None:
continue
if command_name == util.get_command_name():
continue
spaces = ' ' * (space_cnt - len(command_name))
echo.append(" %s%s- %s" % (command_name, spaces, command_doc))
return echo
def print_echo(echo):
print("Usage:")
for e in echo:
print(e)
print("")
print("Use -h/--help for more detail. Enjoy :)")
if __name__ == '__main__':
echo = list()
echo.extend(auto_echo(util.get_command_home()))
print_echo(echo)
<file_sep># Boost Script
Script commands to boost up your development.
*Suggest using with [lin-vim](https://github.com/linrongbin16/lin-vim)*.
#### Linux, UNIX, MacOS Installation
```bash
$ git clone https://github.com/linrongbin16/boostscript.git ~/.boostscript
$ cd ~/.boostscript
$ bash install.sh
```
#### Windows Installation
1. Install [Git](https://git-scm.com/), choose **Use Git from Windows Command Prompt** since we rely on UNIX command.
2. Install [Python3](https://www.python.org/downloads/), choose **Add python to PATH for ALL Users**, install packages globally `pip3 install pyOpenSSL chardet`.
3. Install [ag.exe](https://github.com/k-takata/the_silver_searcher-win32/releases), make sure **ag.exe** available in **PATH**.
4. Install [zip.exe](http://gnuwin32.sourceforge.net/packages/zip.htm), make sure **zip.exe** available in **PATH**.
5. Install [unzip.exe](http://gnuwin32.sourceforge.net/packages/unzip.htm), make sure **unzip.exe** available in **PATH**.
6. Add `%%USERPROFILE%%\.boostscript\command\` to `PATH`.
```bash
$ git clone https://github.com/linrongbin16/boostscript.git %USERPROFILE%\.boostscript
$ cd ~/.boostscript
$ install.bat
```
#### Usage
Type `boostscript` for more Details.
<file_sep>#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright 2018- <<EMAIL>>
import sys
import os
import threading
import platform
import datetime
import time
import re
import string
import subprocess
import calendar
# platform utils
def is_windows():
return platform.system() == 'Windows'
def is_linux():
return platform.system() == 'Linux'
def is_ubuntu():
if platform.system() == 'Linux':
import distro
return distro.linux_distribution()[0].find('Ubuntu') >= 0
return False
def is_debian():
if platform.system() == 'Linux':
import distro
return distro.linux_distribution()[0].find('Debian') >= 0
return False
def is_manjaro():
if platform.system() == 'Linux':
import distro
return distro.linux_distribution()[0].find('Manjaro') >= 0
return False
def is_macos():
return platform.system() == 'Darwin'
def get_platform_name():
if is_windows():
return 'windows'
elif is_macos():
return 'macos'
elif is_linux():
if is_ubuntu():
return 'ubuntu'
elif is_manjaro():
return 'manjaro'
else:
return None
else:
return None
# path utils
def get_file_name_suffix(name):
if len(name) <= 0:
return ''
if name[0] == '.':
return ''
dot_pos = name.rfind('.')
if dot_pos >= 0:
return name[dot_pos + 1:]
return ''
def get_file_name_all_suffix(name):
if len(name) <= 0:
return ''
if name[0] == '.':
return ''
dot_pos = name.find('.')
if dot_pos >= 0:
return name[dot_pos + 1:]
return ''
def get_file_name_base(name):
if len(name) <= 0:
return ''
if name[0] == '.':
return ''
dot_pos = name.rfind('.')
if dot_pos >= 0:
return name[:dot_pos]
return name
def get_command_home():
if is_windows():
return os.path.expanduser('~') + '\\.boostscript\\command'
else:
return os.path.expanduser('~') + '/.boostscript/command'
def get_command_name():
py_name = sys.argv[0][:-3]
left_slash = py_name.rfind('/')
right_slash = py_name.rfind('\\')
py_name = py_name[left_slash + 1:] if left_slash >= 0 else py_name
py_name = py_name[right_slash + 1:] if right_slash >= 0 else py_name
return py_name
def get_file_name(file_name):
if file_name[0] == "/":
file_name = file_name[1:]
if file_name[0] == "\\":
file_name = file_name[1:]
if file_name[-1] == "/":
file_name = file_name[:-1]
if file_name[-1] == "\\":
file_name = file_name[:-1]
return file_name
def find_file_up_impl(start_path, file_name):
os.chdir(start_path)
if os.path.exists(file_name):
return start_path
if os.path.abspath(".") == os.path.abspath("/"):
return None
for ch in string.ascii_uppercase:
if os.path.abspath(".") == os.path.abspath("%s:\\" % (ch)):
return None
return find_file_up_impl(os.path.abspath(".."), file_name)
def find_file_up(start_path, file_name):
save_dir = os.path.abspath(".")
result = find_file_up_impl(os.path.abspath("."), file_name)
if os.path.exists(save_dir):
os.chdir(save_dir)
return result
def backup_file(target):
if not os.path.exists(target):
return
bakname = ".%s.bak" % (target)
check_user_confirm("[boostscript] backup existed '%s' to '%s', yes? " %
(target, bakname))
if os.path.exists(bakname):
os.rmdir(bakname)
os.rename(target, bakname)
def recursive_list_dir(directory):
save_dir = os.getcwd()
os.chdir(directory)
file_list = []
for root, ds, fs in os.walk(os.getcwd()):
fs[:] = [f for f in fs if not f[0] == '.']
ds[:] = [d for d in ds if not d[0] == '.']
for f in fs:
file_list.append(os.path.join(root, f))
if os.path.exists(save_dir):
os.chdir(save_dir)
return file_list
def recursive_list_dir_relative(directory):
file_list = recursive_list_dir(directory)
return [os.path.relpath(p) for p in file_list]
# process utils
def run(*cmd):
try:
proc = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout_str = iter(proc.stdout.readline, b"")
stderr_str = iter(proc.stderr.readline, b"")
except subprocess.CalledProcessError:
exit(3)
outstr = [x.decode() for x in stdout_str if len(x) > 0]
errstr = [x.decode() for x in stderr_str if len(x) > 0]
return outstr, errstr
# args utils
def get_sys_args_one_line(start=1):
args = [sys.argv[i] for i in range(len(sys.argv)) if i >= start]
return ' '.join(args).strip()
def check_help_message(help_msg_func):
if len(sys.argv) >= 2:
if sys.argv[1] in ("--help", "-h", "-help"):
help_msg_func()
def check_user_confirm(msg):
yes = input(msg)
if not yes.lower().startswith('y'):
print("[boostcript] error: user not confirm")
exit(3)
# date time utils
def date_to_second(d, local=True):
assert isinstance(d, datetime.date)
if local:
return time.mktime(d.timetuple())
else:
utc = time.gmtime(time.mktime(d.timetuple()))
return time.mktime(utc)
def datetime_to_second(dt, local=True):
assert isinstance(dt, datetime.datetime)
if local:
return time.mktime(dt.timetuple())
else:
utc = time.gmtime(time.mktime(dt.timetuple()))
return time.mktime(utc)
# number string utils
def number_to_string(n):
if isinstance(n, int):
return str(n)
else:
n_int = int(n)
if float(n_int) == float(n):
return str(n_int)
else:
return str(n)
def is_empty_str(s):
return True if (s is None) else (len(s.strip()) == 0)
def trim_quotation(s):
s = s.strip()
if s[0] == '\"' or s[0] == '\'':
s = s[1:]
if s[-1] == '\"' or s[-1] == '\'':
s = s[:-1]
return s
# ag utils
def get_ag_ignore_file():
return (get_command_home() +
'\\ag.ignore') if is_windows() else (get_command_home() +
'/ag.ignore')
# git utils
def get_git_root():
root, _ = run('git', 'rev-parse', '--show-toplevel')
return root[0].strip() if (len(root) > 0) else None
def check_git_repository():
if get_git_root() is None:
print("[boostscript] error: not a git repository")
exit(3)
def get_git_current_branch():
lines, _ = run('git', 'status')
return lines[0].split(' ')[2].strip()
def get_git_modified_files():
result, _ = run('git', 'ls-files', '-m')
return [modified_file.strip() for modified_file in result]
def get_git_untract_files():
result, _ = run('git', 'ls-files', '--others', '--exclude-standard')
return [untract_file.strip() for untract_file in result]
def get_git_remote_repository_count():
branches, _ = run('git', 'remote')
return len(branches)
def get_git_remote_repository():
branches, _ = run('git', 'remote')
remote_branches = [x.strip() for x in branches]
if len(remote_branches) < 1:
return None
remote_str = ""
if len(remote_branches) > 1:
remote_branches.sort()
remote_str = ''
for i in range(len(remote_branches)):
remote_str = remote_str + "\'" + remote_branches[i] + "\'[" + str(
i) + "]"
if i < len(remote_branches) - 1:
remote_str = remote_str + ', '
print('[boostscript] detect multiple remote repositories: %s' %
(remote_str))
user_input = input(
'[boostscript] which one to choose(%s[0] if empty)? ' %
("\'" + remote_branches[0] + "\'"))
if not is_empty_str(user_input):
try:
remote_str = list(remote_branches)[int(user_input)]
except Exception:
print('[boostscript] error input: %s' % (user_input))
exit(3)
else:
remote_str = list(remote_branches)[0]
if len(remote_branches) == 1:
remote_str = list(remote_branches)[0]
return remote_str
def check_git_is_behind():
os.system('git fetch')
status, _ = run('git', 'status')
return len([s for s in status if s.find('Your branch is behind') >= 0]) > 0
def check_git_is_ahead():
os.system('git fetch')
status, _ = run('git', 'status')
return len([s for s in status if s.find('Your branch is ahead') >= 0]) > 0
def get_git_last_commit(n):
commits, _ = run('git', 'log', '--pretty=oneline')
return commits[n].split(' ')[0]
def git_has_branch(target_br):
os.system('git fetch')
branches, _ = run('git', 'branch', '-a')
return len([b for b in branches if b.find(target_br) >= 0]) > 0
# ip utils
IPV4_PATTERN = re.compile(r'^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$')
IPV6_PATTERN = re.compile(
r'^[0-9,a-e,A-E]{1,4}:[0-9,a-e,A-E]{1,4}:[0-9,a-e,A-E]{1,4}:[0-9,a-e,A-E]{1,4}:[0-9,a-e,A-E]{1,4}:[0-9,a-e,A-E]{1,4}:[0-9,a-e,A-E]{1,4}:[0-9,a-e,A-E]{1,4}$'
)
def check_valid_ipv4(ipaddr):
try:
if not IPV4_PATTERN.match(ipaddr):
return False
ip_splits = ipaddr.split('.')
if len(ip_splits) != 4:
return False
for each_ip in ip_splits:
tmp = int(each_ip)
if tmp < 0 or tmp > 255:
return False
return True
except Exception:
return False
def check_valid_ipv6(ipaddr):
try:
if not IPV6_PATTERN.match(ipaddr):
return False
ip_splits = ipaddr.split(':')
if len(ip_splits) != 8:
return False
for each_ip in ip_splits:
print('each_ip: %s' % (each_ip))
if not all(c in string.hexdigits for c in each_ip):
print('not hex string')
return False
return True
except Exception:
return False
def ipv4_string_to_uint32(ipstr):
ip_split = ipstr.split('.')
p1 = int(ip_split[0]) * 16777216
p2 = int(ip_split[1]) * 65536
p3 = int(ip_split[2]) * 256
p4 = int(ip_split[3])
return p1 + p2 + p3 + p4
def ipv4_uint32_to_string(ipint):
p1 = int(ipint / 16777216) % 256
p2 = int(ipint / 65536) % 256
p3 = int(ipint / 256) % 256
p4 = int(ipint) % 256
return '%d.%d.%d.%d' % (p1, p2, p3, p4)
def ipv6_string_to_uint128(ipstr):
ip_split = ipstr.split('.')
p1 = int(ip_split[0]) * 16777216
p2 = int(ip_split[1]) * 65536
p3 = int(ip_split[2]) * 256
p4 = int(ip_split[3])
return p1 + p2 + p3 + p4
def ipv6_uint128_to_string(ipint):
p1 = int(ipint / 16777216) % 256
p2 = int(ipint / 65536) % 256
p3 = int(ipint / 256) % 256
p4 = int(ipint) % 256
return '%d.%d.%d.%d' % (p1, p2, p3, p4)
<file_sep>#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright 2018- <<EMAIL>>
""" translate uint32 ipv4 address to string """
import sys
sys.path.append('.')
import util
def help_msg():
print("Brief:")
print(" transform an ipv4 [uint32] to ipstr")
print("Usage:")
print(" %s [uint32]" % util.get_command_name())
print("Try again")
exit(1)
if __name__ == '__main__':
util.check_help_message(help_msg)
if len(sys.argv) != 2:
help_msg()
ipaddr = int(sys.argv[1])
print(util.ipv4_uint32_to_string(ipaddr))
<file_sep>#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright 2018- <<EMAIL>>
""" compress *.tar.gz """
import sys
import os
sys.path.append('.')
import util
def help_msg():
print("Brief:")
print(" 1. compress [file/directory] to *.tar.gz")
print(" 2. compress [file/directory] to *.[type] ")
print("Usage:")
print(" 1. %s [file/directory]" % util.get_command_name())
print(" 2. %s [file/directory] [type](tar.gz/tgz/tar.bz2/zip) " %
util.get_command_name())
print("Try again")
exit(1)
def compressTargz(target):
tarname = "%s.tar.gz" % target
util.backup_file(tarname)
os.system('tar czvf "%s" "%s"' % (tarname, target))
print("[boostscript] compress '%s' to '%s'" % (target, tarname))
def compressTgz(target):
tarname = "%s.tgz" % target
util.backup_file(tarname)
os.system('tar czvf "%s" "%s"' % (tarname, target))
print("[boostscript] compress '%s' to '%s'" % (target, tarname))
def compressTarbz2(target):
tarname = "%s.tar.bz2" % target
util.backup_file(tarname)
os.system('tar czvf "%s" "%s"' % (tarname, target))
print("[boostscript] compress '%s' to '%s'" % (target, tarname))
def compressZip(target):
tarname = "%s.zip" % target
util.backup_file(tarname)
os.system('zip -r "%s" "%s"' % (tarname, target))
print("[boostscript] compress '%s' to '%s'" % (target, tarname))
PackMapping = {
'tar.gz': compressTargz,
'tgz': compressTgz,
'zip': compressZip,
'tar.bz2': compressTarbz2
}
if __name__ == '__main__':
util.check_help_message(help_msg)
if len(sys.argv) < 2 or len(sys.argv) > 3:
help_msg()
target = util.get_file_name(sys.argv[1])
if target in ('.', '..'):
help_msg()
tp = 'tar.gz'
if len(sys.argv) == 3:
tp = sys.argv[2]
if tp not in PackMapping.keys():
help_msg()
packer = PackMapping[tp]
packer(target)
<file_sep>#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright 2018- <<EMAIL>>
""" unpack *.tar.gz *.zip *.tgz *.rar *.tax *.jar files """
import sys
import os
sys.path.append('.')
import util
def help_msg():
print("Brief:")
print(" extract compressed [file]")
print("Usage:")
print(" %s [file]" % util.get_command_name())
print("Try again")
exit(1)
def unpackTarGz(target):
os.system('tar zxvf "%s"' % (target))
def unpackTar(target):
os.system('tar xvf "%s"' % (target))
def unpackTarBz2(target):
os.system('tar xvf "%s"' % (target))
def unpackZip(target):
os.system('unzip "%s"' % (target))
def unpackJar(target):
os.system('jar xf "%s"' % (target))
UnpackMapping = {
'tar.gz': unpackTarGz,
'tgz': unpackTarGz,
'tar': unpackTar,
'tar.bz2': unpackTarBz2,
'zip': unpackZip,
'jar': unpackJar,
}
if __name__ == '__main__':
util.check_help_message(help_msg)
if len(sys.argv) != 2:
help_msg()
target = util.get_sys_args_one_line()
if target == "." or target == "..":
help_msg()
foldname = target[:target.index(".")]
util.backup_file(foldname)
ts = util.get_file_name_all_suffix(target)
if ts not in UnpackMapping.keys():
help_msg()
unpacker = UnpackMapping[ts]
unpacker(target)
print("[boostscript] extract '%s' to '%s'" % (target, foldname))
<file_sep>#! /usr/bin/env bash
# Copyright 2018- <<EMAIL>>
python3 ~/.boostscript/command/timestr.py $@
<file_sep>#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright 2018- <<EMAIL>>
""" git show local/remote branches """
import sys
import os
import re
sys.path.append('.')
import util
def help_msg():
print("Brief:")
print(" 1. git show all branches")
print(" 2. git show only local branches")
print(" 3. git show only remote branches")
print("Usage:")
print(" 1. %s" % util.get_command_name())
print(" 2. %s l/local" % util.get_command_name())
print(" 3. %s r/remote" % util.get_command_name())
print("Try again")
exit(1)
def local_branch():
outstr, errstr = util.run("git", "branch")
print("[boostscript] local branches")
for o in outstr:
print(" %s" % (o.strip()))
def remote_branch():
outstr, errstr = util.run("git", "branch", "-r")
print("[boostscript] remote branches")
for o in outstr:
print(" %s" % (o.strip()))
if __name__ == '__main__':
util.check_help_message(help_msg)
util.check_git_repository()
# case 1
if len(sys.argv) <= 1:
local_branch()
remote_branch()
else:
mode = util.get_sys_args_one_line()
# case 2
if mode.upper().startswith('L'):
local_branch()
# case 3
elif mode.upper().startswith('R'):
remote_branch()
else:
util.check_help_message(help_msg)
<file_sep>#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright 2018- <<EMAIL>>
""" translate file encoding """
import sys
import os
from chardet.universaldetector import UniversalDetector
from chardet import detect
sys.path.append('.')
import util
def help_msg():
print("Brief:")
print(" 1. translate [file] from detected encoding to UTF-8 encoding")
print(
" 2. translate [file] from detected encoding to target [encoding]")
print("Usage:")
print(" 1. %s [file]" % util.get_command_name())
print(" 2. %s [file] [encoding]" % util.get_command_name())
print("Try again")
exit(1)
def detect_encoding(file_name):
with open(file_name, 'rb') as f:
rawdata = f.read()
result = detect(rawdata)['encoding']
return result
def convert_encoding(src_file, detect_encoding, target_encoding):
dest_file = "%s.%s" % (src_file, target_encoding)
util.backup_file(dest_file)
try:
with open(src_file, 'r', encoding=detect_encoding) as s, open(
dest_file, 'w', encoding=target_encoding) as d:
text = s.read()
d.write(text)
except UnicodeDecodeError as de:
print('[boostscript] unicode decode exception %s' % (de))
except UnicodeEncodeError as ee:
print('[boostscript] unicode encode exception %s' % (ee))
if __name__ == '__main__':
util.check_help_message(help_msg)
if len(sys.argv) < 2 or len(sys.argv) > 3:
help_msg()
file_name = sys.argv[1]
detect_encoding = detect_encoding(file_name)
target_encoding = 'UTF-8'
if len(sys.argv) == 3:
target_encoding = sys.argv[2].strip()
if target_encoding == detect_encoding:
print('[boostscript] origin and target encoding are the same \"%s\"' %
(target_encoding))
exit(1)
convert_encoding(file_name, detect_encoding, target_encoding)
<file_sep>#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright 2018- <<EMAIL>>
""" validate ipv6 address """
import sys
sys.path.append('.')
import util
def help_msg():
print("Brief:")
print(" check if [ipv6] address is valid")
print("Usage:")
print(" %s [ipv6]" % util.get_command_name())
print("Try again")
exit(1)
if __name__ == '__main__':
util.check_help_message(help_msg)
if len(sys.argv) != 2:
help_msg()
ipaddr = sys.argv[1]
if util.check_valid_ipv6(ipaddr):
print(1)
else:
print(0)
<file_sep>#!/usr/bin/env bash
echo [boostscript] Install BoostScript for Manjaro
# Prepare Environment
touch ~/.bashrc
touch ~/.zshrc
## Software
sudo pacman -Syyu
yes | sudo pacman -S git python pip unzip zip wget bzip2 p7zip the_silver_searcher
sudo pip3 install pyOpenSSL chardet
if [ -d ~/.config ]; then
sudo chmod -R +rwx ~/.config
sudo chown -R $USER ~/.config
fi
# Git Config
git config core.filemode false
# Variable
cd ~/.boostscript/command
chmod +x *
echo "export PATH=\$PATH:~/.boostscript/command" >> ~/.bashrc
echo "export PATH=\$PATH:~/.boostscript/command" >> ~/.zshrc
source ~/.bashrc
source ~/.zshrc
<file_sep>#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright 2018- <<EMAIL>>
""" git push all changes to current branch """
import sys
import os
sys.path.append('.')
import util
def help_msg():
print("Brief:")
print(" 1. git push local commits to remote repository")
print(
" 2. git add and push all changes to remote repository with [comment]"
)
print("Usage:")
print(" 1. %s" % util.get_command_name())
print(" 2. %s [comment]" % util.get_command_name())
print("Try again")
exit(1)
if __name__ == '__main__':
util.check_git_repository()
util.check_help_message(help_msg)
# remote repository count
remote_count = util.get_git_remote_repository_count()
# error: remote repository not exist
if remote_count == 0:
print("[boostscript] remote repository not exist!")
exit(1)
branch = util.get_git_current_branch()
remote_repo = util.get_git_remote_repository()
# case 1
if len(sys.argv) == 1:
util.check_user_confirm("[boostscript] git push to \'%s/%s\', yes? " %
(remote_repo, branch))
os.chdir(util.get_git_root())
os.system("git push %s %s" % (remote_repo, branch))
# case 2
else:
comment = util.get_sys_args_one_line()
util.check_user_confirm(
"[boostscript] git push to \'%s/%s\' with \'%s\', yes? " %
(remote_repo, branch, comment))
os.chdir(util.get_git_root())
os.system("git add -A .")
os.system("git commit -m \"%s\"" % (comment))
os.system("git push %s %s" % (remote_repo, branch))
<file_sep>#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright 2018- <<EMAIL>>
""" git reset to last n commits """
import sys
import os
sys.path.append('.')
import util
def help_msg():
print("Brief:")
print(" 1. git reset to last commit")
print(" 2. git reset to last [n] commit, NOTICE: `%s 1` equals `%s`" %
(util.get_command_name(), util.get_command_name()))
print("Usage:")
print(" 1. %s" % util.get_command_name())
print(" 2. %s [n]" % util.get_command_name())
print("Try again")
if __name__ == '__main__':
util.check_help_message(help_msg)
util.check_git_repository()
branch = util.get_git_current_branch()
n = 1
if len(sys.argv) > 1:
n = int(sys.argv[1])
commit_name = util.get_git_last_commit(n - 1)
util.check_user_confirm(
"[boostscript] git reset to last '%d' commits '%s' on '%s', yes? " %
(n, commit_name, branch))
save_dir = os.getcwd()
os.chdir(util.get_git_root())
os.system("git reset HEAD~%d" % n)
os.system("git commit -m \"[boostscript] reset to last %d commits %s\"" %
(n, commit_name))
if os.path.exists(save_dir):
os.chdir(save_dir)
<file_sep>#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright 2018- <<EMAIL>>
""" git fetch and catch up all commits in current branch """
import sys
import os
sys.path.append('.')
import util
def help_msg():
print("Brief:")
print(" 1. git fetch and pull all commits in current branch")
print(" 2. git fetch and merge all commits from other [branch]")
print("Usage:")
print(" 1. %s" % util.get_command_name())
print(" 2. %s [branch]" % util.get_command_name())
print("Try again")
exit(1)
if __name__ == '__main__':
util.check_git_repository()
util.check_help_message(help_msg)
# remote repository count
remote_count = util.get_git_remote_repository_count()
# error: remote repository not exist
if remote_count == 0:
print("[boostscript] remote repository not exist!")
exit(1)
branch = util.get_git_current_branch()
remote_repo = util.get_git_remote_repository()
# case 1
if len(sys.argv) == 1:
os.chdir(util.get_git_root())
print("[boostscript] git pull from \'%s/%s\'" % (remote_repo, branch))
os.system("git fetch")
os.system("git pull %s %s" % (remote_repo, branch))
# case 2
else:
remote_branch = util.get_sys_args_one_line()
util.check_user_confirm(
"[boostscript] git merge \'%s/%s\'(remote) to \'%s\'(local), yes? "
% (remote_repo, remote_branch, branch))
os.chdir(util.get_git_root())
os.system("git fetch")
os.system("git pull %s %s" % (remote_repo, remote_branch))
<file_sep>#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright 2018- <<EMAIL>>
""" translate uint128 ipv6 string to string """
import sys
sys.path.append('.')
import util
def help_msg():
print("Brief:")
print(" transform ipv6 from [uint128] to ipstr")
print("Usage:")
print(" %s [uint128]" % (util.get_command_name()))
print("Try again")
exit(1)
if __name__ == '__main__':
if len(sys.argv) != 2:
help_msg()
ipaddr = sys.argv[1]
print(util.ipv6_uint128_to_string(ipaddr))
<file_sep>#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright 2018- <<EMAIL>>
""" git create/switch to new/existed branch """
import sys
import os
import re
sys.path.append('.')
import util
def help_msg():
print("Brief:")
print(
" git move to [branch] by creating new if not exist, or switching to it if existed"
)
print("Usage:")
print(" %s [branch]" % util.get_command_name())
print("Try again")
exit(1)
if __name__ == '__main__':
util.check_help_message(help_msg)
util.check_git_repository()
if len(sys.argv) <= 1:
help_msg()
branch = util.get_sys_args_one_line()
git_branches, errstr = util.run("git", "branch")
local_branches = list()
for b in git_branches:
if b.strip().startswith('* '):
local_branches.append(b.strip()[2:])
else:
local_branches.append(b.strip())
if branch not in local_branches:
os.system("git checkout -b %s" % (branch))
else:
os.system("git checkout %s" % (branch))
<file_sep>#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright 2018- <<EMAIL>>
""" ssh manual helper """
def help_msg():
print("Help 1: Generate ssh token for [<EMAIL>].")
print(
" Remove old *id_rsa* and *id_rsa.pub* in ~/.ssh before generation."
)
print(" $ ssh-keygen -t rsa -b 4096 -C '<EMAIL>'")
print(" $ Generating public/private rsa key pair.")
print(
" $ Enter file in which to save the key (~/.ssh/id_rsa) `type ENTER`"
)
print(" $ Enter passphrase (empty for no passphrase) `type ENTER`")
print(" $ Enter same passphrase again: `type ENTER`")
print(" $ chmod 700 -R ~/.ssh")
print(" $ chmod 600 ~/.ssh/authorized_keys")
print(" $ chmod 600 ~/.ssh/id_rsa")
print(" $ chmod 644 ~/.ssh/id_rsa.pub")
print(
"Help 2: Login remote Linux/UNIX via ssh without type username & password."
)
print(" Copy generated *id_rsa.pub* to remote Linux/UNIX")
print(" $ cat id_rsa.pub >> ~/.ssh/authorized_keys")
print(" $ ssh-add ~/.ssh/id_rsa")
print("Try again")
if __name__ == '__main__':
help_msg()
<file_sep>#!/usr/bin/env bash
cd ~/.boostscript
git pull
if [ $(uname) == "Linux" ]; then
if cat /etc/*release | grep ^NAME | grep CentOS 1>/dev/null 2>&1; then
bash ~/.boostscript/install/centos.sh
elif cat /etc/*release | grep ^NAME | grep Red 1>/dev/null 2>&1; then
bash ~/.boostscript/install/redhat.sh
elif cat /etc/*release | grep ^NAME | grep Fedora 1>/dev/null 2>&1; then
bash ~/.boostscript/install/fedora.sh
elif cat /etc/*release | grep ^NAME | grep Ubuntu 1>/dev/null 2>&1; then
bash ~/.boostscript/install/ubuntu.sh
elif cat /etc/*release | grep ^NAME | grep Debian 1>/dev/null 2>&1; then
bash ~/.boostscript/install/debian.sh
elif cat /etc/*release | grep ^NAME | grep Mint 1>/dev/null 2>&1; then
bash ~/.boostscript/install/mint.sh
elif cat /etc/*release | grep ^NAME | grep Knoppix 1>/dev/null 2>&1; then
bash ~/.boostscript/install/kanoppix.sh
elif cat /etc/*release | grep ^NAME | grep Manjaro 1>/dev/null 2>&1; then
bash ~/.boostscript/install/manjaro.sh
else
echo "[boostscript] OS not detected, cannot install"
exit 1;
fi
elif [ $(uname) == "FreeBSD" ]; then
bash ~/.boostscript/install/bsd.sh
elif [ $(uname) == "Darwin" ]; then
bash ~/.boostscript/install/macos.sh
else
echo "[boostscript] please try 'install.bat'"
fi
<file_sep>#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright 2018- <<EMAIL>>
""" get timestamp like '1528122015.41' from now or from datetime string """
import sys
import time
import datetime
sys.path.append('.')
import util
def help_msg():
print("Brief:")
print(
" 1. get timestamp since 1970-01-01 00:00:00(such as '1528122015.410' sec)"
)
print(
" 2. convert local [datetime] string to timestamp, such as '2018-06-04', '2018-06-04 13:21:49.857'"
)
print("Usage:")
print(" 1. %s" % util.get_command_name())
print(" 2. %s [datetime]" % util.get_command_name())
print("Try again")
exit(1)
def get_second_by_date(year, month, day):
return util.number_to_string(
util.date_to_second(datetime.date(year, month, day)))
def get_second_by_datetime(year, month, day, hour, minute, second):
return util.number_to_string(
util.datetime_to_second(
datetime.datetime(year, month, day, hour, minute, second)))
def date_second_impl(date_str):
date_len = len(date_str)
num = [None, None, None, None, None, None, None]
len_max = [4, 2, 2, 2, 2, 2, 999999999]
count = 0
start_pos = None
for i in range(date_len):
if date_str[i].isdigit():
if start_pos is None:
start_pos = i
if (not date_str[i].isdigit()) and (start_pos is not None):
num[count] = int(date_str[start_pos:i])
count += 1
start_pos = None
if (start_pos is not None) and (i - start_pos > len_max[count]):
num[count] = int(date_str[start_pos:start_pos + len_max[count]])
count += 1
start_pos = None
if start_pos is not None:
num[count] = int(date_str[start_pos:])
count += 1
if count == 0:
raise Exception('invalid [datetime]: ' + str(date_str))
elif count == 1:
return get_second_by_date(num[0], 0, 0)
elif count == 2:
return get_second_by_date(num[0], num[1], 0)
elif count == 3:
return get_second_by_date(num[0], num[1], num[2])
elif count == 4:
return get_second_by_datetime(num[0], num[1], num[2], num[3], 0, 0)
elif count == 5:
return get_second_by_datetime(num[0], num[1], num[2], num[3], num[4],
0)
elif count == 6:
return get_second_by_datetime(num[0], num[1], num[2], num[3], num[4],
num[5])
else:
int_part = get_second_by_datetime(num[0], num[1], num[2], num[3],
num[4], num[5])
decimal_part = util.number_to_string(num[6])
return int_part + '.' + decimal_part
if __name__ == '__main__':
util.check_help_message(help_msg)
if len(sys.argv) <= 1:
print(util.number_to_string(time.time()))
else:
print(date_second_impl(util.get_sys_args_one_line()))
<file_sep>#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright 2018- <<EMAIL>>
""" translate ipv4 address string to uint32 """
import sys
import os
import re
sys.path.append('.')
import util
def help_msg():
print("Brief:")
print(" transform ipv4 from [ipstr] to uint32")
print("Usage:")
print(" %s [ipstr]" % util.get_command_name())
print("Try again")
exit(1)
if __name__ == '__main__':
util.check_help_message(help_msg)
if len(sys.argv) != 2:
help_msg()
ipaddr = sys.argv[1]
print(util.ipv4_string_to_uint32(ipaddr))
<file_sep>#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright 2018- <<EMAIL>>
""" list *.[suffix] files in current directory """
import sys
import os
sys.path.append('.')
import util
def help_msg():
print("Brief:")
print(" 1. list all files in current directory")
print(" 2. list *.[suffix] file in current directory")
print("Usage:")
print(" 1. %s" % util.get_command_name())
print(" 2. %s [suffix]" % util.get_command_name())
print("Try again")
exit(1)
def list_suffix(file_list, suffix, rootdir):
suffix = '.%s' % (suffix)
for f in file_list:
assert isinstance(f, str)
if f.startswith('.'):
continue
if f.endswith(suffix):
print('%s' % (os.path.relpath(f, rootdir)))
def list_all(file_list, rootdir):
for f in file_list:
assert isinstance(f, str)
if f.startswith('.'):
continue
print('%s' % (os.path.relpath(f, rootdir)))
if __name__ == '__main__':
util.check_help_message(help_msg)
file_list = util.recursive_list_dir('.')
if len(sys.argv) <= 1:
list_all(file_list, os.getcwd())
else:
suffix = util.trim_quotation(sys.argv[1])
list_suffix(file_list, suffix, os.getcwd())
<file_sep>#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright 2018- <<EMAIL>>
""" replace text of *.[suffix] files in current directory """
import sys
import os
sys.path.append('.')
import util
def help_msg():
print("Brief:")
print(" 1. replace [origin] with [text] of all files in current folder")
print(
" 2. replace [origin] with [text] of *.[suffix] files in current folder"
)
print("Usage:")
print(" 1. %s [origin] [text]" % util.get_command_name())
print(" 2. %s [origin] [text] [suffix]" % util.get_command_name())
print("Try again")
exit(1)
def replace_suffix(file_list, suffix, origin, text):
suffix = '.%s' % (suffix)
for f in file_list:
assert isinstance(f, str)
if f.startswith('.'):
continue
if not f.endswith(suffix):
continue
try:
with open(f, 'r') as fp:
content = fp.read()
fp.close()
with open(f, 'w') as fp:
new_content = content.replace(origin, text)
fp.write(new_content)
except Exception as e:
print("Error! file:%s, exception:%s" % (f, str(e)))
def replace_all(file_list, origin, text):
for f in file_list:
assert isinstance(f, str)
if f.startswith('.'):
continue
try:
with open(f, 'r') as fp:
content = fp.read()
fp.close()
with open(f, 'w') as fp:
new_content = content.replace(origin, text)
fp.write(new_content)
fp.close()
except Exception as e:
print("Error! file:%s, exception:%s" % (f, str(e)))
if __name__ == '__main__':
util.check_help_message(help_msg)
if len(sys.argv) < 3:
help_msg()
if len(sys.argv) > 4:
help_msg()
origin = util.trim_quotation(sys.argv[1])
text = util.trim_quotation(sys.argv[2])
file_list = util.recursive_list_dir('.')
if len(sys.argv) == 3:
replace_all(file_list, origin, text)
else:
suffix = util.trim_quotation(sys.argv[3])
replace_suffix(file_list, suffix, origin, text)
<file_sep>#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright 2018- <<EMAIL>>
""" get datetime like '2018-06-04 13:04:28.821' from now or from timestamp """
import sys
import time
import datetime
sys.path.append('.')
import util
def help_msg():
print("Brief:")
print(" 1. get 'yyyy-MM-dd HH:mm:ss.SSS' datetime")
print(
" 2. convert [timestamp](such as '1528088668.821') to local datetime string in 'yyyy-MM-dd HH:mm:ss.SSS' format"
)
print("Usage:")
print(" 1. %s" % util.get_command_name())
print(" 2. %s [timestamp]" % util.get_command_name())
print("Try again")
exit(1)
def date_string(ts):
dt = datetime.datetime.fromtimestamp(ts)
return dt.strftime('%Y-%m-%d %H:%M:%S.%f')[0:23]
if __name__ == '__main__':
util.check_help_message(help_msg)
if len(sys.argv) <= 1:
print(date_string(time.time()))
else:
print(date_string(float(util.get_sys_args_one_line())))
|
2f9c22573712203a42bc8857b61e7d255bfd2358
|
[
"Markdown",
"Python",
"Shell"
] | 30
|
Python
|
linrongbin16/boostscript
|
07db2511907f9c60bfc02f252b6b86530d58bf7f
|
33f850d1b3380c9b09252e6a22b8f413ea64a723
|
refs/heads/master
|
<file_sep>APP.Name = "HL2 Go"
APP.Author = "Krede"
APP.Icon = "asset://garrysmod/materials/gphone/apps/hlgo.png"
function APP.Run( frame, w, h, ratio )
frame:SetFullScreen( true )
local h = frame.h
GPhone.EnableSelfie( true )
LocalPlayer():EmitSound( "weapons/smg1/switch_burst.wav", 50, math.random(95,105), 1, CHAN_WEAPON )
local c_iron = 0
local IronSightsPos = Vector(-6.43, -8.506, 3.539)
local RunSightsPos = Vector(3.92, -3.586, -2.6)
local RunSightsAng = Vector(-18.879, 39.603, -35.044)
if !IsValid(frame.viewmodel) then
local mdl = ClientsideModel("models/weapons/v_smg1.mdl", RENDERGROUP_OPAQUE)
mdl:SetNoDraw(true)
mdl:ResetSequence( mdl:LookupSequence("draw") )
mdl:SetPlaybackRate( 0.7 )
mdl:SetCycle( 0 )
function mdl:GetPlayerColor()
return Vector(1, 0.5, 0)
end
frame.viewmodel = mdl
frame.f_nextfire = CurTime() + 1.2
end
function frame:Paint( x, y, w, h )
local mat = GPhone.RenderCamera( 50, false,
function(pos, ang, fov)
for k,v in pairs(ents.FindByClass("npc_*")) do
v:SetNoDraw(true)
end
end,
function(pos, ang, fov)
cam.Start3D(pos, ang)
for k,v in pairs(ents.FindByClass("npc_*")) do
v:SetNoDraw(false)
local ent = KleinerRapeModel
if !IsValid(ent) then
local ent = ClientsideModel("models/kleiner.mdl", RENDER_GROUP_OPAQUE_ENTITY)
ent:SetNoDraw( true )
ent:DrawShadow( true )
ent:ResetSequence( ent:LookupSequence("ragdoll") )
ent:SetCycle(0)
KleinerRapeModel = ent
else
ent:SetRenderOrigin( v:GetPos() )
ent:SetRenderAngles( v:GetAngles() )
ent:SetupBones()
ent:FrameAdvance( FrameTime() )
ent:DrawModel()
ent:SetRenderOrigin()
ent:SetRenderAngles()
end
end
cam.End3D()
local vm = self.viewmodel
local ft = FrameTime()
if IsValid(vm) then
cam.Start3D(pos, ang, 60, 0, 0, w, h, 1, 128)
c_iron = Lerp(math.min(ft * 10, 1), c_iron or 0, GPhone.CursorEnabled and 1 or 0)
local pos = pos + IronSightsPos.x * ang:Right() * c_iron + IronSightsPos.y * ang:Forward() * c_iron + IronSightsPos.z * ang:Up() * c_iron
cam.IgnoreZ(true)
render.SetColorModulation( 1, 1, 1 )
vm:SetRenderOrigin( pos - ang:Up() )
vm:SetRenderAngles( ang )
vm:SetupBones()
vm:FrameAdvance( ft )
vm:DrawModel()
cam.IgnoreZ(false)
cam.End3D()
end
end)
surface.SetDrawColor(255, 255, 255, 255)
surface.SetMaterial( mat )
surface.DrawTexturedRect(0, 0, w, h)
local hp = LocalPlayer():Health()
if hp <= 50 then
local p = 1-(hp/50)
surface.SetDrawColor(255, 0, 0, 150 * p)
surface.DrawRect(0, 0, w, h)
end
end
end
function APP.Focus( frame )
GPhone.EnableSelfie( true )
LocalPlayer():EmitSound( "weapons/smg1/switch_burst.wav", 50, math.random(95,105), 1, CHAN_WEAPON )
frame.f_nextfire = CurTime() + 0.5
local vm = frame.viewmodel
if IsValid(vm) then
vm:ResetSequence( vm:LookupSequence("draw") )
vm:SetPlaybackRate( 1 )
vm:SetCycle( 0 )
end
end
function APP.Think( frame )
local x,y = GPhone.GetCursorPos()
if x > 0 and y > 0 and x <= GPhone.Width and y <= GPhone.Height and GPhone.CursorEnabled then
local ct = CurTime()
if LocalPlayer():KeyDown(IN_ATTACK) and (frame.f_nextfire or 0) < ct then
frame.f_nextfire = ct + 0.08
local vm = frame.viewmodel
if IsValid(vm) then
LocalPlayer():EmitSound( "weapons/smg1/smg1_fire1.wav", 50, math.random(95,105), 1, CHAN_WEAPON )
vm:ResetSequence( vm:LookupSequence("fire0"..math.random(1,4)) )
vm:SetPlaybackRate( 1 )
vm:SetCycle( 0 )
end
--[[local bullet = {}
bullet.Num = 1
bullet.Src = LocalPlayer():GetShootPos()
bullet.Dir = LocalPlayer():GetAimVector()
bullet.Spread = Vector( 0, 0, 0 )
bullet.Tracer = 0
bullet.Force = 10
bullet.Damage = 10
bullet.AmmoType = "smg1"
LocalPlayer():FireBullets( bullet )]]
end
end
end
function APP.Stop( frame )
if IsValid(frame.viewmodel) then
frame.viewmodel:Remove()
end
end<file_sep>APP.Name = "Visualizer"
APP.Author = "Krede"
APP.Negative = true
APP.Icon = "asset://garrysmod/materials/gphone/apps/gtunes.png"
function APP.Run( frame, w, h, ratio )
function frame:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h, Color( 50, 50, 50, 255 ) )
end
local scroll = GPnl.AddPanel( frame, "scroll" )
scroll:SetPos( 0, 64 * ratio )
scroll:SetSize( w, h - 64 * ratio )
local space = 12 * ratio
local mar = (64 - 36) * ratio
local enable = GPnl.AddPanel( scroll, "panel" )
enable:SetSize( w, 64 * ratio )
enable:SetPos( 0, space )
function enable:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 60, 60, 150, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 25, 25, 100, 255 ) )
draw.SimpleText("Enable Visualizer", "GPMedium", mar, h/2, Color(255, 255, 255), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
local pad = 8 * ratio
local size = 64 * ratio - pad*2
local toggle = GPnl.AddPanel( enable, "toggle" )
toggle:SetSize( size * 2, size )
toggle:SetPos( w - size * 2 - pad, pad )
toggle:SetToggle( GPhone.GetAppData("enable", false) )
toggle:SetNegative( true )
function toggle:OnChange( bool )
GPhone.SetAppData("enable", bool)
end
space = space + 64 * ratio
local barlabel = GPnl.AddPanel( scroll, "panel" )
barlabel:SetSize( w, 64 * ratio )
barlabel:SetPos( 0, space )
function barlabel:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 60, 60, 150, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 25, 25, 100, 255 ) )
draw.SimpleText("Size", "GPMedium", mar, h/2, Color(255, 255, 255), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
local bar = GPnl.AddPanel( barlabel, "textentry" )
bar:SetSize( size * 2, 64 * ratio )
bar:SetPos( w - size * 2 - pad, 0 )
bar:SetFont( "GPMedium" )
bar:SetForeColor( Color(255, 255, 255) )
bar:SetBackColor( Color(0, 0, 0, 0) )
bar:SetText( GPhone.GetAppData("size", 4) )
bar:SetAlignment( TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER )
function bar:OnEnter( val )
local val = tonumber(val)
if val then
local num = math.Clamp(val, 1, 20)
self:SetText( num )
GPhone.SetAppData("size", num)
end
end
space = space + 64 * ratio
local header = GPnl.AddPanel( frame )
header:SetPos( 0, 0 )
header:SetSize( w, 64 * ratio )
function header:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 60, 60, 150, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 25, 25, 100, 255 ) )
draw.SimpleText("Music Visualizer", "GPTitle", w/2, h/2, Color(230, 230, 230), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
end
hook.Add("GPhonePreRenderTopbar", "GTunesVisualizer", function(w, h)
if !GPhone.GetAppData("enable", false, "visualizer") then return end
local music = GPhone.GetMusic()
if music then
local fft = {}
local mid = math.Round(w / 2)
local frag = GPhone.GetAppData("size", 4, "visualizer")
music.Channel:FFT( fft, FFT_256 )
for k = 1, mid, frag do
local v = fft[math.ceil((k/mid) * #fft)]
if !v then continue end
local val = math.Clamp(math.Round(v * h ^ 2), 0, h)
if val == 0 then continue end
local col = HSVToColor(360 * (k/mid) + 180 * math.sin(RealTime()), 1, 1)
surface.SetDrawColor(col.r, col.g, col.b, 255)
surface.DrawRect(mid + (k-1), 0, frag, val)
surface.SetDrawColor(col.r, col.g, col.b, 255)
surface.DrawRect(mid - (k-1), 0, frag, val)
end
end
end)<file_sep>APP.Name = "StormFox"
APP.Author = "Krede"
APP.Icon = "asset://garrysmod/materials/gphone/apps/stormfox.png"
function APP.Run( frame, w, h, ratio )
function frame:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h, Color( 220, 220, 220, 255 ) )
end
if !StormFox && !StormFox2 then
local header = GPnl.AddPanel( frame )
header:SetPos( 0, 0 )
header:SetSize( w, 64 * ratio )
function header:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("StormFox not found", "GPTitle", w/2, h/2, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
local install = GPnl.AddPanel( frame )
install:SetPos( 32 * ratio, h/2 - 64 * ratio )
install:SetSize( w - 64 * ratio, 128 * ratio )
function install:Paint( x, y, w, h )
draw.RoundedBox( 8, 0, 0, w, h, Color( 150, 150, 150, 255 ) )
draw.SimpleText("Get StormFox", "GPTitle", w/2, h/2, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
function install:OnClick()
gui.OpenURL( "http://steamcommunity.com/sharedfiles/filedetails/?id=1132466603" )
end
else
local scroll = GPnl.AddPanel( frame, "scroll" )
scroll:SetPos( 0, 64 * ratio )
scroll:SetSize( w, h - 64 * ratio )
scroll:SetScrollSpeed( 48 )
local function loadWeather()
scroll:Clear()
local weather = StormFox.GetNetworkData("WeekWeather", {})
local size = 128 * ratio
for k = 1, 7 do
local data = weather[k]
if !data then continue end
local pnl = GPnl.AddPanel( scroll )
pnl:SetPos( 0, 6 * ratio + (k-1)*size )
pnl:SetSize( w, size )
pnl.name = StormFox.GetWeatherType(data.name):GetName()
pnl.mat = StormFox.GetWeatherType(data.name):GetIcon()
if GPhone.GetData("imperial", false) then
if StormFox2 then
pnl.temp = "Temp: "..StormFox2.Temperature.Get(sType = "fahrenheit").."°F"
else
pnl.temp = "Temp: "..math.Round(StormFox.CelsiusToFahrenheit(data.temp), 1).."°F"
end
else
if StormFox2 then
pnl.temp = "Temp: "..StormFox2.Temperature.Get(sType = "celsius").."°C"
else
pnl.temp = "Temp: "..math.Round(data.temp, 1).."°C"
end
end
pnl.wind = "Wind: "..data.wind.." u/s"
function pnl:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText(self.name, "GPTitle", w/2, 54/2, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
draw.SimpleText(self.temp, "GPMedium", w-8, 54/2, Color(70, 70, 70), TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER)
draw.SimpleText(self.wind, "GPMedium", w-8, h/2, Color(70, 70, 70), TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER)
surface.SetDrawColor( 70, 70, 70 )
surface.SetMaterial( self.mat )
surface.DrawTexturedRect( 8, 8, h-16, h-16 )
end
end
end
loadWeather()
local header = GPnl.AddPanel( frame )
header:SetPos( 0, 0 )
header:SetSize( w, 64 * ratio )
function header:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("Weather Forecast", "GPTitle", w/2, h/2, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
local refresh = GPnl.AddPanel( header )
refresh:SetPos( w - 64 * ratio, 0 )
refresh:SetSize( 64 * ratio, 64 * ratio )
function refresh:Paint( x, y, w, h )
surface.SetDrawColor(50, 50, 50)
surface.SetTexture( surface.GetTextureID( "gui/html/refresh" ) )
local ct = CurTime()
if (self.Delay or 0) < ct then
surface.DrawTexturedRect( 0, 0, w, h )
else
local p = (self.Delay - ct)*720
surface.DrawTexturedRectRotated( w/2, h/2, w, h, p )
end
end
function refresh:OnClick()
self.Delay = CurTime() + 0.5
loadWeather()
end
end
end<file_sep>AddCSLuaFile()
SWEP.PrintName = "GPhone"
SWEP.Author = "Krede"
SWEP.Contact = "Discord"
SWEP.Purpose = "It's a phone."
SWEP.Instructions = "Use it like a phone."
if CLIENT then
SWEP.WepSelectIcon = surface.GetTextureID("vgui/hud/phone")
SWEP.BounceWeaponIcon = false
end
SWEP.SwayScale = 0
SWEP.BobScale = 0
SWEP.Spawnable = true
SWEP.Category = "Krede's SWEPs"
SWEP.Primary.ClipSize = -1
SWEP.Primary.DefaultClip = -1
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = "none"
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.HoldType = "slam"
SWEP.ViewModelFOV = 55
SWEP.ViewModel = "models/weapons/c_garry_phone.mdl"
SWEP.WorldModel = "models/nitro/iphone4.mdl"
SWEP.DrawCrosshair = false
SWEP.UseHands = false
SWEP.Bones = {
["ValveBiped.Bip01_R_Forearm"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(12.364, -4.447, -166.75) },
["ValveBiped.Bip01_R_Hand"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(-26.625, 46.612, 148.677) },
["ValveBiped.Bip01_R_Finger4"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(2.838, -8.886, 8.005) },
["ValveBiped.Bip01_R_Finger41"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 2.005, 7.734) },
["ValveBiped.Bip01_R_Finger42"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(-14.054, -2.49, -14.485) },
["ValveBiped.Bip01_R_Finger3"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(-1.554, 0.397, 12.392) },
["ValveBiped.Bip01_R_Finger31"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(4.939, 0.391, 2.486) },
["ValveBiped.Bip01_R_Finger32"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(1.215, 3.562, -15.863) },
["ValveBiped.Bip01_R_Finger2"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(-2.967, 5.788, 0.527) },
["ValveBiped.Bip01_R_Finger22"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, -0.002, -6.613) },
["ValveBiped.Bip01_R_Finger1"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(3.894, 3.219, 0) },
["ValveBiped.Bip01_R_Finger11"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
["ValveBiped.Bip01_R_Finger12"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
["ValveBiped.Bip01_R_Finger0"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(6.468, -2.203, 54.722) },
["ValveBiped.Bip01_R_Finger01"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(-2, 2, 0) },
["ValveBiped.Bip01_R_Finger02"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) }
}
SWEP.LandscapeBones = {
["ValveBiped.Bip01_R_Forearm"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(12.364, -4.447, -166.75) },
["ValveBiped.Bip01_R_Hand"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(-26.625, 46.612, 148.677) },
["ValveBiped.Bip01_R_Finger4"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(-1.838, 0.886, 0) },
["ValveBiped.Bip01_R_Finger41"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(-8, 30.005, 0) },
["ValveBiped.Bip01_R_Finger42"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(44.054, 100.49, 15) },
["ValveBiped.Bip01_R_Finger3"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(-1.554, 30.397, 12.392) },
["ValveBiped.Bip01_R_Finger31"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(4.939, 0.391, 2.486) },
["ValveBiped.Bip01_R_Finger32"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(1.215, 3.562, -15.863) },
["ValveBiped.Bip01_R_Finger2"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(-8.967, 25.788, 0.527) },
["ValveBiped.Bip01_R_Finger22"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, -0.002, -6.613) },
["ValveBiped.Bip01_R_Finger1"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(-19.894, -34.219, 0) },
["ValveBiped.Bip01_R_Finger11"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(20, 50, 0) },
["ValveBiped.Bip01_R_Finger12"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(5, 60, 0) },
["ValveBiped.Bip01_R_Finger0"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(-2.468, -3.203, 54.722) },
["ValveBiped.Bip01_R_Finger01"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(-26, 10, 0) },
["ValveBiped.Bip01_R_Finger02"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(-10, 40, 40) }
}
SWEP.SightsPos = Vector(-2.28, -10.3, 2.37)
SWEP.LandscapeSightsPos = Vector(-0.98, -10.4, 3.11)
SWEP.SightsAng = Vector(0, 3, 0.25)
SWEP.CallSightsPos = Vector(-10.461, -12.421, 0.55)
SWEP.CallSightsAng = Vector(0, -90, 5)
SWEP.PhoneInfo = {
model = "models/nitro/iphone4.mdl",
pos = Vector(1.5, 1.774, -1.912),
ang = Angle(-2.198, -90.477, 180),
scale = Vector(1, 1, 1),
bone = "ValveBiped.Bip01_MobilePhone"
}
SWEP.WorldModelInfo = {
pos = Vector(2,-0.4,0.4),
ang = Angle(20,150,5)
}
local function parentPos( p )
if p then
local px,py = parentPos( p.parent )
local x,y = p.x,p.y
return x + px,y + py
else
return 0,0
end
end
-- Movement
local c_jump = 0
local c_move = 0
local c_sight = 0
local c_iron = 0
local c_deploytime = 0
local c_deployed = false
function SWEP:GetViewModelPosition(pos, ang)
local ct,ft = CurTime(),FrameTime()
local iftp = game.SinglePlayer() or IsFirstTimePredicted()
if c_deploytime > ct and c_deployed then
local p = (c_deploytime - ct) / 0.8
ang:RotateAroundAxis(ang:Right(), -(8 * p)^2)
ang:RotateAroundAxis(ang:Up(), -(2 * p)^2)
ang:RotateAroundAxis(ang:Forward(), -(8 * p)^2)
elseif !c_deployed then
ang:RotateAroundAxis(ang:Right(), -64)
ang:RotateAroundAxis(ang:Up(), -4)
ang:RotateAroundAxis(ang:Forward(), -64)
end
local pos,ang = self:Movement(pos, ang, ct, ft, iftp)
local pos,ang = self:Zoom(pos, ang, ct, ft, iftp)
return pos,ang
end
function SWEP:Movement(pos, ang, ct, ft, iftp)
if !IsValid(self.Owner) then return pos,ang end
local cv = GetConVar("gphone_bob")
local bob = cv and cv:GetFloat() or 1
if bob == 0 then return pos,ang end
local move = Vector(self.Owner:GetVelocity().x, self.Owner:GetVelocity().y, 0)
local movement = move:LengthSqr()
local movepercent = math.Clamp(movement / self.Owner:GetRunSpeed() ^ 2, 0, 1)
local vel = move:GetNormalized()
local rd = self.Owner:GetRight():Dot( vel )
local fd = (self.Owner:GetForward():Dot( vel ) + 1)/2
if iftp then
local ft8 = math.min(ft * 8, 1)
c_move = Lerp(ft8, c_move or 0, self.Owner:OnGround() and movepercent or 0)
c_sight = Lerp(ft8, c_sight or 0, GPhone.CursorEnabled and 0.1 or 1)
c_jump = Lerp(ft8, c_jump or 0, self.Owner:GetMoveType() == MOVETYPE_NOCLIP and 0 or math.Clamp(self.Owner:GetVelocity().z / 120, -1.5, 1))
end
pos = pos + ang:Up() * 0.75 * c_jump * c_sight
ang.p = ang.p + (c_jump or 0) * 3* c_sight
if c_move > 0 then
local p = c_move * c_sight * bob
pos = pos - ang:Forward() * c_move * c_sight * fd - ang:Up() * 0.75 * c_move * c_sight + ang:Right() * 0.5 * c_move * c_sight
ang.y = ang.y + math.sin(ct * 8.4) * 1.2 * p
ang.p = ang.p + math.sin(ct * 16.8) * 0.8 * p
ang.r = ang.r + math.cos(ct * 8.4) * 0.3 * p
end
local p = (1 - c_move) * c_sight * bob
ang.p = ang.p + math.sin(ct * 0.6) * 1 * p
ang.y = ang.y + math.sin(ct * 1.2) * 0.5 * p
ang.r = ang.r + math.sin(ct * 1.8) * 0.25 * p
return pos,ang
end
function SWEP:Zoom(pos, ang, ct, ft, iftp)
if iftp then
c_iron = Lerp(math.min(ft * 6, 1), c_iron or 0, GPhone.CursorEnabled and 1 or 0)
end
local cv = GetConVar("gphone_focus")
local focus = cv and cv:GetFloat() or 0
local offset = GPhone.Landscape and self.LandscapeSightsPos or self.SightsPos
ang = ang * 1
if self.SightsAng then
ang:RotateAroundAxis(ang:Right(), self.SightsAng.x * c_iron)
ang:RotateAroundAxis(ang:Up(), self.SightsAng.y * c_iron)
ang:RotateAroundAxis(ang:Forward(), self.SightsAng.z * c_iron)
end
pos = pos + (offset.x + focus*0.052) * ang:Right() * c_iron
pos = pos + (offset.y + focus) * ang:Forward() * c_iron
pos = pos + offset.z * ang:Up() * c_iron
return pos, ang
end
function SWEP:PrimaryAttack()
return false
end
function SWEP:SecondaryAttack()
return false
end
function SWEP:Reload()
if CLIENT then return end
local ct = SysTime()
if (self.b_lastreload or 0) + 0.5 < ct then
self.b_lastreload = ct
net.Start("GPhone_Rotate")
net.Send(self.Owner)
end
return false
end
local function clickFrame( frame, x, y, double )
local button = nil
local function clickChildren( pnl )
local px,py = parentPos( pnl )
local bx,by,bw,bh = px,py,pnl.w,pnl.h
if x < bx or x > bx + bw or y < by or y > by + bh or !pnl.visible then return end
button = pnl
for _,child in pairs(pnl.children) do
clickChildren( child )
end
end
clickChildren( frame )
if button then
if button.OnClick then
GPhone.DebugFunction( button.OnClick, button, double or false )
return true
end
end
return false
end
local function getHoverHome( wep, x, y )
local home = wep.ScreenInfo.home
return x >= home.x and x <= home.x + home.size and y >= home.y and y <= home.y + home.size
end
local function getHoverApp( x, y )
for _,data in pairs(GPhone.GetPage()) do
local posx,posy,size,id = data.x,data.y,data.size,data.app
if x > posx and x < posx + size and y > posy and y < posy + size then
return id
end
end
return false
end
function SWEP:Think()
local ct = CurTime()
self:NextThink( ct )
if SERVER then return true end
if !IsValid(self.Owner) or !game.SinglePlayer() and !IsFirstTimePredicted() then return true end
local st = SysTime()
local vm = self.Owner:GetViewModel()
if IsValid(vm) then
local bone_id = vm:LookupBone("ValveBiped.Bip01_MobilePhone")
if bone_id then
vm:ManipulateBoneScale(bone_id, Vector(0.01, 0.01, 0.01))
end
local bones = GPhone.Landscape and self.LandscapeBones or self.Bones
for bone,data in pairs(bones) do
local bone_id = vm:LookupBone(bone)
if bone_id then
vm:ManipulateBoneScale(bone_id, data.scale)
vm:ManipulateBonePosition(bone_id, data.pos)
vm:ManipulateBoneAngles(bone_id, data.angle)
end
end
end
if self.ToggleDelay < st and input.IsMouseDown(MOUSE_RIGHT) and !vgui.CursorVisible() then
self.ToggleDelay = st + 0.3
GPhone.CursorEnabled = !GPhone.CursorEnabled
end
if self.Owner:WaterLevel() > 2 then
return true
end
if GPhone.CurrentFrame then
local function animChildren( pnl )
local anim = pnl.f_anim
if anim then
local delta = math.Clamp((ct - anim.start) / anim.max, 0, 1)
GPhone.DebugFunction( anim.func, pnl, delta, anim.pos.x, anim.pos.y )
if delta >= 1 then
if anim.stop then
GPhone.DebugFunction( anim.stop, pnl )
end
pnl.f_anim = nil
end
end
for _,child in pairs(pnl.children) do
animChildren( child )
end
end
animChildren( GPhone.CurrentFrame )
if GPhone.CurrentApp and GPhone.CurrentApp != "" then
local app = GPhone.GetApp( GPhone.CurrentApp )
if app.Think then
GPhone.DebugFunction( app.Think, GPhone.CurrentFrame, GPhone.Width, GPhone.Height, GPhone.Resolution )
end
end
end
if GPhone.CursorEnabled and !vgui.CursorVisible() or g_VR and g_VR.active then
local cv = GetConVar("gphone_holdtime")
local rx,ry = GPhone.CursorPos.x,GPhone.CursorPos.y
local x,y = GPhone.GetCursorPos()
local ls = GPhone.Landscape
local leftDown = GPhone.TriggerDown()
if leftDown and !self.b_leftdown then -- Mouse down
self.b_leftdown = true
self.b_override = nil
self.b_dragging = nil
self.b_lefthold = st
local quick = self.ScreenInfo.quickmenu
local ratio = GPhone.Resolution
local size = quick.size
if !ls and self.b_quickopen then
if y >= GPhone.Height - size and y <= GPhone.Height - size + 30 * ratio then -- Close Control center
self.b_quickopen = nil
self.b_quickhold = true
end
elseif !ls and ry >= quick.y and ry <= quick.y + quick.offset then -- Open Control center
self.b_quickhold = true
self.b_quickopen = nil
end
elseif ( self.b_lefthold or st ) < st - (cv and cv:GetFloat() or 0.4) and !GPhone.AppScreen.Enabled then -- Mouse hold
self.b_lefthold = nil
if !ls and (self.b_quickopen or self.b_quickhold) then return end -- Control center overrides doubleclick and others
if getHoverHome(self, rx, ry) then -- Hold home button
self.b_override = true
GPhone.AppScreen.Enabled = true
GPhone.AppScreen.Scroll = 0
if GPhone.CurrentApp then -- Change focused window
local space = 0
for appid,_ in pairs(GPhone.Panels) do
if appid == GPhone.CurrentApp then
GPhone.AppScreen.Scroll = space
break
end
space = space - 1
end
GPhone.AppThumbnail( GPhone.CurrentApp )
GPhone.FocusHome()
end
elseif GPhone.CurrentFrame then -- Double-clicking in app
clickFrame( GPhone.CurrentFrame, x, y, true )
self.b_override = true
self.b_downtime = ct + 0.25
self.cursor_lastx = x
self.cursor_lasty = y
end
elseif !leftDown and self.b_leftdown then -- Mouse release
self.b_leftdown = nil
self.b_lefthold = nil
if !ls then
if self.b_quickhold then -- Control center held down
self.b_quickhold = nil
self.b_quickopen = y < GPhone.Height * 0.8
return
elseif self.b_quickopen then -- Control center clicking
if getHoverHome(self, rx, ry) then
self.b_quickopen = nil
self.b_quickhold = nil
elseif y < GPhone.Height - self.ScreenInfo.quickmenu.size then
self.b_quickopen = nil
self.b_quickhold = nil
self.b_downtime = ct + 0.25
self.cursor_lastx = x
self.cursor_lasty = y
else
clickFrame( self.QuickMenu, x, y )
self.b_downtime = ct + 0.25
self.cursor_lastx = x
self.cursor_lasty = y
end
return
end
end
if self.b_override then return end
self.b_downtime = ct + 0.25
self.cursor_lastx = x
self.cursor_lasty = y
if GPhone.GetInputText() then -- Close text input
GPhone.CloseInput()
self.b_downtime = 0
elseif GPhone.AppScreen.Enabled then -- Inside app screen
local appscr = GPhone.AppScreen
local space,scale = 0,appscr.Scale
local w,h = GPhone.Width*scale,(GPhone.Height - GPhone.Desk.Offset)*scale
for appid,frame in pairs(GPhone.Panels) do
local px,py = GPhone.Width/2 - w/2 + (w + appscr.Spacing) * (space + appscr.Scroll), GPhone.Height/2 - h/2
if x > px and x < px + w and y > py and y < py + h then
GPhone.AppScreen.Enabled = false
GPhone.FocusApp( appid )
return
elseif x > px and x < px + w and y > (py - appscr.Offset * scale) and y < py then
GPhone.StopApp( appid )
local max = -(table.Count(GPhone.Panels) - 1)
if appscr.Scroll < max then
appscr.Scroll = max
end
if table.Count(GPhone.Panels) > 0 then return end
end
space = space + 1
end
GPhone.AppScreen.Enabled = false
GPhone.FocusHome()
elseif getHoverHome(self, rx, ry) then -- Home button pressed
if GPhone.CurrentApp then
GPhone.AppThumbnail( GPhone.CurrentApp )
end
GPhone.FocusHome()
elseif GPhone.CurrentFrame then -- Clicking inside an app
clickFrame( GPhone.CurrentFrame, x, y, false )
end
end
end
return true
end
function SWEP:Initialize()
self:SetWeaponHoldType(self.HoldType)
self:SetHoldType(self.HoldType)
self.ToggleDelay = SysTime() + 0.3
GPLoadApps()
if CLIENT then
self.ViewModelFlip = GetConVar("gphone_lefthand"):GetBool()
GPhone.LoadImages()
net.Start("GPhone_Case")
net.WriteString(GetConVar("gphone_case"):GetString())
net.SendToServer()
local ratio = GPhone.Resolution
local hand = 15 * ratio
local space = 30 * ratio
local divide = 4 * ratio
local music = 44 * ratio
local size = 80 * ratio
local slider = 8 * ratio
local quick = self.ScreenInfo.quickmenu
local offset = hand * ratio
self.QuickMenu = GPnl.AddPanel()
self.QuickMenu:SetPos( 0, GPhone.Height - quick.size )
self.QuickMenu:SetSize( GPhone.Width, quick.size )
function self.QuickMenu:Paint( x, y, w, h )
local blur = GetConVar("gphone_blur")
local alpha = blur and blur:GetBool() and 80 or 150
draw.RoundedBox( 0, 0, 0, w, h, Color( 190, 190, 190, alpha ) )
end
local handle = GPnl.AddPanel( self.QuickMenu )
handle:SetPos( GPhone.Width/2 - 30 * ratio, offset )
handle:SetSize( 60 * ratio, hand )
function handle:Paint( x, y, w, h )
draw.RoundedBox(h/2, 0, 0, w, h, Color(60, 60, 60))
end
local offset = offset + hand * 2
local divider = GPnl.AddPanel( self.QuickMenu )
divider:SetPos( 0, offset )
divider:SetSize( GPhone.Width, divide )
function divider:Paint( x, y, w, h )
surface.SetDrawColor(50, 50, 50, 200)
surface.DrawRect(0, 0, w, h)
end
local offset = offset + divide + space
local dull = GPnl.AddPanel( self.QuickMenu )
dull:SetPos( GPhone.Width * 0.05, offset + slider/2 - music/2 )
dull:SetSize( music, music )
function dull:Paint( x, y, w, h )
local size = w * 0.7
local pad = w * 0.15
surface.SetDrawColor(70, 70, 70)
surface.SetTexture( surface.GetTextureID("gphone/brightness") )
surface.DrawTexturedRect( pad, pad, size, size )
end
function dull:OnClick()
RunConsoleCommand("gphone_brightness", 0)
end
local brightness = GPnl.AddPanel( self.QuickMenu )
brightness:SetPos( GPhone.Width * 0.15, offset )
brightness:SetSize( GPhone.Width * 0.7, slider )
function brightness:Paint( x, y, w, h )
local brightness = GetConVar("gphone_brightness"):GetFloat()
draw.RoundedBox(h/2, 0, 0, w, h, Color(90, 90, 90))
draw.RoundedBox(h/2, 0, 0, w * brightness, h, Color(255, 255, 255))
end
function brightness:OnClick()
local x = GPhone.GetCursorPos()
local w = self:GetSize()
local px = self:GetPos()
if x >= px and x <= px + w then
local p = math.Round((x - px) / w, 2)
RunConsoleCommand("gphone_brightness", p)
end
end
local bright = GPnl.AddPanel( self.QuickMenu )
bright:SetPos( GPhone.Width * 0.95 - music, offset + slider/2 - music/2 )
bright:SetSize( music, music )
function bright:Paint( x, y, w, h )
surface.SetDrawColor(70, 70, 70)
surface.SetTexture( surface.GetTextureID("gphone/brightness") )
surface.DrawTexturedRect( 0, 0, w, h )
end
function bright:OnClick()
RunConsoleCommand("gphone_brightness", 1)
end
local offset = offset + divide + space
local divider2 = GPnl.AddPanel( self.QuickMenu )
divider2:SetPos( 0, offset )
divider2:SetSize( GPhone.Width, divide )
function divider2:Paint( x, y, w, h )
surface.SetDrawColor(50, 50, 50, 200)
surface.DrawRect(0, 0, w, h)
end
local offset = offset + divide + space
local title = GPnl.AddPanel( self.QuickMenu )
title:SetPos( 0, offset )
title:SetSize( GPhone.Width, 42 * ratio )
function title:Paint( x, y, w, h )
local stream = GPhone.GetMusic()
if stream and stream.URL then
surface.SetFont("GPTitle")
local size = surface.GetTextSize(stream.URL)
draw.SimpleText(stream.URL, "GPTitle", w/2 + (size/2 - w/2 + 4 * ratio) * math.sin(RealTime()), h/2, Color(60,60,60), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
end
local offset = offset + 42 * ratio + space
local play = GPnl.AddPanel( self.QuickMenu )
play:SetPos( GPhone.Width/2 - music/2, offset )
play:SetSize( music, music )
function play:Paint( x, y, w, h )
local music = GPhone.GetMusic()
if music and music.Playing then
surface.SetDrawColor(255, 255, 255)
surface.SetTexture( surface.GetTextureID( "gphone/pause" ) )
surface.DrawTexturedRect( 0, 0, w, h )
else
if music then
surface.SetDrawColor(255, 255, 255)
else
surface.SetDrawColor(90, 90, 90)
end
surface.SetTexture( surface.GetTextureID( "gphone/play" ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
end
function play:OnClick()
GPhone.ToggleMusic()
end
local stop = GPnl.AddPanel( self.QuickMenu )
stop:SetPos( GPhone.Width*0.3 - music/2, offset )
stop:SetSize( music, music )
function stop:Paint( x, y, w, h )
local music = GPhone.GetMusic()
if music then
surface.SetDrawColor(255, 255, 255)
else
surface.SetDrawColor(90, 90, 90)
end
surface.SetTexture( surface.GetTextureID( "gphone/stop" ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
function stop:OnClick()
GPhone.StopMusic()
end
local offset = offset + space + music
local mute = GPnl.AddPanel( self.QuickMenu )
mute:SetPos( GPhone.Width * 0.05, offset + slider/2 - music/2 )
mute:SetSize( music, music )
function mute:Paint( x, y, w, h )
surface.SetDrawColor(70, 70, 70)
surface.SetTexture( surface.GetTextureID("gphone/sound_mute") )
surface.DrawTexturedRect( 0, 0, w, h )
end
function mute:OnClick()
GPhone.ChangeVolume( 0 )
end
local volume = GPnl.AddPanel( self.QuickMenu )
volume:SetPos( GPhone.Width * 0.15, offset )
volume:SetSize( GPhone.Width * 0.7, slider )
function volume:Paint( x, y, w, h )
local vol = GetConVar("gphone_volume")
draw.RoundedBox(h/2, 0, 0, w, h, Color(90, 90, 90))
draw.RoundedBox(h/2, 0, 0, w * (vol and vol:GetFloat() or 1), h, Color(255, 255, 255))
end
function volume:OnClick()
local x = GPhone.GetCursorPos()
local w = self:GetSize()
local px = self:GetPos()
if x >= px and x <= px + w then
local p = (x - px) / w
GPhone.ChangeVolume( p )
end
end
local full = GPnl.AddPanel( self.QuickMenu )
full:SetPos( GPhone.Width * 0.95 - music, offset + slider/2 - music/2 )
full:SetSize( music, music )
function full:Paint( x, y, w, h )
surface.SetDrawColor(70, 70, 70)
surface.SetTexture( surface.GetTextureID("gphone/sound_full") )
surface.DrawTexturedRect( 0, 0, w, h )
end
function full:OnClick()
GPhone.ChangeVolume( 1 )
end
local offset = offset + space + slider
local divider3 = GPnl.AddPanel( self.QuickMenu )
divider3:SetPos( 0, offset )
divider3:SetSize( GPhone.Width, divide )
function divider3:Paint( x, y, w, h )
surface.SetDrawColor(50, 50, 50, 200)
surface.DrawRect(0, 0, w, h)
end
local offset = offset + divide + space
local wifi = GPnl.AddPanel( self.QuickMenu )
wifi:SetPos( GPhone.Width/2 - size/2, offset )
wifi:SetSize( size, size )
wifi.outer = 4 * ratio
wifi.inner = 12 * ratio
function wifi:Paint( x, y, w, h )
local col = self.b_toggled and 255 or 90
draw.RoundedBox(h/4, 0, 0, w, h, Color(col, col, col))
draw.RoundedBox(h/4, self.outer/2, self.outer/2, w - self.outer, h - self.outer, Color(190, 190, 190))
surface.SetDrawColor(col, col, col)
surface.SetTexture( surface.GetTextureID( "gphone/wifi_3" ) )
surface.DrawTexturedRect( self.inner/2, self.inner/2, w - self.inner, h - self.inner )
end
function wifi:OnClick()
self.b_toggled = !self.b_toggled
end
local flash = GPnl.AddPanel( self.QuickMenu )
flash:SetPos( space, offset )
flash:SetSize( size, size )
flash.outer = 4 * ratio
flash.inner = 12 * ratio
function flash:Paint( x, y, w, h )
local col = LocalPlayer():FlashlightIsOn() and 255 or 90
draw.RoundedBox(h/4, 0, 0, w, h, Color(col, col, col))
draw.RoundedBox(h/4, self.outer/2, self.outer/2, w - self.outer, h - self.outer, Color(190, 190, 190))
surface.SetDrawColor(col, col, col)
surface.SetTexture( surface.GetTextureID( "gphone/flashlight" ) )
surface.DrawTexturedRect( self.inner/2, self.inner/2, w - self.inner, h - self.inner )
end
function flash:OnClick()
RunConsoleCommand("impulse", "100")
end
end
end
function SWEP:Deploy()
if CLIENT then
if IsFirstTimePredicted() then
c_deploytime = CurTime() + 0.8
c_deployed = true
if g_VR and g_VR.active then
net.Start("GPhone_VR")
net.SendToServer()
end
end
elseif game.SinglePlayer() then
net.Start("GPhone_Equip")
net.Send(self.Owner)
end
return true
end
net.Receive("GPhone_Equip", function(len)
if g_VR and g_VR.active then
net.Start("GPhone_VR")
net.SendToServer()
end
c_deploytime = CurTime() + 0.8
c_deployed = true
end)
function SWEP:Holster( wep )
c_deployed = false
if CLIENT and IsValid(self.Owner) then
GPhone.CursorEnabled = false
local vm = self.Owner:GetViewModel()
if IsValid(vm) then
for bone = 0, vm:GetBoneCount() do
vm:ManipulateBoneScale(bone, Vector(1, 1, 1))
vm:ManipulateBonePosition(bone, Vector(0,0,0))
vm:ManipulateBoneAngles(bone, Angle(0,0,0))
end
end
timer.Simple(0.1, function()
if IsValid(vm) then
for bone = 0, vm:GetBoneCount() do
vm:ManipulateBoneScale(bone, Vector(1, 1, 1))
vm:ManipulateBonePosition(bone, Vector(0,0,0))
vm:ManipulateBoneAngles(bone, Angle(0,0,0))
end
end
end)
end
return true
end
function SWEP:OnRemove()
if CLIENT then
if IsValid(self.HandModel) then
self.HandModel:Remove()
end
if IsValid(self.PhoneModel) then
self.PhoneModel:Remove()
end
GPhone.CursorEnabled = false
end
self:Holster()
end
if SERVER then return end -- Stop the server from here on
local dotemat = Material("gphone/dot_empty")
local dotfmat = Material("gphone/dot_full")
local blurmat = Material("pp/blurscreen")
local screenlight = 1
-- Test VR stuff
if g_VR then
g_VR.viewModelInfo = g_VR.viewModelInfo or {}
g_VR.viewModelInfo.gmod_gphone = {
offsetPos = Vector(0, 0, 2.5),
offsetAng = Angle(0, 0, 0),
}
hook.Add("VRUtilEventInput", "GPhoneVRInput", function(action, press)
local wep = LocalPlayer():GetActiveWeapon()
if !IsValid(wep) or wep:GetClass() != "gmod_gphone" then return end
if action == "boolean_primaryfire" then
wep.b_triggerdown = press
end
end)
hook.Add("VRUtilEventTracking", "GPhoneVRTracking", function()
local wep = LocalPlayer():GetActiveWeapon()
if !IsValid(wep) or wep:GetClass() != "gmod_gphone" then return end
if !g_VR.active then return end
if !g_VR.tracking.pose_lefthand then return end
local origin = g_VR.origin
local lhpos = g_VR.tracking.pose_lefthand.pos - origin
local lhang = g_VR.tracking.pose_lefthand.ang
local lhfwd = lhang:Forward()
local pos,ang = wep:GetPos(),wep:GetAngles()
pos = pos + ang:Forward() * wep.ScreenInfo.pos.x + ang:Right() * wep.ScreenInfo.pos.y + ang:Up() * wep.ScreenInfo.pos.z
ang:RotateAroundAxis(ang:Up(), wep.ScreenInfo.ang.y)
ang:RotateAroundAxis(ang:Right(), wep.ScreenInfo.ang.p)
ang:RotateAroundAxis(ang:Forward(), wep.ScreenInfo.ang.r)
local hit = util.IntersectRayWithPlane(lhpos, lhfwd, pos, ang:Up())
if hit then
local hitLocal = wep:WorldToLocal(hit)
local cursorX = hitLocal.y * 500 + 560
local cursorY = -hitLocal.z * 1000 / 2 + 830
GPhone.CursorPos.x = cursorX
GPhone.CursorPos.y = cursorY
--debugoverlay.Sphere(wep:GetPos() + wep:GetAngles():Forward() * wep.ScreenInfo.pos.x, 0.05, 0.1, Color(255, 255, 255), true)
--debugoverlay.Sphere(hit, 0.05, 0.1, Color(255, 255, 255), true)
end
end)
end
SWEP.ScreenInfo = {
pos = Vector(0.25, 1.125, 1.68),
ang = Angle(0, 90, 90),
size = 0.002,
bone = "ValveBiped.Bip01_MobilePhone",
home = {
x = 492,
y = 1792,
size = 144
},
quickmenu = {
y = 1660,
offset = 60,
size = 479 * GPhone.Resolution
},
draw = function( wep, w, h, ratio )
local cv = GetConVar("gphone_showbounds")
local thumb = GetConVar("gphone_thumbnail")
if GPhone.AppScreen and GPhone.AppScreen.Enabled then
hook.Run("GPhonePreRenderBackground", w, h)
local mat = GPhone.BackgroundMat
if mat and !mat:IsError() then
local rw,rh = mat:GetFloat("$realwidth") or mat:Width(), mat:GetFloat("$realheight") or mat:Height()
local rt = rw / rh
surface.SetDrawColor(255, 255, 255, 255)
surface.SetMaterial( mat )
if GPhone.Landscape then
local s = w / rt
surface.DrawTexturedRect(0, h/2 - s/2, w, s)
else
local s = h * rt
surface.DrawTexturedRect(w/2 - s/2, 0, s, h)
end
end
hook.Run("GPhonePostRenderBackground", w, h)
local blur = GetConVar("gphone_blur")
if blur and blur:GetBool() then
render.BlurRenderTarget(render.GetRenderTarget(), 6, 4, 8)
end
local appscr = GPhone.AppScreen
local space,scale = 0,appscr.Scale
local offset = appscr.Offset * scale
local w,h = GPhone.Width*scale,(GPhone.Height - GPhone.Desk.Offset)*scale
for appid,frame in pairs(GPhone.Panels) do
local app = GPhone.GetApp( appid )
if !app then continue end
local x,y = GPhone.Width/2 - w/2 + (w + appscr.Spacing) * (space + appscr.Scroll), GPhone.Height/2 - h/2
space = space + 1
if x + w < 0 or x > GPhone.Width then continue end
surface.SetDrawColor(0, 0, 0, 200)
surface.DrawRect(x, y - offset, w, offset + h)
surface.SetDrawColor(255, 255, 255)
surface.SetTexture( surface.GetTextureID( "gui/html/stop" ) )
surface.DrawTexturedRect( x + w/2 - offset/2, y - offset, offset, offset )
local mat = GPhone.GetThumbnail( appid )
if thumb and thumb:GetBool() and mat then
surface.SetDrawColor(255, 255, 255, 255)
surface.SetMaterial( mat )
surface.DrawTexturedRect(x, y, w, h)
else
surface.DrawRect(x, y, w, h)
end
if cv and cv:GetBool() then
surface.SetDrawColor( Color( 255, 0, 0, 255 ) )
surface.DrawOutlinedRect( x, y, w, h )
surface.DrawOutlinedRect( x, y - offset, w, offset )
end
local size = 64 * ratio
surface.SetDrawColor(255, 255, 255, 255)
surface.SetMaterial( GPhone.GetImage( app.Icon ) )
surface.DrawTexturedRect(x + w/2 - size/2, y + h + appscr.Spacing, size, size)
draw.SimpleText(app.Name, "GPAppName5", x + w/2 + 2, y + h + appscr.Spacing + size + 2, Color(0,0,0), TEXT_ALIGN_CENTER)
draw.SimpleText(app.Name, "GPAppName5", x + w/2, y + h + appscr.Spacing + size, Color(255,255,255), TEXT_ALIGN_CENTER)
end
elseif GPhone.CurrentFrame then
local frame = GPhone.CurrentFrame
local oldw,oldh = ScrW(),ScrH()
local exclude = {}
local function drawChildren( pnl )
if pnl.children then
for _,child in pairs(pnl.children) do
if !child.visible then continue end
if exclude[child] then
GPhone.CurrentFrame = nil
local name = " "
if GPhone.CurrentApp then
local app = GPhone.GetApp(GPhone.CurrentApp)
if app and app.Name then
name = " '"..app.Name.."' "
else
name = " '"..GPhone.CurrentApp.."' "
end
GPhone.Panels[GPhone.CurrentApp] = nil
end
GPhone.Debug("[ERROR] App"..name.."stuck in infinite loop\n 1. "..tostring(child).." - App terminated\n", false, true)
GPhone.FocusHome()
break
end
if child.Paint then
local px,py = parentPos( child.parent )
local max,may = GPhone.Width*0.016 + math.max(px + child.x, 0), GPhone.Height*0.016 + math.max(py + child.y, 0)
local mix,miy = math.min(GPhone.Width*0.016 + px + child.x + child.w, GPhone.Width*1.032), math.min(GPhone.Height*0.016 + py + child.y + child.h, GPhone.Height*1.032)
if mix < 0 or miy < 0 or max > GPhone.Width*1.032 or may > GPhone.Height*1.032 then continue end
render.SetViewPort(max, may, oldw, oldh)
render.SetScissorRect(max, may, mix, miy, true)
GPhone.DebugFunction( child.Paint, child, px + child.x, py + child.y, child.w, child.h )
if cv and cv:GetBool() then
surface.SetDrawColor( Color( 255, 0, 0, 255 ) )
surface.DrawOutlinedRect( 0, 0, child.w, child.h )
end
render.SetScissorRect(0, 0, 0, 0, false)
end
exclude[child] = true
drawChildren( child )
end
end
end
if frame.Paint then
local offset = GPhone.Height*0.016 + (frame.b_fullscreen and 0 or GPhone.Desk.Offset)
render.SetViewPort(GPhone.Width*0.016, offset, oldw, oldh)
GPhone.DebugFunction( frame.Paint, frame, frame.x, frame.y, frame.w, frame.h )
if cv and cv:GetBool() then
surface.SetDrawColor( Color( 255, 0, 0, 255 ) )
surface.DrawOutlinedRect( 0, 0, frame.w, frame.h )
end
end
drawChildren( frame )
render.SetViewPort(GPhone.Width*0.016, GPhone.Height*0.016, oldw, oldh)
end
if !GPhone.Landscape and (wep.b_quickhold or wep.b_quickopen) then
local frame = wep.QuickMenu
if frame then
local oldw,oldh = ScrW(),ScrH()
local height = frame.h
local max = GPhone.Height - height
local offset = max
if wep.b_quickhold then
local _,y = GPhone.GetCursorPos()
offset = math.max(max, y)
end
local blur = GetConVar("gphone_blur")
if blur and blur:GetBool() and offset < GPhone.Height then
local p = 1-math.Clamp((offset - GPhone.Height + height)/height, 0, 1)
render.BlurRenderTarget( render.GetRenderTarget(), p*8, p*4, math.Round(p*8) )
end
local function drawChildren( pnl )
if pnl.children then
for _,child in pairs(pnl.children) do
if child.Paint then
render.SetViewPort(GPhone.Width*0.016 + child.x, GPhone.Height*0.016 + offset + child.y, oldw, oldh)
GPhone.DebugFunction( child.Paint, child, child.x, offset + child.y, child.w, child.h )
if cv and cv:GetBool() then
surface.SetDrawColor( Color( 255, 0, 0, 255 ) )
surface.DrawOutlinedRect( 0, 0, child.w, child.h )
end
end
drawChildren( child )
end
end
end
if frame.Paint then
render.SetViewPort(GPhone.Width*0.016, GPhone.Height*0.016 + offset, oldw, oldh)
GPhone.DebugFunction( frame.Paint, frame, frame.x, frame.y, frame.w, frame.h )
end
drawChildren( frame )
render.SetViewPort(GPhone.Width*0.016, GPhone.Height*0.016, oldw, oldh)
end
end
end
}
function SWEP:ViewModelDrawn()
local cv = GetConVar("gphone_bgblur")
local flip = GetConVar("gphone_lefthand"):GetBool()
if cv and cv:GetBool() then
local st = SysTime()
if GPhone.CursorEnabled or self.ToggleDelay > st then
cam.Start2D()
local p = math.Clamp((self.ToggleDelay - st)/0.3, 0, 1)
if GPhone.CursorEnabled then
p = 1 - p
end
surface.SetDrawColor(255,255,255)
surface.SetMaterial(blurmat)
for i = 1, 3 do
blurmat:SetFloat("$blur", (i / 3) * 3 * p)
blurmat:Recompute()
render.UpdateScreenEffectTexture()
surface.DrawTexturedRect(0, 0, ScrW(), ScrH())
end
cam.End2D()
end
end
local ply = LocalPlayer()
local vm = LocalPlayer():GetViewModel()
if !self.PhoneInfo then return end
if !IsValid(self.PhoneModel) then
local mdl = ClientsideModel(self.WorldModel, RENDERGROUP_OPAQUE)
mdl:SetNoDraw(true)
self.PhoneModel = mdl
end
local pos,ang
if g_VR and g_VR.active then
pos = self:GetPos()
ang = self:GetAngles()
else
local bone_id = vm:LookupBone(self.PhoneInfo.bone)
if !bone_id then return end
pos,ang = vm:GetBonePosition(bone_id)
end
if IsValid(self.Owner) and self.Owner:IsPlayer() and flip then
ang.r = -ang.r
end
local p = (flip and -1 or 1)
local offset
if g_VR and g_VR.active then
offset = Vector(0, 0, 0)
else
offset = Vector(self.PhoneInfo.pos.x, self.PhoneInfo.pos.y, self.PhoneInfo.pos.z)
end
if GPhone.Landscape then
offset.x = offset.x + 1.3
offset.y = offset.y - 0.1
offset.z = offset.z + 0.7
end
pos = pos + ang:Forward() * offset.x + ang:Right() * offset.y * p + ang:Up() * offset.z
ang:RotateAroundAxis(ang:Up(), p * self.PhoneInfo.ang.y)
ang:RotateAroundAxis(ang:Right(), p * self.PhoneInfo.ang.p)
ang:RotateAroundAxis(ang:Forward(), p * self.PhoneInfo.ang.r)
if GPhone.Landscape then
ang:RotateAroundAxis(ang:Forward(), 90)
end
self.PhoneModel:SetPos( pos )
self.PhoneModel:SetAngles( ang )
self.PhoneModel:SetLOD(0)
self.PhoneModel:SetSkin(4)
self.PhoneModel:SetupBones()
self.PhoneModel:DrawModel()
if LocalPlayer():GetNWString("PhoneCase") != "" && LocalPlayer():GetNWString("PhoneCase") != "none" then
self.PhoneModel:SetSubMaterial(0, LocalPlayer():GetNWString("PhoneCase"))
else
local col = LocalPlayer():GetWeaponColor() * 255
local c = Color(math.Round(col.x), math.Round(col.y), math.Round(col.z))
local mat = "models/nitro/iphone_case"
local params = { ["$basetexture"] = mat, ["$vertexcolor"] = 1, ["$color2"] = "{ "..c.r.." "..c.g.." "..c.b.." }" }
local matname = mat.."-"..c.r.."-"..c.g.."-"..c.b
local phonemat = CreateMaterial(matname, "VertexLitGeneric", params)
self.PhoneModel:SetSubMaterial(0, "!"..matname)
end
if LocalPlayer():WaterLevel() > 2 then return end
pos = pos + ang:Forward() * self.ScreenInfo.pos.x + ang:Right() * self.ScreenInfo.pos.y * p + ang:Up() * self.ScreenInfo.pos.z * p
ang:RotateAroundAxis(ang:Up(), p * self.ScreenInfo.ang.y)
ang:RotateAroundAxis(ang:Right(), p * self.ScreenInfo.ang.p)
ang:RotateAroundAxis(ang:Forward(), p * self.ScreenInfo.ang.r)
local cv = GetConVar("gphone_lighting")
if cv and cv:GetBool() and !GPhone.SelfieEnabled() then
local dlight = DynamicLight( self:EntIndex() )
if dlight then
dlight.Pos = pos + ang:Up()*4
dlight.r = 150
dlight.g = 150
dlight.b = 255
dlight.Brightness = 1
dlight.Decay = 1000
dlight.size = 30
dlight.DieTime = CurTime() + 1
end
end
if flip then
ang:RotateAroundAxis(ang:Up(), 180)
pos = pos - ang:Forward() * self.ScreenInfo.size * 560*2 - ang:Right() * self.ScreenInfo.size * 830*2
end
cam.Start3D2D(pos, ang, self.ScreenInfo.size)
local cv = GetConVar("gphone_brightness")
local light = 0.7 + math.Clamp(render.ComputeLighting(pos, ang:Up()):Length(), 0, 0.3)
screenlight = Lerp(FrameTime() * 5, screenlight, 0.05 + 0.95 * light * math.Clamp(cv and cv:GetFloat() or 1, 0, 1))
surface.SetDrawColor(255 * screenlight, 255 * screenlight, 255 * screenlight)
surface.SetMaterial( GPhone.PhoneMT )
surface.DrawTexturedRect(0, 0, 560*2, 830*2)
local dbg = GetConVar("gphone_showbounds")
if dbg and dbg:GetBool() then
surface.SetDrawColor( Color(250, 250, 250, 100) )
surface.DrawRect( self.ScreenInfo.home.x, self.ScreenInfo.home.y, self.ScreenInfo.home.size, self.ScreenInfo.home.size )
local quick = self.ScreenInfo.quickmenu
surface.SetDrawColor( Color(250, 250, 250, 100) )
surface.DrawRect( 0, quick.y, 1120, quick.offset )
end
if !GPhone.MovingApp then
local col = LocalPlayer():GetWeaponColor()
local x,y = GPhone.CursorPos.x,GPhone.CursorPos.y
if GPhone.CursorEnabled then
local cv = GetConVar("gphone_cursorsize")
local size = math.Round(cv and cv:GetFloat() or 60)
local cmat = GetConVar("gphone_cursormat")
local mat = GPhone.GetInputText() and "gphone/text" or cmat and cmat:GetString() or "effects/select_dot"
surface.SetDrawColor(col.x*255, col.y*255, col.z*255, 255)
surface.SetTexture( surface.GetTextureID( mat ) )
surface.DrawTexturedRectRotated(x, y, size, size, GPhone.Landscape and -90 or 0)
end
end
cam.End3D2D()
end
hook.Add("RenderScene", "GPhoneRenderPhoneRT", function(origin, angles, fov)
local wep = LocalPlayer():GetActiveWeapon()
if IsValid(wep) and wep:GetClass() == "gmod_gphone" and wep.ScreenInfo then
if LocalPlayer():WaterLevel() > 2 then return end
local mtx = GPhone.PhoneMT:GetMatrix("$basetexturetransform")
if GPhone.Landscape then
mtx:SetAngles( Angle(0, -90, 0) )
GPhone.PhoneMT:SetTexture("$basetexture", GPhone.PhoneLSRT)
render.PushRenderTarget(GPhone.PhoneLSRT)
else
mtx:SetAngles( Angle(0, 0, 0) )
GPhone.PhoneMT:SetTexture("$basetexture", GPhone.PhoneRT)
render.PushRenderTarget(GPhone.PhoneRT)
end
GPhone.PhoneMT:SetMatrix("$basetexturetransform", mtx)
render.Clear(0, 0, 0, 255, true, true)
cam.Start2D()
local oldw,oldh = ScrW(),ScrH()
local w,h = GPhone.Width,GPhone.Height
local offset = GPhone.Desk.Offset
local x,y = GPhone.GetCursorPos()
local app = GPhone.GetApp( GPhone.CurrentApp )
local frame = GPhone.CurrentFrame
local fullscreen = (!app or frame and frame.b_fullscreen)
render.SetViewPort(w*0.016, h*0.016, oldw, oldh)
hook.Run("GPhonePreRenderScreen", w, h)
if wep.ScreenInfo.draw then
if fullscreen then
GPhone.DebugFunction( wep.ScreenInfo.draw, wep, w, h, GPhone.Resolution )
else
GPhone.DebugFunction( wep.ScreenInfo.draw, wep, w, h - offset, GPhone.Resolution )
end
end
render.SetViewPort(w*0.016, h*0.016, oldw, oldh)
if GPhone.MovingApp then
local a = GPhone.GetApp( GPhone.MovingApp )
local size = GPhone.GetAppSize()
local posx,posy = math.Clamp(x, 0, w),math.Clamp(y, 0, h)
surface.SetDrawColor(255, 255, 255, 255)
surface.SetMaterial( GPhone.GetImage( a.Icon ) )
surface.DrawTexturedRect(posx - size/2, posy - size/2, size, size)
draw.SimpleText(a.Name, "GPAppName"..GPhone.Rows, posx + 2, posy + size/2 + 2, Color(0,0,0), TEXT_ALIGN_CENTER)
draw.SimpleText(a.Name, "GPAppName"..GPhone.Rows, posx, posy + size/2, Color(255,255,255), TEXT_ALIGN_CENTER)
local cv = GetConVar("gphone_showbounds")
if cv and cv:GetBool() then
surface.SetDrawColor( Color( 255, 0, 0, 255 ) )
surface.DrawOutlinedRect( posx - size/2, posy - size/2, size, size )
end
end
local isLauncher = GPhone.CurrentApp == GPhone.GetData("launcher", "launcher")
if isLauncher or !fullscreen then
local p_col = Color(255,255,255)
local shadow = true
if !isLauncher and app and !GPhone.AppScreen.Enabled then
shadow = false
if app.Negative then
draw.RoundedBox(0, 0, 0, w, offset, Color(0,0,0))
else
draw.RoundedBox(0, 0, 0, w, offset, Color(255,255,255))
p_col = Color(0,0,0)
end
end
hook.Run("GPhonePreRenderTopbar", w, offset)
local ampm = GPhone.GetData("ampm", false)
local sf = GetConVar("gphone_sf")
local time = ampm and os.date("%I:%M %p") or os.date("%H:%M")
if sf and sf:GetBool() and (StormFox or StormFox2) then
if StormFox and StormFox.Version < 2 then
time = StormFox.GetRealTime(nil, ampm)
elseif StormFox2 then
time = StormFox2.Time.TimeToString(nil, ampm)
end
end
surface.SetFont( "GPTopBar" )
local gts = surface.GetTextSize( "GMad Inc." )
if shadow then
draw.SimpleText(time, "GPTopBar", w/2 + 2, offset/2 + 2, Color(0, 0, 0), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
draw.SimpleText("GMad Inc.", "GPTopBar", 6, offset/2 + 2, Color(0, 0, 0), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
surface.SetDrawColor(0, 0, 0, 255)
surface.SetTexture( surface.GetTextureID( "gphone/wifi_3") )
surface.DrawTexturedRect(gts + 10, 6, offset-8, offset-8)
surface.SetDrawColor(0, 0, 0, 255)
surface.SetTexture( surface.GetTextureID( "gphone/battery") )
surface.DrawTexturedRect(w-offset*2-2, 6, offset*2-8, offset-8)
end
draw.SimpleText(time, "GPTopBar", w/2, offset/2, p_col, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
draw.SimpleText("GMad Inc.", "GPTopBar", 4, offset/2, p_col, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
surface.SetDrawColor(p_col.r, p_col.g, p_col.b, 255)
surface.SetTexture( surface.GetTextureID( "gphone/wifi_3") )
surface.DrawTexturedRect(gts + 8, 4, offset-8, offset-8)
surface.SetDrawColor(p_col.r, p_col.g, p_col.b, 255)
surface.SetTexture( surface.GetTextureID( "gphone/battery") )
surface.DrawTexturedRect(w-offset*2-4, 4, offset*2-8, offset-8)
local p = math.Clamp(system.BatteryPower()/100, 0, 1)
if p > 0 then
if shadow then
draw.SimpleText(math.Round(p*100).."%", "GPTopBar", w-offset*2-6, offset/2 + 2, Color(0, 0, 0), TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER)
surface.SetDrawColor(0, 0, 0, 255)
surface.SetTexture( surface.GetTextureID( "gphone/battery_meter") )
surface.DrawTexturedRectUV(w-offset*2-2, 6, (offset*2-8)*p, offset-8, 0, 0, p, 1)
end
draw.SimpleText(math.Round(p*100).."%", "GPTopBar", w-offset*2-8, offset/2, p_col, TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER)
if p <= 0.2 then
surface.SetDrawColor(255, 0, 0, 255)
else
surface.SetDrawColor(p_col.r, p_col.g, p_col.b, 255)
end
surface.SetTexture( surface.GetTextureID( "gphone/battery_meter") )
surface.DrawTexturedRectUV(w-offset*2-4, 4, (offset*2-8)*p, offset-8, 0, 0, p, 1)
end
hook.Run("GPhonePostRenderTopbar", w, offset)
end
hook.Run("GPhonePostRenderScreen", w, h)
if GPhone.CursorEnabled then
local ct = CurTime()
if (wep.b_downtime or 0) > ct then
local p = (wep.b_downtime - ct) * 4
local cv = GetConVar("gphone_cursorsize")
local size = math.Round((1 - p) * 1.5 * (cv and cv:GetFloat() or 60))
surface.SetDrawColor(255, 255, 255, p * 255)
surface.SetTexture(surface.GetTextureID("effects/select_ring"))
surface.DrawTexturedRect(wep.cursor_lastx - size/2, wep.cursor_lasty - size/2, size, size)
end
end
render.SetViewPort(0, 0, oldw, oldh)
cam.End2D()
render.PopRenderTarget()
end
end)
local devcon = GetConVar("developer")
local lmbmat = Material("gphone/icons/lmb.png")
local rmbmat = Material("gphone/icons/rmb.png")
local infmat = Material("gphone/icons/hint.png")
local scrmat = Material("gphone/icons/scroll.png")
function SWEP:DrawHUD()
if devcon:GetBool() then
surface.SetDrawColor(255, 255, 255)
surface.SetMaterial( GPhone.PhoneMT )
if GPhone.Landscape then
surface.DrawTexturedRectRotated(830 / 2, 560 / 2, 560, 830, 90)
else
surface.DrawTexturedRect(0, 0, 560, 830)
end
surface.SetDrawColor( Color(0, 0, 0, 255) )
surface.DrawRect( self.ScreenInfo.home.x / 2, self.ScreenInfo.home.y / 2, self.ScreenInfo.home.size / 2, self.ScreenInfo.home.size / 2 )
if GPhone.CursorEnabled then
local col = LocalPlayer():GetWeaponColor()
local x,y = GPhone.CursorPos.x / 2,GPhone.CursorPos.y / 2
local cv = GetConVar("gphone_cursorsize")
local size = math.Round(cv and cv:GetFloat() or 60) / 2
local cmat = GetConVar("gphone_cursormat")
local mat = GPhone.GetInputText() and "gphone/text" or cmat and cmat:GetString() or "effects/select_dot"
surface.SetDrawColor(col.x * 255, col.y * 255, col.z * 255, 255)
surface.SetTexture( surface.GetTextureID( mat ) )
surface.DrawTexturedRectRotated(x, y, size, size, GPhone.Landscape and -90 or 0)
end
end
local cv = GetConVar("gphone_hints")
if cv and cv:GetBool() then
surface.SetDrawColor( 10, 10, 10, 200 )
surface.SetTexture( surface.GetTextureID( "gui/gradient" ) )
surface.DrawTexturedRect( ScrW()/2, ScrH()-88, 256, 88 )
surface.SetDrawColor( 10, 10, 10, 200 )
surface.SetTexture( surface.GetTextureID( "gui/gradient" ) )
surface.DrawTexturedRectRotated( ScrW()/2 - 128, ScrH()-88 + 44, 256, 88, 180 )
if !GPhone.CursorEnabled then
surface.SetDrawColor( 255, 255, 255, 255 )
surface.SetMaterial( rmbmat )
surface.DrawTexturedRect( ScrW()/2-16, ScrH() - 80, 32, 32 )
draw.SimpleText("Right-click to toggle focus on the phone", "GPAppBuilder", ScrW()/2, ScrH() - 54, Color(255,255,255), TEXT_ALIGN_CENTER)
draw.SimpleText("Press reload to rotate the phone", "GPAppBuilder", ScrW()/2, ScrH() - 32, Color(255,255,255), TEXT_ALIGN_CENTER)
elseif GPhone.GetInputText() then
surface.SetDrawColor( 255, 255, 255, 255 )
surface.SetMaterial( infmat )
surface.DrawTexturedRect( ScrW()/2-16, ScrH() - 80, 32, 32 )
draw.SimpleText("You can type using your keyboard", "GPAppBuilder", ScrW()/2, ScrH() - 54, Color(255,255,255), TEXT_ALIGN_CENTER)
draw.SimpleText("Left-click to cancel. Enter to continue", "GPAppBuilder", ScrW()/2, ScrH() - 32, Color(255,255,255), TEXT_ALIGN_CENTER)
elseif GPhone.MovingApp then
surface.SetDrawColor( 255, 255, 255, 255 )
surface.SetMaterial( lmbmat )
surface.DrawTexturedRect( ScrW()/2-16, ScrH() - 80, 32, 32 )
draw.SimpleText("Release left-click to move the app", "GPAppBuilder", ScrW()/2, ScrH() - 54, Color(255,255,255), TEXT_ALIGN_CENTER)
draw.SimpleText("Scroll to go between pages", "GPAppBuilder", ScrW()/2, ScrH() - 32, Color(255,255,255), TEXT_ALIGN_CENTER)
elseif GPhone.MoveMode then
surface.SetDrawColor( 255, 255, 255, 255 )
surface.SetMaterial( lmbmat )
surface.DrawTexturedRect( ScrW()/2-16, ScrH() - 80, 32, 32 )
draw.SimpleText("Hold left-click on an app to move it", "GPAppBuilder", ScrW()/2, ScrH() - 54, Color(255,255,255), TEXT_ALIGN_CENTER)
draw.SimpleText("Left-click to go back", "GPAppBuilder", ScrW()/2, ScrH() - 32, Color(255,255,255), TEXT_ALIGN_CENTER)
elseif GPhone.AppScreen.Enabled then
surface.SetDrawColor( 255, 255, 255, 255 )
surface.SetMaterial( lmbmat )
surface.DrawTexturedRect( ScrW()/2-16, ScrH() - 80, 32, 32 )
draw.SimpleText("Left-click on a window to open it", "GPAppBuilder", ScrW()/2, ScrH() - 54, Color(255,255,255), TEXT_ALIGN_CENTER)
draw.SimpleText("Left-click on a cross to close the window", "GPAppBuilder", ScrW()/2, ScrH() - 32, Color(255,255,255), TEXT_ALIGN_CENTER)
elseif GPhone.CurrentApp and GPhone.CurrentApp == GPhone.GetData("launcher", "launcher") then
surface.SetDrawColor( 255, 255, 255, 255 )
surface.SetMaterial( lmbmat )
surface.DrawTexturedRect( ScrW()/2-16, ScrH() - 80, 32, 32 )
draw.SimpleText("Left-click on an app to open it", "GPAppBuilder", ScrW()/2, ScrH() - 54, Color(255,255,255), TEXT_ALIGN_CENTER)
draw.SimpleText("Hold left-click to edit the screen", "GPAppBuilder", ScrW()/2, ScrH() - 32, Color(255,255,255), TEXT_ALIGN_CENTER)
else
surface.SetDrawColor( 255, 255, 255, 255 )
surface.SetMaterial( scrmat )
surface.DrawTexturedRect( ScrW()/2-16, ScrH() - 80, 32, 32 )
draw.SimpleText("Use your scroll-wheel to scroll up and down", "GPAppBuilder", ScrW()/2, ScrH() - 54, Color(255,255,255), TEXT_ALIGN_CENTER)
draw.SimpleText("Scrolling only works on supported apps", "GPAppBuilder", ScrW()/2, ScrH() - 32, Color(255,255,255), TEXT_ALIGN_CENTER)
end
end
end
function SWEP:DrawWeaponSelection( x, y, wide, tall, alpha )
-- Borders
y = y + 10
x = x + 10
wide = wide - 20
tall = tall - 20
alpha = (alpha - 191) / 64 * 255
local cv = GetConVar("gphone_wepicon")
if cv and cv:GetBool() then
local fsin = math.sin( RealTime() * 8 )
local centerx, centery = x + wide/2,y + tall/2
local radius = wide/2
local apps = GPhone.GetApps()
local size = (32 + 8 * fsin) * GPhone.Resolution
local frag = (math.pi * 2) / table.Count( apps )
local i = frag
for name,app in pairs(apps) do
i = i + frag
local r = RealTime() * 2
local s,c = math.sin(i + r),math.cos(i + r)
surface.SetDrawColor( 255, 255, 255, alpha )
surface.SetMaterial( GPhone.GetImage( app.Icon ) )
surface.DrawTexturedRectRotated( centerx - s * radius, centery - c * radius, size, size, math.deg(i + r) )
end
if !IsValid(WeaponInfoEnt) then
WeaponInfoEnt = ClientsideModel( self.WorldModel, RENDER_GROUP_OPAQUE_ENTITY )
WeaponInfoEnt:SetNoDraw( true )
WeaponInfoEnt:SetModel( self.WorldModel )
WeaponInfoEnt:SetSkin( 4 )
else
local subs = WeaponInfoEnt:GetMaterials()
if LocalPlayer():GetNWString("PhoneCase") != "" then
for i = 1, #subs do
if subs[i] == "models/nitro/iphone_case" then
WeaponInfoEnt:SetSubMaterial(i-1, LocalPlayer():GetNWString("PhoneCase"))
end
end
else
local pcol = LocalPlayer():GetWeaponColor()
local col = Color(math.Round(pcol.x*255),math.Round(pcol.y*255),math.Round(pcol.z*255))
local mat = "models/nitro/iphone_case"
local params = { ["$basetexture"] = mat, ["$vertexcolor"] = 1, ["$color2"] = "{ "..col.r.." "..col.g.." "..col.b.." }" }
local matname = mat.."-"..col.r.."-"..col.g.."-"..col.b
local phonemat = CreateMaterial(matname,"VertexLitGeneric",params)
for i = 1, #subs do
if subs[i] == "models/nitro/iphone_case" then
WeaponInfoEnt:SetSubMaterial(i-1, "!"..matname)
end
end
end
local vec = Vector(32,0,0)
local ang = Vector(-1,0,0):Angle()
cam.Start3D( vec, ang, 14, x, y + tall*0.22, wide, tall, 5, 48 )
render.SuppressEngineLighting( true )
render.ResetModelLighting( 50/255, 50/255, 50/255 )
render.SetColorModulation( 1, 1, 1 )
render.SetBlend( alpha/255 )
render.SetModelLighting( 4, 1, 1, 1 )
WeaponInfoEnt:SetupBones()
WeaponInfoEnt:DrawModel()
render.SetColorModulation( 1, 1, 1 )
render.SetBlend( 1 )
render.SuppressEngineLighting( false )
cam.End3D()
end
else
local ratio = GPhone.Ratio
local w = tall * ratio
surface.SetDrawColor( 255, 255, 255, alpha )
surface.SetTexture( self.WepSelectIcon )
surface.DrawTexturedRect( x + wide/2 - w/2, y, w, tall )
end
end
function SWEP:PostDrawViewModel( vm )
if g_VR and g_VR.active then return end
local flip = GetConVar("gphone_lefthand"):GetBool()
if flip then
render.CullMode( MATERIAL_CULLMODE_CW )
end
local cv = GetConVar("gphone_hands")
if !cv or !cv:GetBool() then
local hands = self.Owner:GetHands()
if IsValid(hands) then hands:DrawModel() end
else
if !IsValid(self.HandModel) then
local mdl = ClientsideModel("models/weapons/c_arms_citizen.mdl", RENDERGROUP_OPAQUE)
mdl:SetBodygroup( 1, 1 )
mdl:SetNoDraw(true)
mdl:SetParent( vm )
mdl:AddEffects( EF_BONEMERGE )
function mdl:GetPlayerColor()
return Vector(0, 0, 0)
end
self.HandModel = mdl
end
local hands = self.HandModel
if IsValid(hands) then hands:DrawModel() end
end
if flip then
render.CullMode( MATERIAL_CULLMODE_CCW )
end
end
function SWEP:DrawWorldModel()
local ply = self.Owner
if IsValid(ply) then
local attach_id = ply:LookupAttachment("anim_attachment_RH")
if !attach_id then return end
local attach = ply:GetAttachment(attach_id)
if !attach then return end
local pos,ang = attach.Pos,attach.Ang
local organg = ang
pos = pos + ang:Forward() * self.WorldModelInfo.pos.x + ang:Right() * self.WorldModelInfo.pos.y + ang:Up() * self.WorldModelInfo.pos.z
self:SetRenderOrigin(pos)
ang:RotateAroundAxis(ang:Up(), self.WorldModelInfo.ang.y)
ang:RotateAroundAxis(ang:Right(), self.WorldModelInfo.ang.p)
ang:RotateAroundAxis(ang:Forward(), self.WorldModelInfo.ang.r)
self:SetRenderAngles(ang)
self:SetSkin(1)
self:DrawModel()
if LocalPlayer():GetNWString("PhoneCase") != "" && LocalPlayer():GetNWString("PhoneCase") != "none" then
self:SetSubMaterial(0, LocalPlayer():GetNWString("PhoneCase"))
else
local col = LocalPlayer():GetWeaponColor() * 255
local c = Color(math.Round(col.x), math.Round(col.y), math.Round(col.z))
local mat = "models/nitro/iphone_case"
local params = { ["$basetexture"] = mat, ["$vertexcolor"] = 1, ["$color2"] = "{ "..c.r.." "..c.g.." "..c.b.." }" }
local matname = mat.."-"..c.r.."-"..c.g.."-"..c.b
local phonemat = CreateMaterial(matname, "VertexLitGeneric", params)
self:SetSubMaterial(0, "!"..matname)
end
pos = pos + ang:Forward() * self.ScreenInfo.pos.x + ang:Right() * self.ScreenInfo.pos.y + ang:Up() * self.ScreenInfo.pos.z
ang:RotateAroundAxis(ang:Up(), self.ScreenInfo.ang.y)
ang:RotateAroundAxis(ang:Right(), self.ScreenInfo.ang.p)
ang:RotateAroundAxis(ang:Forward(), self.ScreenInfo.ang.r)
local cv = GetConVar("gphone_lighting")
if cv and cv:GetBool() then
local dlight = DynamicLight( self:EntIndex() )
if dlight then
dlight.Pos = pos + ang:Up()*4
dlight.r = 150
dlight.g = 150
dlight.b = 255
dlight.Brightness = 1
dlight.Decay = 1000
dlight.size = 30
dlight.DieTime = CurTime() + 1
end
end
cam.Start3D2D(pos, ang, self.ScreenInfo.size)
local cv = GetConVar("gphone_brightness")
local light = 0.7 + math.Clamp(render.ComputeLighting(pos, -ang:Up()):Length(), 0, 0.3)
screenlight = Lerp(FrameTime() * 5, screenlight, 0.05 + 0.95 * light * math.Clamp(cv and cv:GetFloat() or 1, 0, 1))
surface.SetDrawColor(255 * screenlight, 255 * screenlight, 255 * screenlight)
surface.SetMaterial( GPhone.PhoneMT )
surface.DrawTexturedRect(0, 0, 560*2, 830*2)
local dbg = GetConVar("gphone_showbounds")
if dbg and dbg:GetBool() then
surface.SetDrawColor( Color(250,250,250,100) )
surface.DrawRect( self.ScreenInfo.home.x, self.ScreenInfo.home.y, self.ScreenInfo.home.size, self.ScreenInfo.home.size )
local quick = self.ScreenInfo.quickmenu
surface.SetDrawColor( Color(250,250,250,100) )
surface.DrawRect( 0, quick.y, 1120, quick.offset )
end
if !GPhone.MovingApp then
local col = LocalPlayer():GetWeaponColor()
local x,y = GPhone.CursorPos.x,GPhone.CursorPos.y
local cv = GetConVar("gphone_cursorsize")
local size = math.Round(cv and cv:GetFloat() or 60)
local cmat = GetConVar("gphone_cursormat")
local mat = GPhone.GetInputText() and "gphone/text" or cmat and cmat:GetString() or "effects/select_dot"
surface.SetDrawColor(col.x*255, col.y*255, col.z*255, 255)
surface.SetTexture( surface.GetTextureID( mat ) )
surface.DrawTexturedRectRotated(x, y, size, size, GPhone.Landscape and -90 or 0)
end
cam.End3D2D()
else
self:SetSkin(1)
self:DrawModel()
end
end<file_sep>APP.Name = "Launcher"
APP.Author = "Krede"
APP.Launcher = true
APP.Icon = "asset://garrysmod/materials/gphone/apps/camera.png"
function APP.Run(frame, w, h, ratio)
frame:SetFullScreen(true)
local dotemat = Material("gphone/dot_empty")
local dotfmat = Material("gphone/dot_full")
function frame:OnScroll(num)
if GPhone.MoveMode then
GPhone.Page = math.max(GPhone.Page - num, 1)
else
GPhone.Page = math.Clamp(GPhone.Page - num, 1, #GPhone.GetAppPos())
end
self:Reload(self, w, h, ratio)
end
function frame:OnClick(long)
if !GPhone.MoveMode and long then
GPhone.MoveMode = true
else
GPhone.MoveMode = false
end
end
function frame:Paint(x, y, w, h)
hook.Run("GPhonePreRenderBackground", w, h)
local mat = GPhone.BackgroundMat
if mat and !mat:IsError() then
local rw,rh = mat:GetFloat("$realwidth") or mat:Width(), mat:GetFloat("$realheight") or mat:Height()
local rt = rw / rh
surface.SetDrawColor(255, 255, 255, 255)
surface.SetMaterial( mat )
if GPhone.Landscape then
local s = w / rt
surface.DrawTexturedRect(0, h/2 - s/2, w, s)
else
local s = h * rt
surface.DrawTexturedRect(w/2 - s/2, 0, s, h)
end
end
hook.Run("GPhonePostRenderBackground", w, h)
local pages = #GPhone.GetAppPos()
if pages > 1 or GPhone.MoveMode then
for i = 1, pages do
surface.SetDrawColor(255, 255, 255, 255)
if GPhone.Page == i then
surface.SetMaterial(dotfmat)
else
surface.SetMaterial(dotemat)
end
surface.DrawTexturedRect(w/2 - (pages*32)/2 + i*32 - 32, h-32, 24, 24)
end
end
end
function frame:Reload(frame, w, h, ratio)
frame:Clear()
for k,data in pairs(GPhone.GetPage()) do
local posx,posy,size,appid = data.x,data.y,data.size,data.app
local app = GPhone.GetApp(appid)
local but = GPnl.AddPanel( frame )
but:SetSize(size, size)
but:SetPos(posx, posy)
but.AppID = appid
function but:Paint(x, y, w, h)
if GPhone.MoveMode then
if GPhone.MovingApp != self.AppID then
local ran = math.Rand(-3,3)
surface.SetDrawColor(255, 255, 255, 255)
surface.SetMaterial(GPhone.GetImage(app.Icon))
surface.DrawTexturedRectRotated(w / 2, h / 2, w, h, ran)
end
else
surface.SetDrawColor(255, 255, 255, 255)
surface.SetMaterial(GPhone.GetImage(app.Icon))
surface.DrawTexturedRect(0, 0, w, h)
end
end
function but:OnClick(long)
if long then
GPhone.MovingApp = self.AppID
GPhone.MoveMode = true
else
if GPhone.MoveMode then
GPhone.MoveMode = false
else
local res = GPhone.FocusApp(self.AppID)
if !res then
GPhone.RunApp(self.AppID)
end
end
end
end
if !table.HasValue(GPDefaultApps, appid) then
local rwid = size / 3
local xwid = rwid * 0.6
local remove = GPnl.AddPanel(frame)
remove:SetSize(rwid, rwid)
remove:SetPos(posx - rwid / 2, posy - rwid / 2)
remove.AppID = appid
function remove:Paint(x, y, w, h)
if GPhone.MoveMode and GPhone.MovingApp != self.AppID then
draw.RoundedBox(w/2, 0, 0, w, h, Color(190, 190, 190))
surface.SetDrawColor(0, 0, 0)
surface.SetTexture(surface.GetTextureID("gui/html/stop"))
surface.DrawTexturedRect(w/2 - xwid/2, h/2 - xwid/2, xwid, xwid)
end
end
function remove:OnClick()
if GPhone.MoveMode then
GPhone.UninstallApp(self.AppID)
end
end
end
surface.SetFont("GPAppName"..GPhone.Rows)
local tw,th = surface.GetTextSize(app.Name)
local name = GPnl.AddPanel( frame )
name:SetSize(tw + 2, th + 2)
name:SetPos(posx + size / 2 - tw / 2, posy + size)
name.AppID = appid
name.Font = "GPAppName"..GPhone.Rows
function name:Paint(x, y, w, h)
if GPhone.MoveMode then
if GPhone.MovingApp != self.AppID then
local ran = math.Rand(-1,1)
draw.SimpleText(app.Name, self.Font, ran + w/2 + 2, ran + 2, Color(0,0,0), TEXT_ALIGN_CENTER)
draw.SimpleText(app.Name, self.Font, ran + w/2, ran, Color(255,255,255), TEXT_ALIGN_CENTER)
end
else
draw.SimpleText(app.Name, self.Font, w/2 + 2, 2, Color(0,0,0), TEXT_ALIGN_CENTER)
draw.SimpleText(app.Name, self.Font, w/2, 0, Color(255,255,255), TEXT_ALIGN_CENTER)
end
end
end
end
frame:Reload(frame, w, h, ratio)
end
function APP.Think(frame, w, h, ratio)
if GPhone.MovingApp then
local leftDown = GPhone.TriggerDown()
if !leftDown then
local rows = GPhone.GetRows()
local columns = math.floor(rows * GPhone.Resolution)
local offset = GPhone.Desk.Offset
local cellsize = GPhone.Width / rows
local x,y = GPhone.GetCursorPos()
local apps = GPhone.GetData("apps", {})
local page = (GPhone.Page - 1) * rows * columns
x = math.floor(x / cellsize)
y = math.floor((y - offset) / cellsize)
local replaceindex = page + 1 + x + y * rows
local appid = apps[replaceindex]
local moveindex = 0
for k,v in pairs(apps) do
if v == GPhone.MovingApp then
moveindex = k
end
end
apps[replaceindex] = GPhone.MovingApp
apps[moveindex] = appid
GPhone.SetData("apps", apps)
GPhone.MovingApp = nil
frame:Reload(frame, w, h, ratio)
end
end
end<file_sep>APP.Name = "Photos"
APP.Author = "Krede"
APP.Icon = "asset://garrysmod/materials/gphone/apps/photos.png"
function APP.Run( frame, w, h, ratio )
function frame:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h, Color( 220, 220, 220, 255 ) )
end
frame.m_chosen = {}
function frame:Open( pic, mat )
self:SetFullScreen( false )
self:Clear()
local bigpic = GPnl.AddPanel( self )
bigpic:SetPos( 0, -GPhone.Desk.Offset )
bigpic:SetSize( w, GPhone.Height )
function bigpic:Paint( x, y, w, h )
surface.SetDrawColor(255, 255, 255)
surface.SetMaterial( mat )
surface.DrawTexturedRect( 0, 0, w, h )
end
function bigpic:OnClick()
local bool = !footer:GetVisible()
footer:SetVisible( bool )
header:SetVisible( bool )
local off = frame:SetFullScreen( !bool )
self:SetPos( 0, -off )
end
footer = GPnl.AddPanel( self )
footer:SetPos( 0, h - 64 * ratio )
footer:SetSize( w, 64 * ratio )
function footer:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, 2, Color( 80, 80, 80, 255 ) )
draw.RoundedBox( 0, 0, 2, w, h-2, Color( 255, 255, 255, 255 ) )
end
header = GPnl.AddPanel( self )
header:SetPos( 0, 0 )
header:SetSize( w, 64 * ratio )
function header:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
local name = string.Explode("/", pic)
draw.SimpleText(name[#name], "GPTitle", w/2, h/2, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
if file.Exists(pic, "DATA") then
local trash = GPnl.AddPanel( footer )
trash:SetPos( footer:GetWidth() - 64 * ratio, 0 )
trash:SetSize( 64 * ratio, 64 * ratio )
function trash:Paint( x, y, w, h )
surface.SetDrawColor(255, 0, 0)
surface.SetTexture( surface.GetTextureID( "gui/html/stop" ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
function trash:OnClick()
if file.Exists(pic, "DATA") then
file.Delete(pic)
end
frame:Main()
end
end
local wallpaper = GPnl.AddPanel( footer )
wallpaper:SetPos( 64 * ratio, 0 )
wallpaper:SetSize( footer:GetWidth() - 128 * ratio, 64 * ratio )
function wallpaper:Paint( x, y, w, h )
draw.SimpleText("Set As Background", "GPMedium", w/2, h/2, Color(75, 170, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
function wallpaper:OnClick()
if file.Exists(pic, "DATA") then
GPhone.SetData("background", "data/"..pic)
end
end
local back = GPnl.AddPanel( header )
back:SetPos( 0, 0 )
back:SetSize( 64 * ratio, 64 * ratio )
function back:OnClick()
frame:Main()
end
function back:Paint( x, y, w, h )
draw.SimpleText("<", "GPTitle", w/2, h/2, Color(0, 160, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
end
function frame:Main()
self:Clear()
local scroll = GPnl.AddPanel( self, "scroll" )
scroll:SetPos( 0, 64 * ratio )
scroll:SetSize( w, h - 128 * ratio )
local x = 0
local y = 0
local size = w/6
local pics,dirs = file.Find("gphone/photos/*.jpg", "DATA")
for i,jpg in pairs(pics) do
timer.Simple((i-1)*0.05, function()
x = x + 1
while x > 6 do
x = 1
y = y + 1
end
local but = GPnl.AddPanel( scroll )
but:SetSize( size, size )
but:SetPos( x*size - size, y*size )
but.pic = "gphone/photos/"..jpg
but.mat = Material( "data/gphone/photos/"..jpg )
function but:Paint( x, y, w, h )
if frame and frame.m_choose and table.HasValue(frame.m_chosen, but) then
draw.RoundedBox( 0, 0, 0, w, h, Color( 0, 200, 255 ) )
end
surface.SetDrawColor(255, 255, 255)
surface.SetMaterial( but.mat )
surface.DrawTexturedRect( 2, 2, w-4, h-4 )
end
function but:OnClick( hold )
if hold and !frame.m_choose then
frame.trash:SetVisible( true )
frame.m_choose = true
frame.m_chosen = { self }
elseif frame.m_choose then
if table.HasValue(frame.m_chosen, but) then
table.RemoveByValue(frame.m_chosen, but)
else
table.insert(frame.m_chosen, but)
end
else
frame:Open( but.pic, but.mat )
end
end
end)
end
local footer = GPnl.AddPanel( self )
footer:SetPos( 0, h - 64 * ratio )
footer:SetSize( w, 64 * ratio )
function footer:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, 2, Color( 80, 80, 80, 255 ) )
draw.RoundedBox( 0, 0, 2, w, h-2, Color( 255, 255, 255, 255 ) )
end
self.trash = GPnl.AddPanel( footer )
self.trash:SetPos( footer:GetWidth() - 64 * ratio, 0 )
self.trash:SetSize( 64 * ratio, 64 * ratio )
self.trash:SetVisible(false)
function self.trash:Paint( x, y, w, h )
if frame and frame.m_chosen and #frame.m_chosen > 0 then
surface.SetDrawColor(255, 0, 0)
else
surface.SetDrawColor(50, 50, 50)
end
surface.SetTexture( surface.GetTextureID( "gui/html/stop" ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
function self.trash:OnClick()
if frame and frame.m_chosen and #frame.m_chosen > 0 then
for k,but in pairs(frame.m_chosen) do
if file.Exists(but.pic, "DATA") then
file.Delete(but.pic)
end
but:Remove()
end
frame.m_choose = false
frame.m_chosen = {}
self:SetVisible(false)
frame:Main()
end
end
local header = GPnl.AddPanel( self )
header:SetPos( 0, 0 )
header:SetSize( w, 64 * ratio )
function header:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("Photos", "GPTitle", w/2, h/2, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
local choose = GPnl.AddPanel( header )
choose:SetSize( 104 * ratio, 64 * ratio )
choose:SetPos( w - 104 * ratio, 0 )
function choose:Paint( x, y, w, h )
if !frame then return end
if !frame.m_choose then
draw.SimpleText("Pick", "GPMedium", w-5, h/2, Color(0, 160, 255), TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER)
else
draw.SimpleText("Cancel", "GPMedium", w-5, h/2, Color(0, 160, 255), TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER)
end
end
function choose:OnClick()
local b = !frame.m_choose
frame.m_choose = b
if !b then
frame.m_chosen = {}
frame.trash:SetVisible(false)
else
frame.trash:SetVisible(true)
end
end
end
frame:Main()
end
function APP.Focus( frame )
if frame.trash then
frame:Main()
end
end<file_sep>APP.Name = "Maps"
APP.Author = "Krede"
APP.Icon = "asset://garrysmod/materials/gphone/apps/maps.png"
function APP.Run( frame, w, h, ratio )
function frame:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h, Color( 0, 0, 0, 255 ) )
end
local arrowmat = Material("gphone/maps/arrow.png", "nocull smooth")
local pointmat = Material("gphone/maps/point.png", "nocull smooth")
local mat,offset,dist = LoadMapRT()
local map = GPnl.AddPanel( frame )
map:SetPos( 0, 64 * ratio )
map:SetSize( w, w )
function map:OnClick()
local x,y = GPhone.GetCursorPos()
local point = GPnl.AddPanel( self )
point:SetPos( x - 16 * ratio, y - GPhone.Desk.Offset - (32 + 64) * ratio )
point:SetSize( 32 * ratio, 32 * ratio )
function point:Paint( x, y, w, h )
surface.SetDrawColor( 255, 0, 0 )
surface.SetMaterial( pointmat )
surface.DrawTexturedRect( 0, 0, w, h )
end
function point:OnClick()
point:Remove()
end
end
function map:Paint( x, y, w, h )
local offx,offy = offset.x or 0,offset.y or 0
local max = dist*2
surface.SetDrawColor( 255, 255, 255 )
surface.SetMaterial( mat )
surface.DrawTexturedRect( 0, 0, w, w )
--[[for _,v in pairs(self:GetChildren()) do
local px,py = v:GetPos()
local x,y = mapToRealPos( px, py, w, offx, offy, max )
local pos = LocalPlayer():GetPos()
local path = ComputeAStar( navmesh.GetNearestNavArea( pos ), navmesh.GetNearestNavArea( Vector(x, y, pos.z) ) )
PrintTable(path)
end]]
for k,ply in pairs(player.GetAll()) do
local plypos = ply:GetPos()
local plyang = ply:EyeAngles()
local plycol = ply:GetPlayerColor()*255
local px,py = realToMapPos( plypos.x, plypos.y, w, offx, offy, max )
surface.SetDrawColor( plycol.r, plycol.g, plycol.b )
surface.SetMaterial( arrowmat )
surface.DrawTexturedRectRotated( px, py, 32, 32, plyang.y )
end
end
local header = GPnl.AddPanel( frame )
header:SetPos( 0, 0 )
header:SetSize( w, 64 * ratio )
function header:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText(game.GetMap(), "GPTitle", w/2, h/2, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
local refresh = GPnl.AddPanel( header )
refresh:SetPos( w - 64 * ratio, 0 )
refresh:SetSize( 64 * ratio, 64 * ratio )
function refresh:Paint( x, y, w, h )
surface.SetDrawColor(50, 50, 50)
surface.SetTexture( surface.GetTextureID( "gui/html/refresh" ) )
local ct = CurTime()
if (self.Delay or 0) < ct then
surface.DrawTexturedRect( 0, 0, w, h )
else
local p = (self.Delay - ct)*720
surface.DrawTexturedRectRotated( w/2, h/2, w, h, p )
end
end
function refresh:OnClick()
self.Delay = CurTime() + 0.5
mat,offset,dist = LoadMapRT( true )
end
end
function realToMapPos(x, y, size, offx, offy, max)
local px,py = (x - offx),(y - offy)
local x = size/2 - (px/max*size)
local y = size/2 - (py/max*size)
return y,x
end
function mapToRealPos(x, y, size, offx, offy, max)
local px = (x/size*max) - max/2
local py = (y/size*max) - max/2
local x,y = -(px - offy),-(py - offx)
return y,x
end
local function getRTCoords()
render.CapturePixels()
local leftpos = nil
local toppos = nil
local rightpos = nil
local downpos = nil
for y = 1, size do
for x = 1, size do
if leftpos and rightpos and toppos and downpos then break end -- Early exit
if !leftpos then
local r,g,b = render.ReadPixel( y, x ) -- Left
if ( r != 255 or g != 255 or b != 255 ) and ( r != 0 or g != 0 or b != 0 ) then
leftpos = y
end
end
if !toppos then
local r,g,b = render.ReadPixel( x, y ) -- Top
if ( r != 255 or g != 255 or b != 255 ) and ( r != 0 or g != 0 or b != 0 ) then
toppos = y
end
end
if !rightpos then
local r,g,b = render.ReadPixel( size - y, size - x ) -- Right
if ( r != 255 or g != 255 or b != 255 ) and ( r != 0 or g != 0 or b != 0 ) then
rightpos = y - 1
end
end
if !downpos then
local r,g,b = render.ReadPixel( size - x, size - y ) -- Bottom
if ( r != 255 or g != 255 or b != 255 ) and ( r != 0 or g != 0 or b != 0 ) then
downpos = y - 1
end
end
end
end
return leftpos, toppos, rightpos, downpos
end
function LoadMapRT( reset )
local size = math.min(ScrW(), ScrH())
local offset,dist = 0,0
local map = game.GetMap()
local bMapRT = GetRenderTarget("GPhoneMapRT_"..size, size, size, false)
local oldDraw = nil
LocalPlayer().ShouldDisableLegs = true
if EnhancedCamera then
oldDraw = EnhancedCamera.ShouldDraw
EnhancedCamera.ShouldDraw = function() return false end
end
if !reset and file.Exists("gphone/maps/"..map..".jpg", "DATA") and file.Exists("gphone/maps/"..map..".txt", "DATA") then
local r = file.Read("gphone/maps/"..map..".txt", "DATA")
local data = util.JSONToTable(r)
offset = data.offset
dist = data.dist
else
local ratio = 16384 / size
render.PushRenderTarget(bMapRT, 0, 0, size, size)
render.Clear(0, 0, 0, 0)
render.ClearStencil()
render.ClearDepth()
local pos = Vector(0, 0, 16384)
local ang = Angle(90, 0, 0)
rendering_gphone_map = true
render.SetLightingMode( 1 )
render.RenderView({
x = 0,
y = 0,
w = size,
h = size,
origin = pos,
angles = ang,
drawviewmodel = false,
drawhud = false,
dopostprocess = false,
drawmonitors = false,
znear = 16,
zfar = 32768,
ortho = true,
ortholeft = -16384,
orthoright = 16384,
orthotop = -16384,
orthobottom = 16384
})
local leftpos = nil
local toppos = nil
local rightpos = nil
local downpos = nil
render.CapturePixels()
for y = 1, size do
for x = 1, size do
if leftpos and rightpos and toppos and downpos then break end -- Early exit
if !leftpos then
local r,g,b = render.ReadPixel( y, x ) -- Left
if ( r != 255 or g != 255 or b != 255 ) and ( r != 0 or g != 0 or b != 0 ) then
leftpos = y
end
end
if !toppos then
local r,g,b = render.ReadPixel( x, y ) -- Top
if ( r != 255 or g != 255 or b != 255 ) and ( r != 0 or g != 0 or b != 0 ) then
toppos = y
end
end
if !rightpos then
local r,g,b = render.ReadPixel( size - y, size - x ) -- Right
if ( r != 255 or g != 255 or b != 255 ) and ( r != 0 or g != 0 or b != 0 ) then
rightpos = y - 1
end
end
if !downpos then
local r,g,b = render.ReadPixel( size - x, size - y ) -- Bottom
if ( r != 255 or g != 255 or b != 255 ) and ( r != 0 or g != 0 or b != 0 ) then
downpos = y - 1
end
end
end
end
local b_coords_x = (leftpos or 0)
local b_coords_y = (toppos or 0)
local b_coords_u = size - (rightpos or 0)
local b_coords_v = size - (downpos or 0)
local diffx = b_coords_u - b_coords_x
local diffy = b_coords_v - b_coords_y
local y = (size/2 - (b_coords_x + diffx/2)) * ratio * 2
local x = (size/2 - (b_coords_y + diffy/2)) * ratio * 2
offset = {x = x, y = y}
dist = (math.max(diffx, diffy) + 4) * ratio
if bit.band( util.PointContents( Vector(0, 0, 0) ), CONTENTS_SOLID ) != CONTENTS_SOLID then
local trace = util.TraceLine( {start = Vector(0, 0, 0), endpos = Vector(0, 0, 16384), mask = MASK_SOLID_BRUSHONLY} )
pos = trace.HitPos - Vector(0, 0, 8)
end
render.RenderView({
x = 0,
y = 0,
w = size,
h = size,
origin = pos,
angles = ang,
drawviewmodel = false,
drawhud = false,
dopostprocess = false,
drawmonitors = false,
znear = 16,
zfar = 32768,
ortho = true,
ortholeft = - y - dist,
orthoright = - y + dist,
orthotop = x - dist,
orthobottom = x + dist
})
render.CapturePixels()
local pos = Vector(0, 0, 16384)
render.RenderView({
x = 0,
y = 0,
w = size,
h = size,
origin = pos,
angles = ang,
drawviewmodel = false,
drawhud = false,
dopostprocess = false,
drawmonitors = false,
znear = 16,
zfar = 32768,
ortho = true,
ortholeft = - y - dist,
orthoright = - y + dist,
orthotop = x - dist,
orthobottom = x + dist
})
render.SetLightingMode( 0 )
cam.Start2D()
for y = 1, size do
for x = 1, size do
local r,g,b = render.ReadPixel( x, y )
if (r != 255 or g != 255 or b != 255) and (r != 0 or g != 0 or b != 0) then
surface.SetDrawColor(r, g, b)
surface.DrawRect(x, y, 1, 1)
end
end
end
cam.End2D()
rendering_gphone_map = false
file.CreateDir("gphone/maps")
local data = render.Capture( { format = "jpeg", quality = 100, x = 0, y = 0, h = size, w = size } )
local mapimg = file.Open( "gphone/maps/"..map..".jpg", "wb", "DATA" )
mapimg:Write( data )
mapimg:Close()
local data = {
offset = offset,
dist = dist
}
local mapfile = file.Open( "gphone/maps/"..map..".txt", "wb", "DATA" )
mapfile:Write( util.TableToJSON(data) )
mapfile:Close()
render.PopRenderTarget()
end
LocalPlayer().ShouldDisableLegs = false
if EnhancedCamera and oldDraw then
EnhancedCamera.ShouldDraw = oldDraw
end
local bMapMat = Material("data/gphone/maps/"..map..".jpg")
return bMapMat,offset,dist
end
hook.Add("PreDrawSkyBox", "GPhoneMapRenderSkybox", function()
if rendering_gphone_map then
return true
end
end)
hook.Add("SetupWorldFog", "GPhoneMapSetupWorldFog", function()
if rendering_gphone_map then
render.FogMode( 0 )
return true
end
end)
hook.Add("SetupSkyboxFog", "GPhoneMapSetupSkyFog", function()
if rendering_gphone_map then
render.FogMode( 0 )
return true
end
end)<file_sep>local gpnotfound = false
local noicon = Material("gui/dupe_bg.png", "nocull smooth")
local GPLoadingRT = GetRenderTarget("GPLoadingRT", 512, 512, false)
GPLoadingMT = CreateMaterial(
"GPLoadMT",
"UnlitGeneric",
{
["$basetexture"] = GPLoadingRT,
["$vertexcolor"] = 1,
["$vertexalpha"] = 1
}
)
cvars.AddChangeCallback("gphone_case", function( con, old, new )
if old != val then
net.Start("GPhone_Case")
net.WriteString(new)
net.SendToServer()
end
end, "gphone_stopit")
hook.Add("Think", "GPhoneGlobalThink", function()
for _,html in pairs(GPhone.HTML) do
if IsValid(html) then
if html:IsLoading() then
if !html.b_loading then
html.b_loading = true
if GPhone.IsAwesomium then
html:QueueJavascript([[window.onerror = function(msg, url, line, col, error) {
gmod.print("Line " + line + ": " + msg);
};
isAwesomium = navigator.userAgent.indexOf("Awesomium") != -1;
gmod.getURL( window.location.href );]])
end
end
else
if html.b_loading then
html.b_loading = false
GPhone.UpdateHTMLControl( html ) -- Chromium likes to randomly delete these. Remind it who's boss
html:QueueJavascript([[window.onerror = function(msg, url, line, col, error) {
gmod.print("Line " + line + ": " + msg);
};
isAwesomium = navigator.userAgent.indexOf("Awesomium") != -1;
gmod.getURL( window.location.href );]])
if GPhone.IsAwesomium == nil then
html:QueueJavascript([[gmod.isAwesomium( isAwesomium );]])
end
elseif !html.b_keepvolume then
local vol = GetConVar("gphone_volume")
html:RunJavascript([[var x = [];
x.push.apply( x, document.getElementsByTagName("VIDEO") );
x.push.apply( x, document.getElementsByTagName("AUDIO") );
for (i = 0; i < x.length; i++) {
x[i].volume = ]]..(vol and vol:GetFloat() or 1)..[[;
}]])
end
end
end
end
local count = table.Count(GPhone.ImageQueue)
if count > 0 then
gpnotfound = false
render.PushRenderTarget(GPLoadingRT)
render.Clear(0, 0, 0, 255, true, true)
cam.Start2D()
surface.SetDrawColor(255, 255, 255)
surface.SetMaterial( noicon )
surface.DrawTexturedRect( 0, 0, 512, 512 )
surface.SetDrawColor(255, 255, 255)
surface.SetTexture( surface.GetTextureID("vgui/loading-rotate") )
surface.DrawTexturedRectRotated( 256, 256, 512, 512, RealTime()*360 )
draw.SimpleText("Loading", "GPLoading", 256, 256, Color(255, 255, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_BOTTOM)
draw.SimpleText(count, "GPLoading", 256, 256, Color(255, 255, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP)
cam.End2D()
render.PopRenderTarget()
GPLoadingMT:SetTexture("$basetexture", GPLoadingRT)
for k,data in pairs(GPhone.ImageQueue) do
if GPhone.ImageCache[data.URL] then
GPhone.ImageQueue[k] = nil
break
end
if !ImgDownloadTime and !ImgReady and !IsValid(DownloadHTML) then
DownloadHTML = vgui.Create( "HTML" )
DownloadHTML:SetPos(ScrW()-1, ScrH()-1)
DownloadHTML:SetSize(data.Size, data.Size)
DownloadHTML:SetHTML([[
<style type="text/css">
html { overflow:hidden; margin: -8px -8px; }
img { ]]..(data.Style or "")..[[ }
</style>
<body>
<img src="]]..(data.URL or "")..[[" alt="]]..(data.URL or "")..[[" width="]]..(data.Size or "0")..[[" height="]]..(data.Size or "0")..[[" />
</body>
]])
end
local tex = DownloadHTML:GetHTMLMaterial()
if !ImgReady and tex and !DownloadHTML:IsLoading() then
ImgDownloadTime = CurTime() + 0.1
ImgReady = true
end
if ImgReady and ImgDownloadTime < CurTime() then
ImgReady = nil
ImgDownloadTime = nil
local scale_x,scale_y = DownloadHTML:GetWide() / tex:Width(),DownloadHTML:GetTall() / tex:Height()
local matdata = {
["$basetexture"] = tex:GetName(),
["$basetexturetransform"] = "center 0 0 scale "..scale_x.." "..scale_y.." rotate 0 translate 0 0",
["$vertexcolor"] = 1,
["$vertexalpha"] = 1,
["$nocull"] = 1,
["$model"] = 1
}
local id = string.Replace(tex:GetName(), "__vgui_texture_", "")
GPhone.ImageCache[data.URL] = CreateMaterial("GPhone_CachedImage_"..id, "UnlitGeneric", matdata)
GPhone.ImageQueue[k] = nil
DownloadHTML:Remove()
DownloadHTML = nil
end
break
end
elseif !gpnotfound then -- No need to update if we're not downloading anything
gpnotfound = true
render.PushRenderTarget(GPLoadingRT)
render.Clear(0, 0, 0, 255, true, true)
cam.Start2D()
surface.SetDrawColor(255, 255, 255)
surface.SetMaterial( noicon )
surface.DrawTexturedRect( 0, 0, 512, 512 )
draw.SimpleText("Image", "GPLoading", 512/2, 512/2, Color(255, 255, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_BOTTOM)
draw.SimpleText("Not Found", "GPLoading", 512/2, 512/2, Color(255, 255, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP)
cam.End2D()
render.PopRenderTarget()
GPLoadingMT:SetTexture("$basetexture", GPLoadingRT)
end
end)
hook.Add("HUDShouldDraw", "_GPhoneHideWPSelection", function(name)
local ply = LocalPlayer()
if IsValid(ply) then
local wep = ply:GetActiveWeapon()
if IsValid(wep) and wep:GetClass() == "gmod_gphone" then
if name == "CHUDQuickInfo" then return false end
if GPhone.CursorEnabled and name == "CHudWeaponSelection" then return false end
end
end
end)
local matflash = Material( "sprites/light_ignorez" )
hook.Add("PostPlayerDraw", "DrawGFlashlight", function(ply)
local wep = ply:GetActiveWeapon()
if ply:FlashlightIsOn() and IsValid(wep) and wep:GetClass() == "gmod_gphone" then
if ply != LocalPlayer() or GetViewEntity() != LocalPlayer() then
local id = ply:LookupAttachment("anim_attachment_RH")
if !id then return end
local attach = ply:GetAttachment(id)
if !attach then return end
local pos,ang = attach.Pos,attach.Ang
pos = pos + ang:Forward() * wep.WorldModelInfo.pos.x + ang:Right() * wep.WorldModelInfo.pos.y + ang:Up() * wep.WorldModelInfo.pos.z
pos = pos + ang:Up()*1.9 + ang:Forward()*0.6 + ang:Right()*1.1
local dir = ply:EyeAngles():Forward():Dot( (GetViewEntity():GetPos() - pos):GetNormalized() )
local leng = (GetViewEntity():GetPos() - pos):Length()
local a = math.max(1000-leng, 0)
if dir > 0.2 then
render.SetMaterial( matflash )
render.DrawSprite( pos, dir*(leng/4), dir*(leng/4), Color(255,255,255,a) )
end
end
end
end)
if IsMounted("tf") then
local earbudpos = Vector(-69.3, 0.3, 0.1)
local earbudang = Angle(0, -90, -90)
hook.Add("PostPlayerDraw", "GPhoneAirPods", function(ply)
if !ply:GetNWBool("GPMusic") then return end
if !ply:Alive() then return end
render.SetBlend(1)
if !IsValid(ply.EarBuds) then
local mdl = ClientsideModel("models/player/items/engineer/engineer_earbuds.mdl", RENDERGROUP_OPAQUE)
mdl:SetNoDraw(true)
ply.EarBuds = mdl
end
local pos = Vector()
local ang = Angle()
local bone_id = ply:LookupBone("ValveBiped.Bip01_Head1")
if !bone_id then return end
pos,ang = ply:GetBonePosition(bone_id)
pos = pos + ang:Forward() * earbudpos.x + ang:Right() * earbudpos.y + ang:Up() * earbudpos.z
ang:RotateAroundAxis(ang:Up(), earbudang.y)
ang:RotateAroundAxis(ang:Right(), earbudang.p)
ang:RotateAroundAxis(ang:Forward(), earbudang.r)
ply.EarBuds:SetRenderOrigin(pos)
ply.EarBuds:SetRenderAngles(ang)
render.EnableClipping(true)
local normal = -ang:Forward()
local origin = pos - normal * 0.5
local distance = normal:Dot( origin )
render.PushCustomClipPlane( normal, distance )
ply.EarBuds:SetupBones()
ply.EarBuds:DrawModel()
ply.EarBuds:SetRenderOrigin()
ply.EarBuds:SetRenderAngles()
render.PopCustomClipPlane()
render.EnableClipping(false)
end)
end
hook.Add("InputMouseApply", "_GPhoneMouseInput", function( cmd, x, y, angle )
local wep = LocalPlayer():GetActiveWeapon()
if IsValid(wep) and wep:GetClass() == "gmod_gphone" and GPhone.CursorEnabled then
local cv = GetConVar("gphone_sensitivity")
local sens = cv and cv:GetFloat() or 4
local inv = GPhone.Landscape
local ychange = (inv and x or y) * sens * 0.2
local xchange = (inv and -y or x) * sens * 0.2
local x = math.Clamp(GPhone.CursorPos.x + xchange, -40, 1168)
local y = math.Clamp(GPhone.CursorPos.y + ychange, -380, 2052)
GPhone.CursorPos = {x = x, y = y}
cmd:SetViewAngles( angle )
return true
end
end)
hook.Add("ShouldDrawLocalPlayer", "_GPhoneDrawSelfiePlayer", function(ply)
local wep = LocalPlayer():GetActiveWeapon()
if IsValid(wep) and wep:GetClass() == "gmod_gphone" and GPhone.SelfieEnabled() then
cam.Start3D()
cam.End3D()
if GPSelfieRendering then return true end
end
end)<file_sep>APP.Name = "Messages"
APP.Author = "Krede"
APP.Negative = false
APP.Icon = "asset://garrysmod/materials/gphone/apps/messages.png"
function APP.Run( frame, w, h, ratio )
function frame:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h, Color( 220, 220, 220, 255 ) )
end
frame.main = frame:AddTab( "main", "panel" )
frame.select = frame:AddTab( "select", "panel" )
frame.chat = frame:AddTab( "chat", "panel" )
function frame.OpenChat( id )
frame.id = id
frame.chat:Clear()
frame:OpenTab( "chat", 0.25, "in-right", "out-left" )
local messages = GPhone.GetAppData("messages") or {}
local data = messages[id] or {}
local scroll = GPnl.AddPanel( frame.chat, "scroll" )
scroll:SetPos( 12 * ratio, 64 * ratio )
scroll:SetSize( w - 24 * ratio, h - 128 * ratio )
local padding = 18 * ratio
local space = 0
-- Instantiate every message
for i = #data, 1, -1 do
local msg = data[i]
local text = GPhone.WordWrap(msg.text, w * 0.75, "GPSmall")
local textHeight = (4 + 36 * #text) * ratio
local textWidth = 0
surface.SetFont("GPSmall")
for k,v in pairs(text) do
local size = surface.GetTextSize(v)
if size > textWidth then
textWidth = size
end
end
-- TODO: Only load messages if they are "new", and don't worry about older ones
space = space + 12 * ratio + textHeight
local message = GPnl.AddPanel( scroll )
message:SetSize( textWidth + padding * 2, textHeight )
if msg.me then
message:SetPos( scroll:GetWidth() - message:GetWidth(), scroll:GetHeight() - space )
message.textColor = Color(255, 255, 255)
message.backColor = Color(6, 209, 74)
else
message:SetPos( 0, scroll:GetHeight() - space )
message.textColor = Color(70, 70, 70)
message.backColor = Color(200, 200, 200)
end
message.text = text
function message:Paint( x, y, w, h )
draw.RoundedBox( padding, 0, 0, w, h, self.backColor )
for k,v in pairs(self.text) do
draw.SimpleText(v, "GPSmall", padding, (4 + k * 36 - 36) * ratio, self.textColor, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
end
end
end
local input = GPnl.AddPanel( frame, "textentry" )
input:SetPos( 0, h - 64 * ratio )
input:SetSize( w, 64 * ratio )
input:SetFont( "GPSmall" )
input:SetForeColor( Color(70, 70, 70) )
input:SetBackColor( Color(255, 255, 255) )
input:SetAlignment( TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER )
function input:OnEnter( val )
local addUser = false
for _,ply in pairs(player.GetAll()) do
if ply:AccountID() == id then
addUser = true
end
end
if addUser then
GPhone.SendSharedData(LocalPlayer(), "messenger_send", { val })
local message = {
me = true,
text = val
}
local users = GPhone.GetAppData("messages") or {}
users[id] = users[id] or {}
table.insert(users[id], message)
GPhone.SetAppData("messages", users)
frame.OpenChat( frame.id )
end
end
local header = GPnl.AddPanel( frame.chat )
header:SetPos( 0, 0 )
header:SetSize( w, 64 * ratio )
header.id = id
function header:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText(self.id, "GPTitle", w/2, h/2, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
local back = GPnl.AddPanel( header )
back:SetPos( 0, 0 )
back:SetSize( 64 * ratio, 64 * ratio )
function back:OnClick()
frame.id = nil
frame.Main()
frame:OpenTab( "main", 0.25, "in-left", "out-right" )
end
function back:Paint( x, y, w, h )
draw.SimpleText("<", "GPTitle", w/2, h/2, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
end
-- Selection
local header = GPnl.AddPanel( frame.select )
header:SetPos( 0, 0 )
header:SetSize( w, 64 * ratio )
function header:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("Add phone number", "GPTitle", w/2, h/2, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
local add = GPnl.AddPanel( frame.select, "textentry" )
add:SetPos( 0, 76 * ratio )
add:SetSize( w, 60 * ratio )
add:SetFont( "GPMedium" )
add:SetForeColor( Color(70, 70, 70) )
add:SetBackColor( Color(255, 255, 255) )
add:SetAlignment( TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER )
function add:OnChange( val )
self:SetText(val)
end
function add:OnEnter( val )
local id = tonumber(val)
local addUser = false
for _,ply in pairs(player.GetAll()) do
if ply != LocalPlayer() and ply:AccountID() == id then
addUser = true
end
end
if addUser then
local users = GPhone.GetAppData("messages") or {}
users[id] = {}
GPhone.SetAppData("messages", users)
frame.OpenChat(id)
end
end
local back = GPnl.AddPanel( header )
back:SetPos( 0, 0 )
back:SetSize( 64 * ratio, 64 * ratio )
function back:OnClick()
frame.Main()
frame:OpenTab( "main", 0.25, "in-left", "out-right" )
end
function back:Paint( x, y, w, h )
draw.SimpleText("<", "GPTitle", w/2, h/2, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
-- Main page
function frame.Main()
frame.main:Clear()
local mar = (64 - 36) / 2 * ratio
local scroll = GPnl.AddPanel( frame.main, "scroll" )
scroll:SetPos( 0, 64 * ratio )
scroll:SetSize( w, h - 64 * ratio )
local users = GPhone.GetAppData("messages")
if users and table.Count(users) > 0 then
local i = 0
for id,_ in pairs(users) do
local user = GPnl.AddPanel( scroll )
user:SetSize( w, 64 * ratio )
user:SetPos( 0, (i * 64 + 12) * ratio )
user.id = id
function user:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText(self.id, "GPMedium", mar, h/2, Color(70, 70, 70), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
function user:OnClick()
frame.OpenChat( self.id )
end
local delete = GPnl.AddPanel( user )
delete:SetPos( w - 64 * ratio, 0 )
delete:SetSize( 64 * ratio, 64 * ratio )
function delete:OnClick()
local users = GPhone.GetAppData("messages")
users[id] = nil
GPhone.SetAppData("messages", users)
frame.Main()
end
function delete:Paint( x, y, w, h )
surface.SetDrawColor( 0, 0, 0 )
surface.SetTexture( surface.GetTextureID( "gui/html/stop" ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
i = i + 1
end
else
local empty = GPnl.AddPanel( scroll )
empty:SetSize( w, 64 * ratio )
empty:SetPos( 0, 12 * ratio )
function empty:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("No messages found", "GPMedium", mar, h/2, Color(70, 70, 70), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
function empty:OnClick()
frame.Main()
end
end
local header = GPnl.AddPanel( frame.main )
header:SetPos( 0, 0 )
header:SetSize( w, 64 * ratio )
function header:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("Messages", "GPTitle", w/2, h/2, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
local add = GPnl.AddPanel( header )
add:SetPos( w - 64 * ratio, 0 )
add:SetSize( 64 * ratio, 64 * ratio )
function add:OnClick()
frame:OpenTab( "select", 0.25, "in-right", "out-left" )
end
function add:Paint( x, y, w, h )
surface.SetDrawColor( 70, 70, 70 )
surface.SetTexture( surface.GetTextureID( "gphone/write" ) )
surface.DrawTexturedRect( 8, 8, w-16, h-16 )
end
end
frame.Main()
frame:OpenTab( "main" )
end
GPhone.HookSharedData("messenger_send", function(ply, name, data)
local message = {
me = false,
text = data[1]
}
local id = ply:AccountID()
local users = GPhone.GetAppData("messages", {}, "messenger")
users[id] = users[id] or {}
table.insert(users[id], message)
GPhone.SetAppData("messages", users, "messenger")
local frame = GPhone.Panels["messenger"]
if frame:GetOpenTab() == frame.chat then
frame.OpenChat( frame.id )
end
end)<file_sep>[](http://gphone.icu)
# GPhone
"Are you tired of having to equip your camera every time you want to take a picture?
Would you rather have an App that does virtually the same thing but more complicated?
Well then I present to you, the GPhone (Remade)!
The GPhone features some of the basic abilities from the original IPhone 4, excluding the most essential ofcourse!
Listen to music, browse the internet, execute order 66 and much more! (You can't actually be the senate, yet)
Get yours today, for the low, low price of eternal subscription. What a deal!
Batteries not included."
## Links
* [Workshop](https://steamcommunity.com/sharedfiles/filedetails/?id=1370983401)
* [Website](http://gphone.icu)
* [App Uploader](http://gphone.icu/appcreator)
* [App Creation](https://github.com/KredeGC/GPhone/wiki)
## Credits
* Krede/Author - Coding everything.
* <NAME> - Being dead.
* <NAME> - Starting the trend of putting his name on everything.
<file_sep>-- Loading
util.AddNetworkString("GPhone_Load_Client")
util.AddNetworkString("GPhone_Load_Apps")
-- Data
util.AddNetworkString("GPhone_Change_Data")
util.AddNetworkString("GPhone_Share_Data")
-- Misc
util.AddNetworkString("GPhone_Reset")
util.AddNetworkString("GPhone_Equip")
util.AddNetworkString("GPhone_Rotate")
util.AddNetworkString("GPhone_Selfie")
util.AddNetworkString("GPhone_Music")
util.AddNetworkString("GPhone_Case")
util.AddNetworkString("GPhone_VR")
-- Voicecall
util.AddNetworkString("GPhone_VoiceCall_Request")
util.AddNetworkString("GPhone_VoiceCall_Answer")
util.AddNetworkString("GPhone_VoiceCall_Stop")
resource.AddFile("materials/vgui/entities/gmod_gphone.vmt")
resource.AddFile("materials/vgui/hud/phone.vmt")
resource.AddFile("materials/models/weapons/c_garry_phone.vmt")
resource.AddFile("models/weapons/c_garry_phone.mdl")
resource.AddFile("models/nitro/iphone4.mdl")
local function addResources(dir)
local files,dirs = file.Find(dir.."/*", "GAME")
for _,v in pairs(files) do
resource.AddSingleFile(dir.."/"..v)
end
for _,v in pairs(dirs) do
addResources(dir.."/"..v)
end
end
addResources("materials/gphone")
addResources("materials/models/nitro")
addResources("sound/gphone")
local function resetGPhoneData(ply, id)
local data = table.Copy(GPDefaultData)
file.Write("gphone/users/"..id..".txt", util.TableToJSON(data))
net.Start("GPhone_Load_Client")
net.WriteTable(data)
net.Send(ply)
end
if GetConVar("gphone_spawn"):GetBool() then
hook.Add("PlayerLoadout", "GPhoneSpawn", function(ply)
ply:Give("gmod_gphone")
end)
end
hook.Add("PlayerAuthed", "GPhoneLoadClientData", function(ply, stid)
local id = util.SteamIDTo64(ply:SteamID())
local cv = GetConVar("gphone_sync")
if game.SinglePlayer() or cv and cv:GetBool() then
net.Start("GPhone_Load_Client")
net.WriteTable({})
net.Send(ply)
elseif file.Exists("gphone/users/"..id..".txt", "DATA") then
local tbl = util.JSONToTable(file.Read("gphone/users/"..id..".txt", "DATA"))
if !tbl then
resetGPhoneData(ply, id)
return
end
local apps = {}
for _,id in pairs(GPDefaultApps) do -- Fix default apps
if !table.HasValue(tbl.apps, id) then
table.insert(apps, id)
end
end
if #apps > 0 then
table.Add(tbl.apps, apps)
file.Write("gphone/users/"..id..".txt", util.TableToJSON(tbl))
print("[GPhone] Added "..#apps.." missing default apps for "..ply:Nick())
end
net.Start("GPhone_Load_Client")
net.WriteTable(tbl)
net.Send(ply)
else
resetGPhoneData(ply, id)
end
end)
hook.Add("PlayerCanHearPlayersVoice", "GPhonePlayerVoiceChat", function(p1, p2)
if p1.GPhoneVC and p2.GPhoneVC and p1 != p2 then
return p1.GPhoneVC == p2 and p2.GPhoneVC == p1
elseif p1.GPhoneVC and !p2.GPhoneVC or !p1.GPhoneVC and p2.GPhoneVC then
return false
end
end)
net.Receive("GPhone_VR", function(len, ply)
local wep = ply:GetActiveWeapon()
if wep:GetClass() == "gmod_gphone" then
ply:GetViewModel():SetWeaponModel("models/nitro/iphone4.mdl", wep)
end
end)
net.Receive("GPhone_Change_Data", function(len, ply)
local cv = GetConVar("gphone_sync")
if !game.SinglePlayer() and (cv or !cv:GetBool()) then
local str = net.ReadTable()
local id = util.SteamIDTo64(ply:SteamID())
file.Write("gphone/users/"..id..".txt", util.TableToJSON(str))
end
end)
net.Receive("GPhone_Share_Data", function(len, ply)
if !GPShareData then return end
local receiver = net.ReadEntity()
local name = net.ReadString()
local data = net.ReadTable()
if receiver == ply then return end
-- Networking should be off by default as to not spam the user
-- Add a blacklist so people won't be spammed
-- if receiver.GPBlacklist[ply] then return end
-- Add as an option for travel-time effect
-- timer.Simple(receiver.GPConnection + ply.GPConnection, function() end)
net.Start("GPhone_Share_Data")
net.WriteEntity(ply)
net.WriteString(name)
net.WriteTable(data)
net.Send(receiver)
end)
net.Receive("GPhone_Reset", function(len, ply)
local cv = GetConVar("gphone_sync")
if !game.SinglePlayer() and (cv or !cv:GetBool()) then
local id = util.SteamIDTo64(ply:SteamID())
resetGPhoneData(ply, id)
end
end)
net.Receive("GPhone_VoiceCall_Request", function(len, ply)
local chatter = net.ReadEntity()
if !IsValid(chatter) or !chatter:IsPlayer() or chatter == ply then return end
ply.GPhoneVC = chatter
net.Start("GPhone_VoiceCall_Request")
net.WriteEntity(ply)
net.Send(chatter)
end)
net.Receive("GPhone_VoiceCall_Answer", function(len, ply)
local chatter = net.ReadEntity()
local accept = net.ReadBool()
if !IsValid(chatter) or !chatter:IsPlayer() or chatter == ply or chatter.GPhoneVC != ply then return end
if accept then
ply.GPhoneVC = chatter
else
chatter.GPhoneVC = false
net.Start("GPhone_VoiceCall_Stop")
net.Send(chatter)
end
end)
net.Receive("GPhone_VoiceCall_Stop", function(len, ply)
local chatter = ply.GPhoneVC
if IsValid(chatter) and chatter:IsPlayer() and chatter != ply and chatter.GPhoneVC == ply then
chatter.GPhoneVC = false
end
ply.GPhoneVC = false
end)
net.Receive("GPhone_Selfie", function(len, ply)
local bool = net.ReadBool()
ply:SetNWBool("GPSelfie", bool)
end)
net.Receive("GPhone_Music", function(len, ply)
local bool = net.ReadBool()
ply:SetNWBool("GPMusic", bool)
end)
net.Receive("GPhone_Case", function(len, ply)
local case = net.ReadString()
ply:SetNWString("PhoneCase", case)
end)<file_sep>APP.Name = "GTunes"
APP.Author = "Krede"
APP.Negative = true
APP.Icon = "asset://garrysmod/materials/gphone/apps/gtunes.png"
function APP.Run( frame, w, h, ratio )
function frame:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h, Color( 50, 50, 50, 255 ) )
end
frame.Scroll = GPnl.AddPanel( frame, "scroll" )
frame.Scroll:SetPos( 0, 64 * ratio )
frame.Scroll:SetSize( w, h - (64 + 140) * ratio )
function frame:Open( path )
GPhone.MusicURL = path
GPhone.StartMusic( path )
end
function frame:ResetMusic()
frame.Scroll:Clear()
local music = GPhone.GetAppData("music", {})
for num,url in pairs(music) do
local song = GPnl.AddPanel( self.Scroll )
song:SetSize( w, 42 * ratio )
song:SetPos( 0, (num*42 - 36) * ratio )
song.url = url
function song:Paint( x, y, w, h )
if GPhone.MusicURL == self.url or GPhone.MusicURL == "sound/"..self.url then
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 100, 100, 200, 255 ) )
else
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 60, 60, 150, 255 ) )
end
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 25, 25, 100, 255 ) )
if !self.url then return end
surface.SetFont("GPMedium")
local s = surface.GetTextSize(self.url)
if s > w + h then
draw.SimpleText(self.url, "GPMedium", w - h, h/2, Color(255,255,255), TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER)
else
draw.SimpleText(self.url, "GPMedium", 4, h/2, Color(255,255,255), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
end
function song:OnClick( held )
if held then
local _,y = GPhone.RootToLocal( self, GPhone.GetCursorPos() )
frame.b_move = self
frame.b_rel = y
else
GPhone.MusicURL = self.url
end
end
local size = 42 * ratio
local delete = GPnl.AddPanel( song )
delete:SetPos( w - size, 0 )
delete:SetSize( size, size )
function delete:OnClick()
local music = GPhone.GetAppData("music")
if table.HasValue(music, delete:GetParent().url) then
table.RemoveByValue(music, delete:GetParent().url)
end
GPhone.SetAppData("music", music)
frame:ResetMusic()
end
function delete:Paint( x,y,w,h )
surface.SetDrawColor(255, 255, 255)
surface.SetTexture( surface.GetTextureID( "gui/html/stop" ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
end
end
frame:ResetMusic()
local footer = GPnl.AddPanel( frame )
footer:SetPos( 0, h - 140 * ratio )
footer:SetSize( w, 140 * ratio )
function footer:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 2, w, h-2, Color( 45, 45, 125, 255 ) )
draw.RoundedBox( 0, 0, 0, w, 2, Color( 25, 25, 100, 255 ) )
local music = GPhone.MusicStream
if music and music.Channel and music.Length then
local mx,my = GPhone.GetCursorPos()
if mx >= x and my >= y and mx <= x + w and my <= y + h then
local p = math.Clamp((mx - 4 * ratio) / (w - 8 * ratio), 0, 1)
local time = p * music.Length
draw.SimpleText(string.FormattedTime( time, "%02i:%02i" ), "GPSmall", mx - (p*2-1) * 20 * ratio, h - 16 * ratio, Color(230, 230, 230), TEXT_ALIGN_CENTER, TEXT_ALIGN_BOTTOM)
draw.SimpleText(string.FormattedTime( music.Channel:GetTime(), "%02i:%02i" ), "GPSmall", 4 * ratio, h - 16 * ratio, Color(230, 230, 230, 255*p), TEXT_ALIGN_LEFT, TEXT_ALIGN_BOTTOM)
draw.SimpleText(string.FormattedTime( music.Length, "%02i:%02i" ), "GPSmall", w - 4 * ratio, h - 16 * ratio, Color(230, 230, 230, 255*(1-p)), TEXT_ALIGN_RIGHT, TEXT_ALIGN_BOTTOM)
else
draw.SimpleText(string.FormattedTime( music.Channel:GetTime(), "%02i:%02i" ), "GPSmall", 4 * ratio, h - 16 * ratio, Color(230, 230, 230), TEXT_ALIGN_LEFT, TEXT_ALIGN_BOTTOM)
draw.SimpleText(string.FormattedTime( music.Length, "%02i:%02i" ), "GPSmall", w - 4 * ratio, h - 16 * ratio, Color(230, 230, 230), TEXT_ALIGN_RIGHT, TEXT_ALIGN_BOTTOM)
end
end
local text = GPhone.GetInputText() or music.URL or GPhone.MusicURL
if text then
surface.SetFont("GPMedium")
local size = surface.GetTextSize(text)
if size > w then
draw.SimpleText(text, "GPMedium", w/2 + (size/2 - w/2 + 4 * ratio)*math.sin(RealTime()), 4, Color(230,230,230), TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP)
else
draw.SimpleText(text, "GPMedium", w/2, 4, Color(230,230,230), TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP)
end
end
end
local stop = GPnl.AddPanel( footer )
stop:SetPos( w/2 - 96 * ratio, 46 * ratio )
stop:SetSize( 48 * ratio, 48 * ratio )
function stop:OnClick()
GPhone.StopMusic()
end
function stop:Paint( x, y, w, h )
if GPhone.MusicStream and GPhone.MusicStream.Channel then
surface.SetDrawColor(255, 255, 255)
surface.SetTexture( surface.GetTextureID( "gphone/stop" ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
end
local start = GPnl.AddPanel( footer )
start:SetPos( w/2 - 32 * ratio, 46 * ratio )
start:SetSize( 48 * ratio, 48 * ratio )
function start:OnClick()
if GPhone.MusicStream and GPhone.MusicStream.Channel then
GPhone.ToggleMusic()
elseif GPhone.MusicURL then
GPhone.StartMusic( GPhone.MusicURL )
end
end
function start:Paint( x, y, w, h )
if GPhone.MusicStream and type(GPhone.MusicStream) == "table" and GPhone.MusicStream.Playing then
surface.SetDrawColor(255, 255, 255)
surface.SetTexture( surface.GetTextureID( "gphone/pause" ) )
surface.DrawTexturedRect( 0, 0, w, h )
else
surface.SetDrawColor(255, 255, 255)
surface.SetTexture( surface.GetTextureID( "gphone/play" ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
end
local timeslider = GPnl.AddPanel( footer )
timeslider:SetPos( 4 * ratio, footer:GetHeight() - 12 * ratio )
timeslider:SetSize( footer:GetWidth() - 8 * ratio, 8 * ratio )
function timeslider:OnClick()
local music = GPhone.MusicStream
if !music or !music.Channel then return end
local channel = music.Channel
local x = GPhone.GetCursorPos()
local w = timeslider:GetWidth()
local p = (x - ratio * 4) / w
channel:SetTime( p * music.Length )
end
function timeslider:Paint( x, y, w, h )
local music = GPhone.MusicStream
if music and music.Channel then
local p = (music.Channel:GetTime()/music.Length)
draw.RoundedBox( 0, w*p, 0, w*(1-p), h, Color( 230, 230, 230, 255 ) )
draw.RoundedBox( 0, 0, 0, w*p, h, Color( 85, 85, 200, 255 ) )
end
end
local header = GPnl.AddPanel( frame )
header:SetPos( 0, 0 )
header:SetSize( w, 64 * ratio )
function header:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 60, 60, 150, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 25, 25, 100, 255 ) )
draw.SimpleText("GTunes", "GPTitle", w/2, h/2, Color(230, 230, 230), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
local rep = GPnl.AddPanel( header )
rep:SetPos( 0, 0 )
rep:SetSize( 64 * ratio, 64 * ratio )
function rep:OnClick()
GPhone.SetAppData("repeat", !GPhone.GetAppData("repeat", false))
end
function rep:Paint( x, y, w, h )
if GPhone.GetAppData("repeat", false) then
surface.SetDrawColor(0, 255, 0)
else
surface.SetDrawColor(255, 255, 255)
end
surface.SetTexture( surface.GetTextureID( "gui/html/refresh" ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
local add = GPnl.AddPanel( header )
add:SetPos( w - 64 * ratio, 0 )
add:SetSize( 64 * ratio, 64 * ratio )
function add:OnClick()
local function onEnter( val )
GPhone.MusicURL = val
local music = GPhone.GetAppData("music") or {}
if !table.HasValue(music, val) then
table.insert(music, val)
GPhone.SetAppData("music", music)
end
frame:ResetMusic()
GPhone.StartMusic( GPhone.MusicURL )
end
GPhone.InputText( onEnter )
end
function add:Paint( x, y, w, h )
surface.SetDrawColor( 255, 255, 255 )
surface.SetTexture( surface.GetTextureID( "gphone/write" ) )
surface.DrawTexturedRect( 8, 8, w-16, h-16 )
end
end
function APP.Think( frame, w, h, ratio )
if frame.b_move then
local _,my = GPhone.RootToLocal( frame.b_move, GPhone.GetCursorPos() )
local _,cy = frame.b_move:GetPos()
local y = math.Clamp(my + cy - (frame.b_rel or 0), 0, frame.b_move:GetParent():GetHeight() - frame.b_move:GetHeight())
frame.b_move:SetPos( 0, y )
if !input.IsMouseDown( MOUSE_LEFT ) then
local music = GPhone.GetAppData("music", {})
local pos = 0
local last = 1
local children = frame.Scroll:GetChildren()
for k,v in pairs(children) do
if v == frame.b_move then pos = k end
local _,py = v:GetPos()
if y > py then
last = k
end
end
if pos > 0 and pos != last then
local song = music[pos]
table.remove(music, pos)
table.insert(music, last, song)
GPhone.SetAppData("music", music)
end
frame:ResetMusic()
frame.b_move = nil
frame.b_rel = nil
end
end
end
hook.Add("Think", "GTunesRepeat", function()
local music = GPhone.GetMusic()
if GPhone.GetAppData("repeat", false, "gtunes") and music then
local channel = music.Channel
if channel:GetState() == GMOD_CHANNEL_STOPPED then
channel:Play()
end
end
end)<file_sep>APP.Name = "Notes"
APP.Author = "Krede"
APP.Negative = true
APP.Icon = "asset://garrysmod/materials/gphone/apps/notes.png"
function APP.Run( frame, w, h, ratio )
function frame:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, 62 * ratio, Color( 77, 54, 41, 255 ) )
draw.RoundedBox( 0, 0, 62 * ratio, w, 2 * ratio, Color( 80, 80, 80, 255 ) )
draw.RoundedBox( 0, 0, 64 * ratio, w, h - 64 * ratio, Color( 247, 244, 180, 255 ) )
end
function frame.Open( ind )
frame:Clear()
local notes = GPhone.GetAppData("notes") or {}
local num = ind or table.Count(notes) + 1
local data = notes[ind] or {}
local text = GPnl.AddPanel( frame, "textentry" )
text:SetPos( 0, 64 * ratio )
text:SetSize( w, h - 64 * ratio )
text:SetFont( "GPMedium" )
text:SetBackColor( Color(0, 0, 0, 0) )
text:SetText( data.text )
text:SetAlignment( TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP )
function text:OnEnter( val )
self:SetText(val)
local notes = GPhone.GetAppData("notes") or {}
local note = notes[num] or {title = "Untitled", text = ""}
note.text = val
notes[num] = note
GPhone.SetAppData("notes", notes)
end
local header = GPnl.AddPanel( frame, "textentry" )
header:SetPos( 0, 0 )
header:SetSize( w, 64 * ratio )
header:SetFont( "GPTitle" )
header:SetForeColor( Color(255, 255, 255) )
header:SetBackColor( Color(0, 0, 0, 0) )
header:SetText( data.title or "Untitled" )
header:SetAlignment( TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER )
function header:OnEnter( val )
header:SetText(val)
local notes = GPhone.GetAppData("notes") or {}
local note = notes[num] or {title = "", text = ""}
note.title = val
notes[num] = note
GPhone.SetAppData("notes", notes)
end
local back = GPnl.AddPanel( header )
back:SetPos( 0, 0 )
back:SetSize( 64 * ratio, 64 * ratio )
function back:OnClick()
frame.Main()
end
function back:Paint( x, y, w, h )
draw.SimpleText("<", "GPTitle", w/2, h/2, Color(255, 255, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
end
function frame.Main()
frame:Clear()
local scroll = GPnl.AddPanel( frame, "scroll" )
scroll:SetPos( 0, 64 * ratio )
scroll:SetSize( w, h - 64 * ratio )
local notes = GPhone.GetAppData("notes")
if notes then
for num,data in pairs(notes) do
local note = GPnl.AddPanel( scroll )
note:SetSize( w, 40 * ratio )
note:SetPos( 0, (num*40 - 34) * ratio )
note.num = num
note.data = data
function note:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 77, 54, 41, 255 ) )
local title = note.data.title or "Untitled"
surface.SetFont("GPMedium")
local s = surface.GetTextSize(title)
if s > w-40 then
draw.SimpleText(title, "GPMedium", w-40, h/2, Color(0, 0, 0), TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER)
else
draw.SimpleText(title, "GPMedium", 4, h/2, Color(0, 0, 0), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
end
function note:OnClick()
frame.Open( note.num )
end
local delete = GPnl.AddPanel( note )
delete:SetPos( w - 40 * ratio, 0 )
delete:SetSize( 40 * ratio, 40 * ratio )
function delete:OnClick()
local notes = GPhone.GetAppData("notes")
table.remove(notes, delete:GetParent().num)
GPhone.SetAppData("notes", notes)
frame.Main()
end
function delete:Paint( x, y, w, h )
surface.SetDrawColor( 0, 0, 0 )
surface.SetTexture( surface.GetTextureID( "gui/html/stop" ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
end
end
local header = GPnl.AddPanel( frame )
header:SetPos( 0, 0 )
header:SetSize( w, 64 * ratio )
function header:Paint( x, y, w, h )
draw.SimpleText("Notes", "GPTitle", w/2, h/2, Color(255, 255, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
local add = GPnl.AddPanel( header )
add:SetPos( w - 64 * ratio, 0 )
add:SetSize( 64 * ratio, 64 * ratio )
function add:OnClick()
frame.Open()
end
function add:Paint( x, y, w, h )
surface.SetDrawColor( 255, 255, 255 )
surface.SetTexture( surface.GetTextureID( "gphone/write" ) )
surface.DrawTexturedRect( 8, 8, w-16, h-16 )
end
end
frame.Main()
end<file_sep>APP.Name = "AppStore"
APP.Author = "Krede"
APP.Icon = "asset://garrysmod/materials/gphone/apps/appstore.png"
function APP.Run( frame, w, h, ratio )
function frame:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h, Color(220, 220, 220, 255) )
end
frame.page = nil
frame.title = "Local Apps"
frame.online = {}
local function loadAppPage( name, app, click )
frame.b_hover = nil
frame.title = app.Name
local page = GPnl.AddPanel( frame, "panel" )
page:SetPos( 0, 64 * ratio )
page:SetSize( w, h - 128 * ratio )
page.App = name
page.Name = app.Name
page.Author = app.Author
frame.page = page
function page:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, 144 * ratio, w, 2, Color(80, 80, 80, 255) )
draw.SimpleText(self.Name, "GPTitle", 144 * ratio, 24 * ratio, Color(70, 70, 70), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
draw.SimpleText("By "..(self.Author or "N/A"), "GPMedium", 144 * ratio, 72 * ratio, Color(160, 160, 160), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
if app.Rating then
local rating = GPnl.AddPanel( page )
rating:SetSize( 24 * 5 * ratio, 24 * ratio )
rating:SetPos( 144 * ratio, 108 * ratio )
rating.Rating = app.Rating
rating.App = app.App
rating.Id = app.Id
function rating:Paint( x, y, w, h )
local mx,my = GPhone.GetCursorPos()
local votes = self.Rating
if mx >= x and my >= y and mx <= x + w and my <= y + h then
votes = math.Clamp( math.ceil( (mx - x) / w * 5 ), 1, 5 )
end
local rate = votes / 5
local last = math.floor(votes)
surface.SetDrawColor( 255 * (1 - rate), 255 * rate, 0 )
surface.SetTexture( surface.GetTextureID("gphone/dot_empty") )
for i = 0, 4 do
surface.DrawTexturedRect( i * h, 0, h, h )
end
surface.SetTexture( surface.GetTextureID("gphone/dot_full") )
for i = 0, last do
if i == last then
local p = votes - last
surface.DrawTexturedRectUV( i * h, 0, h * p, h, 0, 0, p, 1 )
else
surface.DrawTexturedRect( i * h, 0, h, h )
end
end
end
function rating:OnClick()
local x = GPhone.RootToLocal( self, GPhone.GetCursorPos() )
local rate = math.Clamp( math.ceil( x / self:GetWidth() * 5 ), 1, 5 )
http.Post("https://gphone.icu/api/vote",
{
id = self.Id,
app = self.App,
vote = tostring(rate)
},
function( body, len, headers, code )
print("[GPhone] "..body)
end,
function( err )
print("[GPhone] "..err)
return false
end
)
end
end
local icon = GPnl.AddPanel( page )
icon:SetSize( 128 * ratio, 128 * ratio )
icon:SetPos( 8 * ratio, 8 * ratio )
icon.Icon = app.Icon
function icon:Paint( x, y, w, h )
surface.SetDrawColor( 255, 255, 255 )
surface.SetMaterial( GPhone.GetImage( self.Icon ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
local install = GPnl.AddPanel( page )
install:SetSize( 120 * ratio, 40 * ratio )
install:SetPos( w - (120 + 25) * ratio, 52 * ratio )
install.clicked = false
function install:Paint( x, y, w, h )
draw.RoundedBox(0, 0, 0, w, h, Color(15, 200, 90))
draw.RoundedBox(0, 4, 4, w-8, h-8, Color(255, 255, 255))
local text = table.HasValue(GPhone.Data.apps, page.App) and "Uninstall" or self.clicked and "Installing" or "Install"
draw.SimpleText(text, "GPMedium", w/2, h/2, Color(15, 200, 90), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
function install:OnClick()
self.clicked = true
click( page, self )
end
if app.Id then
local author = GPnl.AddPanel( page )
author:SetSize( w - 16 * ratio, 40 * ratio )
author:SetPos( 8 * ratio, (128 + 26) * ratio )
function author:Paint( x, y, w, h )
draw.RoundedBox(0, 0, 0, w, h, Color(15, 200, 90))
draw.RoundedBox(0, 4, 4, w-8, h-8, Color(255, 255, 255))
draw.SimpleText("View author", "GPMedium", w/2, h/2, Color(15, 200, 90), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
function author:OnClick()
gui.OpenURL("https://steamcommunity.com/profiles/"..app.Id)
end
local view = GPnl.AddPanel( page )
view:SetSize( w - 16 * ratio, 40 * ratio )
view:SetPos( 8 * ratio, (128 + 74) * ratio )
function view:Paint( x, y, w, h )
draw.RoundedBox(0, 0, 0, w, h, Color(15, 200, 90))
draw.RoundedBox(0, 4, 4, w-8, h-8, Color(255, 255, 255))
draw.SimpleText("View code", "GPMedium", w/2, h/2, Color(15, 200, 90), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
function view:OnClick()
local f = vgui.Create( "DFrame" )
f:SetSize(ScrW() * 0.7, ScrH() * 0.7)
f:SetTitle("")
f:SetDraggable( false )
f:ShowCloseButton( true )
f:SetSizable( false )
f:MakePopup()
f:Center()
function f:Paint(w, h)
surface.SetDrawColor(255, 255, 255)
surface.DrawRect(0, 0, w, h)
draw.SimpleText("Sourcecode for "..app.Name.." by "..app.Author, "GPAppBuilder", 0, 0, Color(0, 0, 0), TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
end
local code = vgui.Create("DTextEntry", f)
code:SetText( "" )
code:Dock( FILL )
code:SetVerticalScrollbarEnabled( true )
code:SetDrawLanguageID( false )
code:SetMultiline( true )
code:SetPlaceholderText( "Loading..." )
function code:AllowInput()
return true
end
http.Fetch("https://gphone.icu/api/list?app="..app.App.."&id="..app.Id, function(body, size, headers)
code:SetText(string.gsub(body, " ", " "))
end,
function(err)
print(err)
end)
end
end
end
local function addbutton(name, app, click)
local but = GPnl.AddPanel()
but:SetSize( w, 110 * ratio )
but:SetPos( 0, 0 )
but.Name = app.Name
but.App = name
but.Author = app.Author
function but:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color(255, 255, 255, 255) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color(80, 80, 80, 255) )
draw.SimpleText(self.Name, "GPMedium", h + 4, 4, Color(70, 70, 70), TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
draw.SimpleText("By "..(self.Author or "N/A"), "GPSmall", h + 4, h/2, Color(160, 160, 160), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
function but:OnClick()
loadAppPage(name, app, click)
end
local icon = GPnl.AddPanel( but )
icon:SetSize( 102 * ratio, 102 * ratio )
icon:SetPos( 4 * ratio, 4 * ratio )
icon.Icon = app.Icon
function icon:Paint( x, y, w, h )
surface.SetDrawColor( 255, 255, 255 )
surface.SetMaterial( GPhone.GetImage( self.Icon ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
function icon:OnClick()
loadAppPage(name, app, click)
end
local install = GPnl.AddPanel( but )
install:SetSize( 120 * ratio, 40 * ratio )
install:SetPos( w - (120 + 25) * ratio, 35 * ratio )
install.clicked = false
function install:Paint( x, y, w, h )
draw.RoundedBox(0, 0, 0, w, h, Color(15, 200, 90))
draw.RoundedBox(0, 4, 4, w-8, h-8, Color(255, 255, 255))
local text = table.HasValue(GPhone.Data.apps, but.App) and "Uninstall" or self.clicked and "Installing" or "Install"
draw.SimpleText(text, "GPMedium", w/2, h/2, Color(15, 200, 90), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
function install:OnClick()
self.clicked = true
click( but, self )
end
return but
end
local function addOnlineButton(name, app, click)
local url = "https://gphone.icu/api/list?app="..app.App.."&id="..app.Id
local name = GPhone.SerializeAppName(url)
local but = addbutton(name, app, function(but)
click( but, self )
end)
but.URL = url
if app.Rating then
local rating = GPnl.AddPanel( but )
rating:SetSize( 24 * 5 * ratio, 24 * ratio )
rating:SetPos( 110 * ratio + 4, (110 - 28) * ratio - 4 )
rating.Rating = app.Rating
rating.App = app.App
rating.Id = app.Id
function rating:Paint( x, y, w, h )
local mx,my = GPhone.GetCursorPos()
local votes = self.Rating
if mx >= x and my >= y and mx <= x + w and my <= y + h then
votes = math.Clamp( math.ceil( (mx - x) / w * 5 ), 1, 5 )
end
local rate = votes / 5
local last = math.floor(votes)
surface.SetDrawColor( 255 * (1-rate), 255 * rate, 0 )
surface.SetTexture( surface.GetTextureID("gphone/dot_empty") )
for i = 0, 4 do
surface.DrawTexturedRect( i * h, 0, h, h )
end
surface.SetTexture( surface.GetTextureID("gphone/dot_full") )
for i = 0, last do
if i == last then
local p = votes - last
surface.DrawTexturedRectUV( i * h, 0, h * p, h, 0, 0, p, 1 )
else
surface.DrawTexturedRect( i * h, 0, h, h )
end
end
end
function rating:OnClick()
local x = GPhone.RootToLocal( self, GPhone.GetCursorPos() )
local rate = math.Clamp( math.ceil( x / self:GetWidth() * 5 ), 1, 5 )
http.Post("https://gphone.icu/api/vote",
{
id = self.Id,
app = self.App,
vote = tostring(rate)
},
function( body, len, headers, code )
print("[GPhone] "..body)
end,
function( err )
print("[GPhone] "..err)
return false
end
)
end
end
if table.HasValue(GPhone.Data.apps, but.App) and app.Update then
local update = GPnl.AddPanel( but )
update:SetSize( 100 * ratio, 40 * ratio )
update:SetPos( w - (120 * 2 + 25) * ratio, 35 * ratio )
function update:Paint( x, y, w, h )
draw.RoundedBox(0, 0, 0, w, h, Color(15, 200, 90))
draw.RoundedBox(0, 4, 4, w-8, h-8, Color(255, 255, 255))
draw.SimpleText("Update", "GPMedium", w/2, h/2, Color(15, 200, 90), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
function update:OnClick()
GPhone.DownloadApp( but.URL )
self:Remove()
app.Update = nil
end
end
return but
end
local panel = GPnl.AddPanel( frame, "frame" )
panel:SetPos( 0, 64 * ratio )
panel:SetSize( w, h - 128 * ratio )
local offline = panel:AddTab( "offline", "scroll" )
offline:SetPos( 0, 0 )
offline:SetSize( panel:GetSize() )
function offline:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h, Color(220, 220, 220, 255) )
end
local count = -1
for name,app in pairs(GPhone.GetApps()) do
if GPDefaultApps and table.HasValue(GPDefaultApps, name) then continue end
if file.Exists("gphone/apps/"..name..".txt", "DATA") then continue end
count = count + 1
local but = addbutton(name, app, function(but)
if table.HasValue(GPhone.Data.apps, but.App) then
GPhone.UninstallApp( but.App )
else
GPhone.InstallApp( but.App )
end
end)
but:SetParent( offline )
but:SetPos( 0, ( count * 110 + 6 ) * ratio )
end
local online = panel:AddTab( "online", "scroll" )
online:SetPos( 0, 0 )
online:SetSize( panel:GetSize() )
function online:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h, Color(220, 220, 220, 255) )
end
local function loadOnlineApps()
online:Clear()
local count = -1
for _,app in pairs(frame.online) do
count = count + 1
local but = addOnlineButton(name, app, function(but)
if table.HasValue(GPhone.Data.apps, but.App) then
GPhone.UninstallApp( but.App )
app.Update = false
else
GPhone.DownloadApp( but.URL )
end
end)
but:SetParent( online )
but:SetPos( 0, ( count * 110 + 6 ) * ratio )
end
end
local updates = panel:AddTab( "updates", "scroll" )
updates:SetPos( 0, 0 )
updates:SetSize( panel:GetSize() )
function updates:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h, Color(220, 220, 220, 255) )
end
local function loadUpdateApps()
updates:Clear()
local count = -1
for _,app in pairs(frame.online) do
if !app.Update then continue end
count = count + 1
local but = addOnlineButton(name, app, function(but)
if table.HasValue(GPhone.Data.apps, but.App) then
GPhone.UninstallApp( but.App )
app.Update = false
else
GPhone.DownloadApp( but.URL )
end
end)
but:SetParent( updates )
but:SetPos( 0, ( count * 110 + 6 ) * ratio )
end
end
panel:OpenTab( "offline" )
local header = GPnl.AddPanel( frame )
header:SetPos( 0, 0 )
header:SetSize( w, 64 * ratio )
function header:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
local text = GPhone.GetInputText() or frame.title or "AppStore"
if text then
surface.SetFont("GPTitle")
local size = surface.GetTextSize(text)
if size > w - 64 then
draw.SimpleText(text, "GPTitle", w - 64, h/2, Color(0, 0, 0), TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER)
else
draw.SimpleText(text, "GPTitle", w/2, h/2, Color(0, 0, 0), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
end
end
local add = GPnl.AddPanel( header )
add:SetPos( w - 64 * ratio, 0 )
add:SetSize( 64 * ratio, 64 * ratio )
add:SetVisible(false)
function add:OnClick()
local function onEnter( value )
GPhone.DownloadApp( value )
end
GPhone.InputText( onEnter, nil, nil )
end
function add:Paint( x, y, w, h )
draw.SimpleText("+", "GPTitle", w/2, h/2, Color(0, 0, 0), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
local footer = GPnl.AddPanel( frame )
footer:SetPos( 0, h - 64 * ratio )
footer:SetSize( w, 64 * ratio )
function footer:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, 2, Color( 80, 80, 80, 255 ) )
draw.RoundedBox( 0, 0, 2, w, h-2, Color( 255, 255, 255, 255 ) )
end
local offtab = GPnl.AddPanel( footer )
offtab:SetPos( 0, 0 )
offtab:SetSize( 64 * ratio, 64 * ratio )
frame.b_hover = offtab
function offtab:Paint( x, y, w, h )
if frame.b_hover == self then
surface.SetDrawColor(0, 200, 255)
else
surface.SetDrawColor(50, 50, 50)
end
surface.SetTexture( surface.GetTextureID( "gui/html/stop" ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
function offtab:OnClick()
add:SetVisible(false)
if frame.page then
frame.page:Remove()
end
frame.b_hover = self
frame.title = "Local Apps"
panel:OpenTab( "offline", 0.25, "in-right", "out-right" )
end
local ontab = GPnl.AddPanel( footer )
ontab:SetPos( w/2 - 32 * ratio, 0 )
ontab:SetSize( 64 * ratio, 64 * ratio )
function ontab:Paint( x, y, w, h )
surface.SetDrawColor(50, 50, 50)
surface.SetTexture( surface.GetTextureID( "gphone/wifi_3" ) )
surface.DrawTexturedRect( 0, 0, w, h )
if frame.b_hover == self then
surface.SetDrawColor(0, 200, 255)
surface.SetTexture( surface.GetTextureID( "gphone/wifi_"..math.Round(math.sin(CurTime() * 3) + 2) ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
end
function ontab:OnClick()
if GetConVar("gphone_csapp"):GetBool() then
add:SetVisible(true)
end
if frame.page then
frame.page:Remove()
end
frame.b_hover = self
frame.title = "Online Apps"
panel:OpenTab( "online", 0.25, "in-right", "out-right" )
end
local uptab = GPnl.AddPanel( footer )
uptab:SetPos( w - 64 * ratio, 0 )
uptab:SetSize( 64 * ratio, 64 * ratio )
function uptab:Paint( x, y, w, h )
if frame.b_hover == self then
surface.SetDrawColor(0, 200, 255)
else
surface.SetDrawColor(50, 50, 50)
end
surface.SetTexture( surface.GetTextureID( "gui/html/home" ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
function uptab:OnClick()
add:SetVisible(false)
if frame.page then
frame.page:Remove()
end
frame.b_hover = self
frame.title = "Updates"
panel:OpenTab( "updates", 0.25, "in-right", "out-right" )
end
function fetchOnlineApps(force)
if force or GetConVar("gphone_csapp"):GetBool() then
http.Fetch("https://gphone.icu/api/list", function(body, size, headers, code)
local tbl = util.JSONToTable(body)
if type(tbl) == "table" then
frame.online = tbl
for _,app in pairs(tbl) do
if app.Icon then
GPhone.DownloadImage( app.Icon, 128, "background-color: #FFF; border-radius: 32px 32px 32px 32px" )
end
GPhone.UpdateApp("https://gphone.icu/api/list?app="..app.App.."&id="..app.Id, function(content)
app.Update = true
end)
end
loadOnlineApps()
loadUpdateApps()
else
print("[GPhone] Data not a table")
end
end,
function(err)
print(err)
end)
else
if game.SinglePlayer() or LocalPlayer():IsAdmin() then
local info = GPnl.AddPanel( online )
info:SetSize( w, 160 * ratio )
info:SetPos( 0, online:GetHeight() / 2 - 80 * ratio )
function info:Paint( x, y, w, h )
draw.SimpleText("Downloading apps has not been enabled", "GPMedium", w/2, 0, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP)
draw.SimpleText("To enable it, click the button below", "GPMedium", w/2, h/2 - 20 * ratio, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
draw.SimpleText("You are responsible for any potentially", "GPMedium", w/2, h/2 + 20 * ratio, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
draw.SimpleText("malicious or phishy apps you install", "GPMedium", w/2, h, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_BOTTOM)
end
local agree = GPnl.AddPanel( online )
agree:SetSize( w - 16 * ratio, 60 * ratio )
agree:SetPos( 8 * ratio, online:GetHeight() - 68 * ratio )
function agree:Paint( x, y, w, h )
draw.RoundedBox(0, 0, 0, w, h, Color(15, 200, 90))
draw.SimpleText("Agree and enable", "GPMedium", w/2, h/2, Color(255, 255, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
function agree:OnClick()
RunConsoleCommand("gphone_csapp", "1")
fetchOnlineApps(true)
self:Remove()
end
else
local info = GPnl.AddPanel( online )
info:SetSize( w, 80 * ratio )
info:SetPos( 0, online:GetHeight() / 2 - 40 * ratio )
function info:Paint( x, y, w, h )
draw.SimpleText("The staff of this server have not enabled", "GPMedium", w/2, 0, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP)
draw.SimpleText("the download and use of online apps", "GPMedium", w/2, h, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_BOTTOM)
end
end
end
end
fetchOnlineApps()
end<file_sep>APP.Name = "<NAME>"
APP.Author = "Krede"
APP.Icon = "asset://garrysmod/materials/gphone/apps/furfox.png"
function APP.Run( frame, w, h, ratio )
function frame:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h, Color( 220, 220, 220, 255 ) )
end
local size = 64 * ratio
frame.content = GPnl.AddPanel( frame, "html" )
frame.content:SetPos( 0, size )
frame.content:SetSize( w, h - size * 2 )
frame.content:Init( "https://www.google.com" )
function frame:OpenURL( url )
frame.content:OpenURL( url )
end
local header = GPnl.AddPanel( frame, "panel" )
header:SetPos( 0, 0 )
header:SetSize( w, size )
function header:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
end
local extend = GPnl.AddPanel( header )
extend:SetPos( 0, 0 )
extend:SetSize( size, size )
function extend:Paint( x, y, w, h )
surface.SetDrawColor(80, 80, 80)
surface.SetTexture( surface.GetTextureID( "gui/html/home" ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
function extend:OnClick()
local html = frame.content:GetHTML()
if IsValid(html) then
gui.OpenURL( html.URL )
end
end
local refresh = GPnl.AddPanel( header )
refresh:SetPos( w - size, 0 )
refresh:SetSize( size, size )
function refresh:Paint( x, y, w, h )
surface.SetDrawColor(80, 80, 80)
surface.SetTexture( surface.GetTextureID( "gui/html/refresh" ) )
local ct = CurTime()
if (self.Delay or 0) < ct then
surface.DrawTexturedRect( 0, 0, w, h )
else
local p = (self.Delay - ct)*720
surface.DrawTexturedRectRotated( w/2, h/2, w, h, p )
end
end
function refresh:OnClick()
self.Delay = CurTime() + 0.5
local html = frame.content:GetHTML()
if IsValid(html) then
html:Refresh( true )
end
end
local url = GPnl.AddPanel( header, "textentry" )
url:SetPos( 6 * ratio + size, 6 * ratio )
url:SetSize( w - size*2 - 12 * ratio, size - 12 * ratio )
url:SetFont("GPMedium")
url:SetBackColor( Color(220, 220, 220) )
url:SetText( frame.content:GetTitle() )
url:SetAlignment( TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER )
function url:OnClick()
self.b_typing = true
self:SetAlignment( TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER )
local html = frame.content:GetHTML()
local text = IsValid(html) and html.URL or ""
GPhone.InputText( self.Enter, self.Change, self.Cancel, text )
end
function url:OnEnter( link )
self:SetAlignment( TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER )
if string.StartWith(link, "http://") or string.StartWith(link, "https://") or string.StartWith(link, "www.") then
frame:OpenURL( link )
else
frame:OpenURL( "https://www.google.com/search?q="..link )
end
end
function url:OnCancel()
self:SetAlignment( TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER )
end
function url:Paint( x, y, w, h )
local text = self.b_typing and GPhone.GetInputText() or frame.content:GetTitle()
self:RenderText( x, y, w, h, text )
end
local footer = GPnl.AddPanel( frame, "panel" )
footer:SetPos( 0, h - 64 * ratio )
footer:SetSize( w, 64 * ratio )
function footer:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, 2, Color( 80, 80, 80, 255 ) )
draw.RoundedBox( 0, 0, 2, w, h-2, Color( 255, 255, 255, 255 ) )
end
local left = GPnl.AddPanel( footer )
left:SetPos( w/2 - 64 * ratio, 0 )
left:SetSize( 64 * ratio, 64 * ratio )
function left:Paint( x, y, w, h )
surface.SetDrawColor(80, 80, 80)
surface.SetTexture( surface.GetTextureID( "gui/html/back" ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
function left:OnClick()
local html = frame.content:GetHTML()
if IsValid(html) then
html:QueueJavascript( [[window.scrollBy(-75, 0);]] )
end
end
local right = GPnl.AddPanel( footer )
right:SetPos( w/2, 0 )
right:SetSize( 64 * ratio, 64 * ratio )
function right:Paint( x, y, w, h )
surface.SetDrawColor(80, 80, 80)
surface.SetTexture( surface.GetTextureID( "gui/html/forward" ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
function right:OnClick()
local html = frame.content:GetHTML()
if IsValid(html) then
html:QueueJavascript( [[window.scrollBy(75, 0);]] )
end
end
local bkwd = GPnl.AddPanel( footer )
bkwd:SetPos( 0, 0 )
bkwd:SetSize( 64 * ratio, 64 * ratio )
function bkwd:Paint( x, y, w, h )
surface.SetDrawColor(80, 80, 80)
surface.SetTexture( surface.GetTextureID( "gui/html/back" ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
function bkwd:OnClick()
local html = frame.content:GetHTML()
if IsValid(html) then
html:GoBack()
end
end
local fwd = GPnl.AddPanel( footer )
fwd:SetPos( w - 64 * ratio, 0 )
fwd:SetSize( 64 * ratio, 64 * ratio )
function fwd:Paint( x, y, w, h )
surface.SetDrawColor(80, 80, 80)
surface.SetTexture( surface.GetTextureID( "gui/html/forward" ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
function fwd:OnClick()
local html = frame.content:GetHTML()
if IsValid(html) then
html:GoForward()
end
end
end
function APP.Rotate( old, new )
if old.content and new.content then
new.content:OpenURL( old.content:GetHTML().URL )
end
end<file_sep>APP.Name = "Camera"
APP.Author = "Krede"
APP.Icon = "asset://garrysmod/materials/gphone/apps/camera.png"
function APP.Run( frame, w, h, ratio )
frame:SetFullScreen( true )
local h = frame.h
local ls = GPhone.Landscape
local size = 100 * ratio
frame.front = GPhone.SelfieEnabled()
frame.fov = 80
frame.pad = 110 * ratio
function frame:OnScroll( num )
self.fov = math.Clamp(self.fov - num*5, 5, 100)
end
function frame:Paint( x, y, w, h )
local mat = GPhone.RenderCamera( frame.fov, self.front )
surface.SetDrawColor(255, 255, 255, 255)
surface.SetMaterial( mat )
surface.DrawTexturedRect(0, 0, w, h)
if GPhone.Landscape then
draw.SimpleText(self.fov, "GPMedium", w - self.pad, h/2, Color(255, 255, 255), TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER)
else
draw.SimpleText(self.fov, "GPMedium", w/2, h - self.pad, Color(255, 255, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_BOTTOM)
end
end
local panel = GPnl.AddPanel( frame )
if ls then
panel:SetSize( size, w )
panel:SetPos( w - size, 0 )
else
panel:SetSize( w, size )
panel:SetPos( 0, h - size )
end
function panel:Paint( x, y, w, h )
surface.SetDrawColor( Color(0, 0, 0, 150) )
surface.DrawRect(0, 0, w, h)
end
local photo = GPnl.AddPanel( panel )
photo:SetSize( size * 0.8, size * 0.8 )
photo:SetPos( (ls and 0 or w - size) + size * 0.1, size * 0.1 )
function photo:Paint( x, y, w, h )
if self.last then
local s = w/GPhone.Ratio
surface.SetDrawColor(255, 255, 255)
surface.SetMaterial( photo.mat )
surface.DrawTexturedRect( 0, h/2 - s/2, w, s )
end
end
function photo:OnClick()
if !self.last then return end
local photos = GPhone.RunApp( "photos" )
if photos then
photos:Open( self.last, photo.mat )
end
end
local screenshot = GPnl.AddPanel( panel )
screenshot:SetSize( size, size )
if ls then
screenshot:SetPos( 0, h/2 - size/2 )
else
screenshot:SetPos( w/2 - size/2, 0 )
end
function screenshot:Paint( x, y, w, h )
surface.SetDrawColor(255, 255, 255)
surface.SetTexture( surface.GetTextureID( "sgm/playercircle" ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
function screenshot:OnClick()
surface.PlaySound("npc/scanner/scanner_photo1.wav")
--[[local dlight = DynamicLight( ent:EntIndex() )
if dlight then
dlight.Pos = vOffset
dlight.r = 255
dlight.g = 255
dlight.b = 255
dlight.Brightness = 10
dlight.Size = 512
dlight.DieTime = CurTime() + 0.02
dlight.Decay = 512
end]]
file.CreateDir("gphone/photos")
GPhone.RenderCamera(frame.fov, frame.front, nil, function(pos, ang)
local data = render.Capture( {
format = "jpeg",
quality = 100,
x = 0,
y = 0,
w = w,
h = h
} )
local name = os.time()..".jpg"
file.Write("gphone/photos/"..name, data)
GPhone.DownloadImage( "data/gphone/photos/"..name )
photo.last = "gphone/photos/"..name
photo.mat = Material("data/"..photo.last, "smooth")
end)
end
local face = GPnl.AddPanel( frame )
face:SetSize( 160 * ratio, 80 * ratio )
if ls then
face:SetPos( 0, h - 80 * ratio )
else
face:SetPos( w - 160 * ratio, 0 )
end
face:SetVisible( false )
function face:Paint( x, y, w, h )
surface.SetDrawColor(255, 255, 255)
surface.SetTexture( surface.GetTextureID( "vgui/face/grin" ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
function face:OnClick()
frame.smile = !frame.smile
end
local switch = GPnl.AddPanel( frame )
switch:SetSize( 80 * ratio, 80 * ratio )
switch:SetPos( 0, 0 )
function switch:Paint( x, y, w, h )
surface.SetDrawColor(255, 255, 255)
surface.SetTexture( surface.GetTextureID( "gui/html/refresh" ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
function switch:OnClick()
local bool = !frame.front
frame.front = bool
face:SetVisible( bool )
GPhone.EnableSelfie( bool )
end
end
function APP.Think( frame )
if !frame.front then return end
local p = frame.smile and 1 or 0
local ply = LocalPlayer()
local flex = ply:GetFlexNum() - 1
if flex > 0 then
for i = 0, flex do
if ply:GetFlexName(i) == "smile" then -- Makes a creepy smile
ply:SetFlexWeight( i, p )
end
end
end
end
function APP.Focus( frame )
if frame.front then
GPhone.EnableSelfie( true )
end
end<file_sep>local path = "gphone_remade"
local files = file.Find(path.."/*.lua", "LUA")
for _,v in pairs(files) do
if string.StartWith(v, "sv_") then
if SERVER then
include(path.."/"..v)
end
else
AddCSLuaFile(path.."/"..v)
if CLIENT or !string.StartWith(v, "cl_") then
include(path.."/"..v)
end
end
end<file_sep>APP.Name = "Settings"
APP.Author = "Krede"
APP.Icon = "asset://garrysmod/materials/gphone/apps/settings.png"
function APP.Run( frame, w, h, ratio )
function frame:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h, Color( 220, 220, 220, 255 ) )
end
local mar = (64 - 36) / 2 * ratio
local main = frame:AddTab( "home", "panel" )
local space = 12 * ratio
local pad = 8 * ratio
local size = 64 * ratio - pad * 2
local scroll = GPnl.AddPanel( main, "scroll" )
scroll:SetPos( 0, 64 * ratio )
scroll:SetSize( w, h - 64 * ratio )
local appeartab = GPnl.AddPanel( scroll )
appeartab:SetSize( w, 64 * ratio )
appeartab:SetPos( 0, space )
function appeartab:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("Appearance", "GPMedium", mar, h/2, Color(70, 70, 70), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
function appeartab:OnClick()
frame:OpenTab( "appearance", 0.25, "in-right", "out-left" )
end
space = space + 64 * ratio
local apptab = GPnl.AddPanel( scroll )
apptab:SetSize( w, 64 * ratio )
apptab:SetPos( 0, space )
function apptab:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("Apps", "GPMedium", mar, h/2, Color(70, 70, 70), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
function apptab:OnClick()
local pnl = frame:GetTab( "apps" )
pnl:Refresh()
frame:OpenTab( "apps", 0.25, "in-right", "out-left" )
end
space = space + 64 * ratio
local storagetab = GPnl.AddPanel( scroll )
storagetab:SetSize( w, 64 * ratio )
storagetab:SetPos( 0, space )
function storagetab:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("Storage", "GPMedium", mar, h/2, Color(70, 70, 70), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
function storagetab:OnClick()
local pnl = frame:GetTab( "storage" )
pnl:Refresh()
frame:OpenTab( "storage", 0.25, "in-right", "out-left" )
end
space = space + 64 * ratio
local debugtab = GPnl.AddPanel( scroll )
debugtab:SetSize( w, 64 * ratio )
debugtab:SetPos( 0, space )
function debugtab:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("Developer", "GPMedium", mar, h/2, Color(70, 70, 70), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
function debugtab:OnClick()
frame:OpenTab( "debug", 0.25, "in-right", "out-left" )
end
space = space + 64 * ratio
local systemtab = GPnl.AddPanel( scroll )
systemtab:SetSize( w, 64 * ratio )
systemtab:SetPos( 0, space )
function systemtab:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("System", "GPMedium", mar, h/2, Color(70, 70, 70), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
function systemtab:OnClick()
frame:OpenTab( "system", 0.25, "in-right", "out-left" )
end
space = space + 64 * ratio
local abouttab = GPnl.AddPanel( scroll )
abouttab:SetSize( w, 64 * ratio )
abouttab:SetPos( 0, space )
function abouttab:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("About", "GPMedium", mar, h/2, Color(70, 70, 70), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
function abouttab:OnClick()
frame:OpenTab( "about", 0.25, "in-right", "out-left" )
end
local header = GPnl.AddPanel( main )
header:SetPos( 0, 0 )
header:SetSize( w, 64 * ratio )
function header:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("Settings", "GPTitle", w/2, h/2, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
frame:OpenTab( "home" )
local appearance = frame:AddTab( "appearance", "panel" )
local space = 12 * ratio
local scroll = GPnl.AddPanel( appearance, "scroll" )
scroll:SetPos( 0, 64 * ratio )
scroll:SetSize( w, h - 64 * ratio )
local holdlabel = GPnl.AddPanel( scroll, "panel" )
holdlabel:SetSize( w, 64 * ratio )
holdlabel:SetPos( 0, space )
function holdlabel:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("Hold time", "GPMedium", mar, h/2, Color(70, 70, 70), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
local hold = GPnl.AddPanel( holdlabel, "textentry" )
hold:SetSize( size * 2, 64 * ratio )
hold:SetPos( w - size * 2 - pad, 0 )
hold:SetFont( "GPMedium" )
hold:SetBackColor( Color(0, 0, 0, 0) )
hold:SetText( math.Round(GetConVar("gphone_holdtime"):GetFloat(), 2) )
hold:SetAlignment( TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER )
function hold:OnEnter( val )
if tonumber(val) then
self:SetText( val )
RunConsoleCommand("gphone_holdtime", val)
end
end
space = space + 64 * ratio
local ampm = GPnl.AddPanel( scroll, "panel" )
ampm:SetSize( w, 64 * ratio )
ampm:SetPos( 0, space )
function ampm:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("Use AM/PM", "GPMedium", mar, h/2, Color(70, 70, 70), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
local toggle = GPnl.AddPanel( ampm, "toggle" )
toggle:SetSize( size*2, size )
toggle:SetPos( w - size*2 - pad, pad )
if GPhone.GetData("ampm", false) then
toggle:SetToggle( true )
end
function toggle:OnChange( bool )
GPhone.SetData("ampm", bool)
end
space = space + 64 * ratio
local murica = GPnl.AddPanel( scroll, "panel" )
murica:SetSize( w, 64 * ratio )
murica:SetPos( 0, space )
function murica:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("Use imperial units", "GPMedium", mar, h/2, Color(70, 70, 70), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
local toggle = GPnl.AddPanel( murica, "toggle" )
toggle:SetSize( size*2, size )
toggle:SetPos( w - size*2 - pad, pad )
if GPhone.GetData("imperial", false) then
toggle:SetToggle( true )
end
function toggle:OnChange( bool )
GPhone.SetData("imperial", bool)
end
space = space + 64 * ratio
local rowlabel = GPnl.AddPanel( scroll, "panel" )
rowlabel:SetSize( w, 64 * ratio )
rowlabel:SetPos( 0, space )
function rowlabel:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("App rows", "GPMedium", mar, h/2, Color(70, 70, 70), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
local rows = GPnl.AddPanel( rowlabel, "textentry" )
rows:SetSize( size * 2, 64 * ratio )
rows:SetPos( w - size * 2 - pad, 0 )
rows:SetFont( "GPMedium" )
rows:SetBackColor( Color(0, 0, 0, 0) )
rows:SetText( GetConVar("gphone_rows"):GetInt() )
rows:SetAlignment( TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER )
function rows:OnEnter( val )
local val = tonumber(val)
if val then
local num = math.Clamp(val, 0, 6)
self:SetText( num )
RunConsoleCommand("gphone_rows", num)
end
end
space = space + 64 * ratio
local brightlabel = GPnl.AddPanel( scroll, "panel" )
brightlabel:SetSize( w, 64 * ratio )
brightlabel:SetPos( 0, space )
function brightlabel:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("Brightness", "GPMedium", mar, h/2, Color(70, 70, 70), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
local brightness = GPnl.AddPanel( brightlabel, "textentry" )
brightness:SetSize( size * 2, 64 * ratio )
brightness:SetPos( w - size * 2 - pad, 0 )
brightness:SetFont( "GPMedium" )
brightness:SetBackColor( Color(0, 0, 0, 0) )
brightness:SetText( math.Round(GetConVar("gphone_brightness"):GetFloat() * 100) )
brightness:SetAlignment( TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER )
function brightness:OnEnter( val )
local val = tonumber(val)
if val then
local num = math.Clamp(val, 0, 100)
self:SetText( math.Round(num) )
RunConsoleCommand("gphone_brightness", math.Round(num/100, 2))
end
end
space = space + 64 * ratio
local wallpaper = GPnl.AddPanel( scroll, "textentry" )
wallpaper:SetSize( w, 64 * ratio )
wallpaper:SetPos( 0, space )
wallpaper:SetFont("GPMedium")
wallpaper:SetText( "" )
function wallpaper:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
local text = self.b_typing and GPhone.GetInputText() or "Change wallpaper"
draw.SimpleText(text, self:GetFont(), mar, h/2, Color(70, 70, 70), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
function wallpaper:OnEnter( path )
GPhone.SetData("background", path)
self:SetText( "" )
end
local header = GPnl.AddPanel( appearance )
header:SetPos( 0, 0 )
header:SetSize( w, 64 * ratio )
function header:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("Appearance", "GPTitle", w/2, h/2, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
local back = GPnl.AddPanel( header )
back:SetPos( 0, 0 )
back:SetSize( 64 * ratio, 64 * ratio )
function back:OnClick()
frame:OpenTab( "home", 0.25, "in-left", "out-right" )
end
function back:Paint( x, y, w, h )
draw.SimpleText("<", "GPTitle", w/2, h/2, Color(0, 0, 0), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
local apps = frame:AddTab( "apps", "panel" )
local scroll = GPnl.AddPanel( apps, "scroll" )
scroll:SetPos( 0, 64 * ratio )
scroll:SetSize( w, h - 64 * ratio )
function apps:Refresh()
scroll:Clear()
local space = 12 * ratio
for _,name in pairs(GPhone.Data.apps or {}) do
if GPDefaultApps and table.HasValue(GPDefaultApps, name) then continue end
local app = GPhone.GetApp(name)
if !app then return end
local but = GPnl.AddPanel( scroll )
but:SetSize( w, 110 * ratio )
but:SetPos( 0, space )
but.Name = app.Name or name
but.Author = app.Author or "N/A"
function but:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText(self.Name, "GPMedium", h + 4, 4, Color(70, 70, 70), TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
draw.SimpleText(self.Author or "N/A", "GPSmall", h + 4, h/2, Color(160, 160, 160), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
local icon = GPnl.AddPanel( but )
icon:SetSize( 102 * ratio, 102 * ratio )
icon:SetPos( 4 * ratio, 4 * ratio )
icon.Icon = app.Icon or "N/A"
function icon:Paint( x, y, w, h )
surface.SetDrawColor( 255, 255, 255 )
surface.SetMaterial( GPhone.GetImage( self.Icon ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
local clear = GPnl.AddPanel( but )
clear:SetSize( 120 * ratio, 40 * ratio )
clear:SetPos( w - 145 * ratio, 35 * ratio )
clear.App = name
function clear:Paint( x, y, w, h )
draw.RoundedBox(0, 0, 0, w, h, Color(15, 200, 90))
draw.RoundedBox(0, 4, 4, w-8, h-8, Color(255, 255, 255))
draw.SimpleText("Uninstall", "GPMedium", w/2, h/2, Color(15, 200, 90), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
function clear:OnClick()
GPhone.UninstallApp(self.App)
self:Remove()
end
space = space + 110 * ratio
end
end
local header = GPnl.AddPanel( apps )
header:SetPos( 0, 0 )
header:SetSize( w, 64 * ratio )
function header:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("Apps", "GPTitle", w/2, h/2, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
local back = GPnl.AddPanel( header )
back:SetPos( 0, 0 )
back:SetSize( 64 * ratio, 64 * ratio )
function back:OnClick()
frame:OpenTab( "home", 0.25, "in-left", "out-right" )
end
function back:Paint( x, y, w, h )
draw.SimpleText("<", "GPTitle", w/2, h/2, Color(0, 0, 0), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
local storage = frame:AddTab( "storage", "panel" )
local scroll = GPnl.AddPanel( storage, "scroll" )
scroll:SetPos( 0, 64 * ratio )
scroll:SetSize( w, h - 64 * ratio )
function storage:Refresh()
scroll:Clear()
local space = 12 * ratio
for name,data in pairs(GPhone.Data.appdata or {}) do
local app = GPhone.GetApp(name)
local but = GPnl.AddPanel( scroll )
but:SetSize( w, 48 * ratio )
but:SetPos( 0, space )
but.Name = app and app.Name or name
but.Size = string.len( util.TableToJSON( data ) ) - 2
function but:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText(math.Round(self.Size/1024, 3).." kb", "GPSmall", w - h - mar, h/2, Color(70, 70, 70), TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER)
draw.SimpleText(self.Name, "GPMedium", mar, h/2, Color(70, 70, 70), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
local clear = GPnl.AddPanel( but )
clear:SetSize( 48 * ratio, 48 * ratio )
clear:SetPos( w - 48 * ratio, 0 )
clear.App = name
function clear:Paint( x, y, w, h )
surface.SetDrawColor(70, 70, 70)
surface.SetTexture( surface.GetTextureID( "gui/html/stop" ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
function clear:OnClick()
but.Size = 0
GPhone.ClearAllAppData(self.App)
self:Remove()
end
space = space + 48 * ratio
end
end
local header = GPnl.AddPanel( storage )
header:SetPos( 0, 0 )
header:SetSize( w, 64 * ratio )
function header:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("Storage", "GPTitle", w/2, h/2, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
local back = GPnl.AddPanel( header )
back:SetPos( 0, 0 )
back:SetSize( 64 * ratio, 64 * ratio )
function back:OnClick()
frame:OpenTab( "home", 0.25, "in-left", "out-right" )
end
function back:Paint( x, y, w, h )
draw.SimpleText("<", "GPTitle", w/2, h/2, Color(0, 0, 0), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
local debugger = frame:AddTab( "debug", "panel" )
local space = 12 * ratio
local scroll = GPnl.AddPanel( debugger, "scroll" )
scroll:SetPos( 0, 64 * ratio )
scroll:SetSize( w, h-64 * ratio )
local wipe = GPnl.AddPanel( scroll )
wipe:SetSize( w, 64 * ratio )
wipe:SetPos( 0, space )
function wipe:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("Wipe log", "GPMedium", mar, h/2, Color(70, 70, 70), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
function wipe:OnClick()
GPhone.WipeLog()
end
space = space + 64 * ratio
local plog = GPnl.AddPanel( scroll )
plog:SetSize( w, 64 * ratio )
plog:SetPos( 0, space )
function plog:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("Print log", "GPMedium", mar, h/2, Color(70, 70, 70), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
function plog:OnClick()
GPhone.PrintLog()
end
space = space + 64 * ratio
local imag = GPnl.AddPanel( scroll )
imag:SetSize( w, 64 * ratio )
imag:SetPos( 0, space )
function imag:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("Redownload Images", "GPMedium", mar, h/2, Color(70, 70, 70), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
function imag:OnClick()
RunConsoleCommand("gphone_redownloadimages")
end
space = space + 64 * ratio
local reset = GPnl.AddPanel( scroll )
reset:SetSize( w, 64 * ratio )
reset:SetPos( 0, space )
function reset:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("Factory Reset", "GPMedium", mar, h/2, Color(255, 0, 0), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
function reset:OnClick()
RunConsoleCommand("gphone_reset")
end
local header = GPnl.AddPanel( debugger )
header:SetPos( 0, 0 )
header:SetSize( w, 64 * ratio )
function header:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("Developer", "GPTitle", w/2, h/2, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
local back = GPnl.AddPanel( header )
back:SetPos( 0, 0 )
back:SetSize( 64 * ratio, 64 * ratio )
function back:OnClick()
frame:OpenTab( "home", 0.25, "in-left", "out-right" )
end
function back:Paint( x, y, w, h )
draw.SimpleText("<", "GPTitle", w/2, h/2, Color(0, 0, 0), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
local system = frame:AddTab( "system", "panel" )
local scroll = GPnl.AddPanel( system, "scroll" )
scroll:SetPos( 0, 64 * ratio )
scroll:SetSize( w, h - 64 * ratio )
local number = GPnl.AddPanel( scroll )
number:SetSize( w, 64 * ratio )
number:SetPos( 0, 12 * ratio )
function number:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80 ) )
draw.SimpleText("Phone Number: "..LocalPlayer():AccountID(), "GPMedium", mar, h/2, Color(0, 0, 0), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
local copy = GPnl.AddPanel( number )
copy:SetSize( 80 * ratio, 64 * ratio )
copy:SetPos( w - 80 * ratio, 0 )
function copy:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h, Color( 80, 80, 80 ) )
draw.RoundedBox( 0, 2, 2, w-4, h-4, Color( 255, 255, 255 ) )
draw.SimpleText("Copy", "GPSmall", w/2, h/2, Color(0, 0, 0), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
function copy:OnClick()
SetClipboardText( LocalPlayer():AccountID() )
end
local header = GPnl.AddPanel( system )
header:SetPos( 0, 0 )
header:SetSize( w, 64 * ratio )
function header:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80 ) )
draw.SimpleText("System", "GPTitle", w/2, h/2, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
local back = GPnl.AddPanel( header )
back:SetPos( 0, 0 )
back:SetSize( 64 * ratio, 64 * ratio )
function back:OnClick()
frame:OpenTab( "home", 0.25, "in-left", "out-right" )
end
function back:Paint( x, y, w, h )
draw.SimpleText("<", "GPTitle", w/2, h/2, Color(0, 0, 0), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
local about = frame:AddTab( "about", "panel" )
local scroll = GPnl.AddPanel( about, "scroll" )
scroll:SetPos( 0, 64 * ratio )
scroll:SetSize( w, h - 64 * ratio )
local content = GPnl.AddPanel( scroll, "panel" )
content:SetSize( w, 280 * ratio )
content:SetPos( 0, 12 * ratio )
function content:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h - 2, Color( 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h - 2, w, 2, Color( 80, 80, 80, 255 ) )
surface.SetDrawColor(255, 255, 255)
surface.SetTexture( surface.GetTextureID( "vgui/entities/gmod_gphone" ) )
surface.DrawTexturedRect( 8, 8, h - 16, h - 16 )
draw.SimpleText("GPhone Remade", "GPTitle", h + 4, 0, Color(0, 0, 0), TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
draw.SimpleText("Created by Krede", "GPMedium", h + 4, 42 * ratio, Color(0, 0, 0), TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
if self.Update then
draw.SimpleText("Last update:", "GPSmall", h + 4, h - 36*2 * ratio, Color(0, 0, 0), TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
draw.SimpleText(self.Update, "GPSmall", h + 4, h - 36 * ratio, Color(0, 0, 0), TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
end
end
http.Fetch("https://steamcommunity.com/sharedfiles/filedetails/changelog/1370983401", function(body)
local start = string.find(body, "Update: ")
if start then
local stop = string.find(body, "</div>", start)
if stop then
content.Update = string.Trim( string.sub(body, start+8, stop-1) )
end
end
end,
function(err)
print(err)
end)
local header = GPnl.AddPanel( about )
header:SetPos( 0, 0 )
header:SetSize( w, 64 * ratio )
function header:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("About", "GPTitle", w/2, h/2, Color(70, 70, 70), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
local back = GPnl.AddPanel( header )
back:SetPos( 0, 0 )
back:SetSize( 64 * ratio, 64 * ratio )
function back:OnClick()
frame:OpenTab( "home", 0.25, "in-left", "out-right" )
end
function back:Paint( x, y, w, h )
draw.SimpleText("<", "GPTitle", w/2, h/2, Color(0, 0, 0), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
local update = GPnl.AddPanel( scroll )
update:SetSize( w, 64 * ratio )
update:SetPos( 0, 292 * ratio )
function update:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
draw.SimpleText("Go to Workshop", "GPMedium", w/2, h/2, Color(0, 0, 0), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
function update:OnClick()
gui.OpenURL( "https://steamcommunity.com/sharedfiles/filedetails/?id=1370983401" )
end
end<file_sep>APP.Name = "FileManager"
APP.Author = "Krede"
APP.Negative = false
APP.Icon = "asset://garrysmod/materials/gphone/apps/contacts.png"
function APP.Run( frame, w, h, ratio )
function frame:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h, Color( 220, 220, 220 ) )
end
frame.Path = ""
local folder = Material("icon16/folder.png")
local page = Material("icon16/page_white.png")
local txt = Material("icon16/page_white_text.png")
local lua = Material("icon16/script.png")
local film = Material("icon16/film.png")
local snd = Material("icon16/sound.png")
local pic = Material("icon16/picture.png")
local root = GPnl.AddPanel( frame, "frame" )
root:SetSize( w, h - 64 * ratio )
root:SetPos( 0, 64 * ratio )
function frame:OpenVideo( path )
frame.File = table.remove(string.Explode("/", path))
local ext = string.EndsWith(path, ".mp4") and "mp4" or string.EndsWith(path, ".webm") and "webm"
if !ext then return false end
local r = file.Read(path, "GAME")
local data = util.Base64Encode( r )
frame.Popup = GPnl.AddPanel( frame, "panel" )
frame.Popup:SetSize( root:GetSize() )
frame.Popup:SetPos( root:GetPos() )
function frame.Popup:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h, Color( 220, 220, 220 ) )
end
local vid = GPnl.AddPanel( frame.Popup, "video" )
vid:SetSize( frame.Popup:GetSize() )
vid:SetPos( 0, 0 )
vid:Open( path )
end
function frame:SetPath( path )
local noslash = path == "" or string.EndsWith(path, "/")
frame.Path = path..(noslash and "" or "/")
local files,dirs = {},{"backgrounds", "data", "lua", "maps", "materials", "screenshots", "sound", "videos"}
if frame.Path != "" then
files,dirs = file.Find(frame.Path.."*", "GAME")
end
local scroll = root:GetTab( "garrysmod/"..frame.Path )
if !scroll then
scroll = root:AddTab( "garrysmod/"..frame.Path, "scroll" )
scroll:SetSize( root:GetSize() )
scroll:SetPos( 0, 0 )
function scroll:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h, Color( 220, 220, 220 ) )
end
local num = 0
for _,dir in pairs(dirs) do
local fileinfo = GPnl.AddPanel( scroll )
fileinfo:SetSize( w, 64 * ratio )
fileinfo:SetPos( 0, num * 64 * ratio )
fileinfo.Dir = dir
function fileinfo:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
local text = self.Dir
surface.SetFont("GPMedium")
local size = surface.GetTextSize(text)
if size > w then
draw.SimpleText(text, "GPMedium", w, h/2, Color(70, 70, 70), TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER)
else
draw.SimpleText(text, "GPMedium", h, h/2, Color(70, 70, 70), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
surface.SetDrawColor(255, 255, 255)
surface.SetMaterial( folder )
surface.DrawTexturedRect( 0, 0, h, h )
end
function fileinfo:OnClick()
frame:SetPath( frame.Path..self.Dir )
end
num = num + 1
end
for _,name in pairs(files) do
local fileinfo = GPnl.AddPanel( scroll )
fileinfo:SetSize( w, 64 * ratio )
fileinfo:SetPos( 0, num * 64 * ratio )
fileinfo.File = name
fileinfo.Extension = string.GetExtensionFromFilename( name )
function fileinfo:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
local text = self.File
surface.SetFont("GPMedium")
local size = surface.GetTextSize(text)
if size > w then
draw.SimpleText(text, "GPMedium", w, h/2, Color(70, 70, 70), TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER)
else
draw.SimpleText(text, "GPMedium", h, h/2, Color(70, 70, 70), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
surface.SetDrawColor(255, 255, 255)
if self.Extension == "lua" then
surface.SetMaterial( lua )
elseif self.Extension == "mp4" or self.Extension == "webm" then
surface.SetMaterial( film )
elseif self.Extension == "png" or self.Extension == "jpg" or self.Extension == "jpeg" or self.Extension == "vmt" then
surface.SetMaterial( pic )
elseif self.Extension == "mp3" or self.Extension == "wav" or self.Extension == "ogg" then
surface.SetMaterial( snd )
elseif self.Extension == "txt" then
surface.SetMaterial( txt )
else
surface.SetMaterial( page )
end
surface.DrawTexturedRect( 0, 0, h, h )
end
function fileinfo:OnClick()
local ext = self.Extension
local path = frame.Path..self.File
if ext == "mp4" or ext == "webm" then
frame:OpenVideo( path )
elseif ext == "mp3" or ext == "wav" then
local app = GPhone.RunApp( "gtunes" )
if app then
app:Open( path )
end
elseif ext == "png" or ext == "jpg" or ext == "jpeg" or ext == "vmt" then
local app = GPhone.RunApp( "photos" )
if ext == "vmt" then
local parts = string.Explode("/", path)
table.remove(parts, 1)
path = string.StripExtension( table.concat(parts, "/") )
end
if app then
app:Open( path, Material(path) )
end
end
end
num = num + 1
end
end
root:OpenTab( "garrysmod/"..frame.Path, 0.25, "in-right", "out-right" )
end
function frame:GoBack()
if self.Path == "" then return end
if self.Popup then self.Popup:Remove() end
if self.File then
self.File = nil
self:SetPath( self.Path )
else
local tbl = string.Explode("/", self.Path)
table.remove(tbl)
table.remove(tbl)
self:SetPath( table.concat(tbl, "/") )
end
end
local header = GPnl.AddPanel( frame )
header:SetSize( w, 64 * ratio )
header:SetPos( 0, 0 )
function header:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h-2, Color( 255, 255, 255, 255 ) )
draw.RoundedBox( 0, 0, h-2, w, 2, Color( 80, 80, 80, 255 ) )
end
local back = GPnl.AddPanel( header )
back:SetSize( 64 * ratio, 64 * ratio )
back:SetPos( 0, 0 )
function back:OnClick()
frame:GoBack()
end
function back:Paint( x, y, w, h )
if frame.Path != "" then
draw.SimpleText("<", "GPTitle", w/2, h/2, Color(0, 160, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
end
local path = GPnl.AddPanel( header )
path:SetSize( w - 128 * ratio, 64 * ratio )
path:SetPos( 64 * ratio, 0 )
function path:Paint( x, y, w, h )
local text = frame.File or "garrysmod/"..(frame.Path or "")
surface.SetFont("GPTitle")
local size = surface.GetTextSize(text)
if size > w then
draw.SimpleText(text, "GPTitle", w, h/2, Color(70, 70, 70), TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER)
else
draw.SimpleText(text, "GPTitle", 0, h/2, Color(70, 70, 70), TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
end
frame:SetPath( "" )
end<file_sep>CreateConVar("gphone_csapp", "0", {FCVAR_ARCHIVE, FCVAR_REPLICATED}, "Allow players to download apps via links and the online AppStore")
CreateConVar("gphone_sync", "1", {FCVAR_ARCHIVE, FCVAR_REPLICATED}, "Synchronize players data with singleplayer")
CreateConVar("gphone_spawn", "0", {FCVAR_ARCHIVE, FCVAR_REPLICATED}, "Whether players should spawn with the GPhone")
GPShareData = true -- Allow data to be shared between players, via the server
GPDefaultApps = {"appstore", "settings", "camera", "photos", "messages", "gtunes", "launcher"} -- Default apps to install
GPDefaultData = { -- Default data to be initialized on the client
apps = table.Copy(GPDefaultApps),
appdata = {
gtunes = {
music = {"sound/music/hl1_song25_remix3.mp3"}
}
},
background = "materials/gphone/backgrounds/sky.jpg",
icon_css = "background-color: #FFF; border-radius: 32px 32px 32px 32px",
launcher = "launcher"
}
GPLoadedApps = GPLoadedApps or false
file.CreateDir("gphone/users")
if CLIENT then
file.CreateDir("gphone/apps")
file.CreateDir("gphone/builds")
end
function GPLoadApps()
if !GPLoadedApps then
print("[GPhone] Adding serverside apps")
local files = file.Find("gpapps/*.lua", "LUA")
local added = 0
for _,v in pairs(files) do -- I mean, you really need at least one app before it's usable
AddCSLuaFile("gpapps/"..v)
GPLoadedApps = true
local name = string.sub(v, 0, string.len(v) - 4)
if SERVER then
added = added + 1
else
APP = {}
include("gpapps/"..v)
--local r = file.Read("gpapps/"..v, "LUA")
--RunString(r, v)
local res = GPhone.AddApp(name, APP)
if res then
added = added + 1
else
print("[GPhone] Could not add serverside app '"..name.."', possibly missing Name field")
end
end
end
if added == 0 then
if CLIENT then
GPhone.Debug("[GPhone] Could not load any serverside apps. Apps might not be available on the phone", false, true)
else
ErrorNoHalt("[GPhone] Server could not load any apps\n")
end
else
print("[GPhone] Added "..added.." serverside apps")
end
if CLIENT and GetConVar("gphone_csapp"):GetBool() then
print("[GPhone] Adding clientside apps")
local files = file.Find("gphone/apps/*.txt", "DATA")
local added = 0
for _,v in pairs(files) do
APP = {}
local name = string.sub(v, 0, string.len(v)-4)
local r = file.Read("gphone/apps/"..v, "DATA")
RunString(r, v)
local res = GPhone.AddApp(name, APP)
if res then
added = added + 1
else
print("[GPhone] Could not add clientside app '"..name.."', possibly missing Name field")
end
end
print("[GPhone] Added "..added.." clientside apps")
end
end
end
-- One idea why Apps might not appear could be because the CLIENT is run before the SERVER. Needs testing
-- Could also be a restriction with garry's mod, not allowing LUA to check filesystems at the start, for whatever reason
-- Make absolutely SURE that this is called, one way or another
timer.Simple(3, function()
GPLoadApps()
end)
-- Just fucking call it constantly, what do I care?
GPLoadApps()
-- Make sure it is loaded on the server as well
hook.Add("Initialize", "GPhoneInitialize", function()
GPLoadApps()
end)
local selfietranslate = {}
selfietranslate[ ACT_MP_STAND_IDLE ] = ACT_HL2MP_IDLE_PISTOL
selfietranslate[ ACT_MP_WALK ] = ACT_HL2MP_WALK_PISTOL
selfietranslate[ ACT_MP_RUN ] = ACT_HL2MP_RUN_PISTOL
selfietranslate[ ACT_MP_CROUCH_IDLE ] = ACT_HL2MP_IDLE_CROUCH_PISTOL
selfietranslate[ ACT_MP_CROUCHWALK ] = ACT_HL2MP_WALK_CROUCH_PISTOL
selfietranslate[ ACT_MP_JUMP ] = ACT_HL2MP_JUMP_PISTOL
hook.Add("TranslateActivity", "GPhoneSelfieActivity", function(ply, act)
local wep = ply:GetActiveWeapon()
if IsValid(wep) and wep:GetClass() == "gmod_gphone" and ply:GetNWBool("GPSelfie") and selfietranslate[act] then
return selfietranslate[act]
end
end)
if SERVER then
concommand.Add("gphone_reloadapps", function(ply)
if ply:IsAdmin() then
GPLoadedApps = false
GPLoadApps()
net.Start("GPhone_Load_Apps")
net.Broadcast()
else
net.Start("GPhone_Load_Apps")
net.Send(ply)
end
end)
else
net.Receive("GPhone_Load_Apps", function(l)
GPLoadedApps = false
GPLoadApps()
end)
list.Add("CursorMaterials", "effects/select_dot")
list.Add("CursorMaterials", "effects/select_ring")
list.Add("CursorMaterials", "vgui/minixhair")
list.Add("CursorMaterials", "gui/faceposer_indicator")
list.Add("CursorMaterials", "sprites/grip")
list.Add("CursorMaterials", "vgui/cursors/hand")
if !Material("sprites/arrow"):IsError() then
list.Add("CursorMaterials", "sprites/arrow")
end
if !Material("vgui/glyph_practice"):IsError() then
list.Add("CursorMaterials", "vgui/glyph_practice")
end
if !Material("vgui/glyph_practice"):IsError() then
list.Add("CursorMaterials", "vgui/flagtime_full")
end
if !Material("vgui/glyph_practice"):IsError() then
list.Add("CursorMaterials", "vgui/glyph_close_x")
end
list.Add("CaseMaterials", "none")
list.Add("CaseMaterials", "models/wireframe")
list.Add("CaseMaterials", "models/flesh")
list.Add("CaseMaterials", "debug/env_cubemap_model")
list.Add("CaseMaterials", "brick/brick_model")
list.Add("CaseMaterials", "models/props_c17/FurnitureFabric003a")
list.Add("CaseMaterials", "models/props_c17/paper01")
list.Add("CaseMaterials", "phoenix_storms/gear")
list.Add("CaseMaterials", "phoenix_storms/stripes")
list.Add("CaseMaterials", "models/XQM/LightLinesRed_tool")
if !Material("models/player/shared/gold_player"):IsError() then
list.Add("CaseMaterials", "models/player/shared/gold_player")
end
local gpvars = {
["gphone_sharedata"] = "1", -- Sharable data
["gphone_askdata"] = "1", -- Ask before sharing
["gphone_lefthand"] = "0", -- Left-handed
["gphone_wepicon"] = "1", -- Fancy weapon-icon
["gphone_bgblur"] = "1", -- Blur when focused
["gphone_blur"] = "1", -- Blur on ui elements
["gphone_bob"] = "1", -- Viewbob
["gphone_hands"] = "0", -- Override hands
["gphone_hints"] = "1", -- Enable hints
["gphone_lighting"] = "1", -- Enable dynamic lighting
["gphone_airpods"] = "1", -- Enable airpods when listening to music
["gphone_report"] = "1", -- Automatic report on error
["gphone_sf"] = "1", -- Enable stormfox clock
["gphone_thumbnail"] = "1", -- Enable screen thumbnails (May cause lag)
["gphone_rows"] = "4", -- Amount of rows per page
["gphone_holdtime"] = "0.4", -- Holdtime
["gphone_brightness"] = "0.7", -- Screen brightness
["gphone_volume"] = "1", -- Volume
["gphone_sensitivity"] = "4", -- Cursor sensitivity
["gphone_cursorsize"] = "60", -- Cursor size
["gphone_focus"] = "0", -- Up-in-the-face focus
["gphone_cursormat"] = "effects/select_dot", -- Cursor material
["gphone_case"] = "\"\"" -- Case material
}
for k,v in pairs(gpvars) do
if GetConVar(k) == nil then
CreateClientConVar(k, v, true, false)
end
end
if GetConVar("gphone_showbounds") == nil then
CreateClientConVar("gphone_showbounds", "0", false, false, "Whether to show boundaries of all clickable panels")
end
if GetConVar("gphone_chromium") == nil then
CreateClientConVar("gphone_chromium", "1", true, false, "Notify user about chromium every time they open the browser")
end
GPhone.Rows = math.ceil(GetConVar("gphone_rows"):GetInt() * (GPhone.Landscape and GPhone.Resolution or 1)) -- Workaround
cvars.AddChangeCallback("gphone_rows", function(_, _, new)
GPhone.Rows = math.Round(new)
local launcher = GPhone.GetData("launcher", "launcher")
if GPhone.CurrentApp == launcher then
GPhone.FocusHome()
end
end)
cvars.AddChangeCallback("gphone_lefthand", function(_, _, new)
local wep = LocalPlayer():GetActiveWeapon()
if IsValid(wep) and wep:GetClass() == "gmod_gphone" then
wep.ViewModelFlip = new != "0"
end
end)
local function GPAdminSettingsPanel(panel)
panel:ClearControls()
panel:AddControl("CheckBox", {
Label = "Allow players to download custom apps",
Command = "gphone_csapp"
})
panel:AddControl("CheckBox", {
Label = "Enable singleplayer synchronization",
Command = "gphone_sync"
})
panel:AddControl("CheckBox", {
Label = "Spawn with the GPhone (Requires restart)",
Command = "gphone_spawn"
})
panel:AddControl("Button", {
Label = "Reload apps",
Command = "gphone_reloadapps"
})
end
local function GPSettingsPanel(panel)
panel:ClearControls()
local cmd = ""
for k,v in pairs(gpvars) do
cmd = cmd..k.." "..v.."\n"
end
panel:AddControl("Button", {
Label = "Reset settings",
Command = cmd
})
panel:AddControl("CheckBox", {
Label = "Enable data-sharing",
Command = "gphone_sharedata"
})
panel:AddControl("CheckBox", {
Label = "Ask before sharing data",
Command = "gphone_askdata"
})
panel:AddControl("CheckBox", {
Label = "Enable fancy Weapon-icon (May cause FPS drops)",
Command = "gphone_wepicon"
})
panel:AddControl("CheckBox", {
Label = "Enable background blur (May cause FPS drops)",
Command = "gphone_bgblur"
})
panel:AddControl("CheckBox", {
Label = "Enable UI blur (May cause FPS drops)",
Command = "gphone_blur"
})
panel:AddControl("CheckBox", {
Label = "Enable dynamic lighting (May cause FPS drops)",
Command = "gphone_lighting"
})
panel:AddControl("CheckBox", {
Label = "Enable airpods (Requires TF2)",
Command = "gphone_airpods"
})
panel:AddControl("CheckBox", {
Label = "Enable App thumbnails",
Command = "gphone_thumbnail"
})
panel:AddControl("CheckBox", {
Label = "Enable automatic bug reporting",
Command = "gphone_report"
})
panel:AddControl("CheckBox", {
Label = "Show clickboxes of panels",
Command = "gphone_showbounds"
})
panel:AddControl("CheckBox", {
Label = "Enable hints",
Command = "gphone_hints"
})
panel:AddControl("CheckBox", {
Label = "Enable StormFox clock",
Command = "gphone_sf"
})
panel:AddControl("CheckBox", {
Label = "Override custom hands with placeholder",
Command = "gphone_hands"
})
panel:AddControl("CheckBox", {
Label = "Flip the viewmodel to be left-handed",
Command = "gphone_lefthand"
})
panel:AddControl( "Slider", {
Label = "Viewmodel bobbing",
Command = "gphone_bob",
Type = "Float",
Min = 0,
Max = 4
})
panel:AddControl( "Slider", {
Label = "Homescreen rows",
Command = "gphone_rows",
Min = 1,
Max = 6
})
panel:AddControl( "Slider", {
Label = "Screen brightness",
Command = "gphone_brightness",
Type = "Float",
Min = 0,
Max = 1
})
panel:AddControl( "Slider", {
Label = "Phone volume",
Command = "gphone_volume",
Type = "Float",
Min = 0,
Max = 1
})
panel:AddControl( "Slider", {
Label = "Sensitivity",
Command = "gphone_sensitivity",
Type = "Float",
Min = 0.5,
Max = 6
})
panel:AddControl( "Slider", {
Label = "Hold time",
Command = "gphone_holdtime",
Type = "Float",
Min = 0.1,
Max = 1.5
})
panel:AddControl( "Slider", {
Label = "Face-to-phone distance",
Command = "gphone_focus",
Type = "Float",
Min = -5,
Max = 5
})
panel:AddControl( "Slider", {
Label = "Cursor size",
Command = "gphone_cursorsize",
Min = 12,
Max = 90
})
panel:MatSelect("gphone_cursormat", list.Get( "CursorMaterials" ), true, 0.25, 0.25)
panel:MatSelect("gphone_case", list.Get( "CaseMaterials" ), true, 0.25, 0.25)
end
local function GPDebugSettingsPanel(panel)
panel:ClearControls()
GPErrorTextField = vgui.Create("DTextEntry", panel)
GPErrorTextField:SetText(string.Implode("\n", GPhone.Log))
GPErrorTextField:SetMultiline(true)
GPErrorTextField:SetDrawLanguageID(false)
GPErrorTextField:SetVerticalScrollbarEnabled(true)
GPErrorTextField:SetTall(512)
GPErrorTextField:SetPlaceholderText("Nothing logged")
function GPErrorTextField:AllowInput(key)
return true
end
panel:AddItem(GPErrorTextField)
panel:AddControl("Button", {
Label = "Report error",
Command = "gphone_log_report"
})
panel:AddControl("Button", {
Label = "Output log in console",
Command = "gphone_log_print"
})
panel:AddControl("Button", {
Label = "Copy log to clipboard",
Command = "gphone_log_copy"
})
panel:AddControl("Button", {
Label = "Wipe log",
Command = "gphone_log_wipe"
})
panel:AddControl("Button", {
Label = "Redownload images",
Command = "gphone_redownloadimages"
})
panel:AddControl("Button", {
Label = "Clear image cache",
Command = "gphone_clearcache"
})
local but = panel:AddControl("Button", {
Label = "Factory Reset",
Command = "gphone_reset"
})
but:SetTextColor(Color(255, 0, 0))
but:SetToolTip("Warning! Resets all data from the phone")
end
hook.Add("PopulateToolMenu", "GPhoneCvarsPanel", function()
spawnmenu.AddToolMenuOption("Options", "GPhone", "GPhone", "Settings", "", "", GPSettingsPanel)
spawnmenu.AddToolMenuOption("Options", "GPhone", "GPhoneDebug", "Debugging", "", "", GPDebugSettingsPanel)
spawnmenu.AddToolMenuOption("Options", "GPhone", "GPhoneAdmin", "Admin Settings", "", "", GPAdminSettingsPanel)
end)
end<file_sep>GPnl = {}
local function parentPos( frame )
if frame then
local px,py = parentPos( frame.parent )
local x,y = frame.x,frame.y
return x + px,y + py
else
return 0,0
end
end
local function removeChildren( pnl )
if pnl.OnRemove then
pnl:OnRemove()
end
for _,child in pairs(pnl.children) do
removeChildren( child )
end
end
local gframe = {}
function gframe:new( parent, kind )
local frame = {
x = 0,
y = 0,
w = 32,
h = 32,
parent = parent,
children = {},
type = kind or "panel",
visible = true
}
function frame:SetVisible( bool )
self.visible = bool
return self
end
function frame:GetVisible()
return self.visible
end
function frame:SetType( str )
self.type = str
return self
end
function frame:GetType()
return self.type
end
function frame:SetPos( x, y )
self.x = x
self.y = y
return self
end
function frame:SetWidth( w )
self.w = w
return self
end
function frame:SetHeight( h )
self.h = h
return self
end
function frame:SetSize( w, h )
self.w = w
self.h = h
return self
end
function frame:GetWidth()
return self.w
end
function frame:GetHeight()
return self.h
end
function frame:GetSize()
return self.w,self.h
end
function frame:GetPos()
return self.x,self.y
end
function frame:SetParent( parent ) -- Technically you could have an infinite loop if you are not careful
if self.parent then
local children = self.parent.children
if table.HasValue(children, self) then
table.RemoveByValue(children, self)
end
end
self.parent = parent
if !table.HasValue(parent.children, self) then
table.insert(parent.children, self)
end
return true
end
function frame:GetParent()
return self.parent
end
function frame:GetChildren()
return self.children
end
function frame:Clear()
for _,child in pairs(self.children) do
removeChildren( child )
end
self.children = {}
return self
end
function frame:Remove()
removeChildren( self )
if self.parent then
local children = self.parent.children
if table.HasValue(children, self) then
table.RemoveByValue(children, self)
end
end
return self
end
function frame:Paint()
end
function frame:Hover()
end
function frame:StopHover()
end
if parent and parent.children then
table.insert(parent.children, frame)
end
local def = GPnl.GetTypes()[kind]
if def and type(def) == "function" then
def( frame )
end
setmetatable( frame, self )
return frame
end
function gframe:__tostring()
return "GPnl["..math.Round(self.x, 2)..","..math.Round(self.y, 2)..","..math.Round(self.w, 2)..","..math.Round(self.h, 2).."]["..self.type.."]"
end
function gframe:__add( frame )
if type(frame) == "table" and getmetatable(frame) then
frame:SetParent( self )
end
return self
end
gframe.__index = gframe
setmetatable( gframe, { __call = gframe.new } )
local paneltypes = {
["panel"] = true,
["frame"] = function(frame)
frame.b_tabs = {}
frame.b_tab = nil
function frame:AddTab( name, kind )
if type(kind) == "table" and getmetatable(kind) then
kind:SetVisible( false )
self.b_tabs[name] = kind
return kind
elseif type(kind) == "string" then
local pnl = GPnl.AddPanel( self, kind )
pnl:SetPos( 0, 0 )
pnl:SetSize( self:GetSize() )
pnl:SetVisible( false )
self.b_tabs[name] = pnl
return pnl
end
return false
end
function frame:RemoveTab( name )
local pnl = self.b_tabs[name]
if pnl then
if self.b_tab == pnl then
self.b_tab = nil
end
pnl:Remove()
self.b_tabs[name] = nil
end
return self
end
function frame:GetTabs()
return self.b_tabs
end
function frame:GetTab( name )
return self.b_tabs[name] or false
end
function frame:GetOpenTab()
return self.b_tab
end
function frame:OpenTab( name, time, newanim, oldanim )
local pnl = self.b_tabs[name]
if !pnl or self.b_tab == pnl then return false end
if self.b_tab then
if time and oldanim then
GPnl.DoAnimation( self.b_tab, time, oldanim, function(pnl)
pnl:SetPos( 0, 0 )
pnl:SetVisible( false )
end)
else
self.b_tab:SetVisible( false )
end
end
pnl:SetVisible( true )
if time and newanim then
GPnl.DoAnimation( pnl, time, newanim, function(pnl)
pnl:SetPos( 0, 0 )
end)
end
self.b_tab = pnl
return true
end
end,
["toggle"] = function(frame)
frame.b_padding = 4 * GPhone.Resolution
function frame:Paint( x, y, w, h )
local bgcol = self.b_negative and Color(80, 80, 80) or Color(200, 200, 200)
local btcol = self.b_negative and Color(80, 80, 80) or Color(255, 255, 255)
local atcol = self.b_toggled and Color(0, 255, 0) or self.b_negative and Color(150, 150, 150) or Color(220, 220, 220)
draw.RoundedBox(h/2, 0, 0, w, h, bgcol )
draw.RoundedBox(h/2, self.b_padding/2, self.b_padding/2, w - self.b_padding, h - self.b_padding, atcol )
draw.RoundedBox(h/2, self.b_padding + (w - h) * (self.b_toggled and 1 or 0), self.b_padding, h - self.b_padding*2, h - self.b_padding*2, btcol )
end
function frame:SetToggle( bool )
self.b_toggled = bool
return self
end
function frame:GetToggle()
return self.b_toggled or false
end
function frame:SetNegative( bool )
self.b_negative = bool
return self
end
function frame:GetNegative()
return self.b_negative or false
end
function frame:OnClick()
local bool = !self.b_toggled
self.b_toggled = bool
if self.OnChange then
self:OnChange( bool )
end
end
end,
["scroll"] = function(frame)
function frame:SetScrollSpeed( num )
self.i_speed = num
return self
end
function frame:GetScrollSpeed()
return (self.i_speed or 30) * GPhone.Resolution
end
function frame:OnScroll( num )
local height = self:GetHeight()
local min = height
local max = 0
for _,c in pairs(frame.children) do
min = math.min(min, c.y)
max = math.max(max, c.y + c.h)
end
if num < 0 and max <= height then return end
if num > 0 and min >= 0 then return end
for k,c in pairs(frame.children) do
c.y = c.y + num * self:GetScrollSpeed()
end
end
end,
["textentry"] = function(frame)
frame.b_forecolor = Color(0, 0, 0)
frame.b_backcolor = Color(220, 220, 220)
frame.b_selccolor = Color(0, 50, 100, 100)
frame.b_alignmenth = TEXT_ALIGN_LEFT
frame.b_alignmentv = TEXT_ALIGN_CENTER
function frame:SetText( val )
self.b_text = val
return self
end
function frame:GetText()
return self.b_text or ""
end
function frame:SetFont( font )
self.f_font = font
return self
end
function frame:GetFont()
return self.f_font or "GPMedium"
end
function frame:SetAlignment( hor, ver )
frame.b_alignmenth = hor
frame.b_alignmentv = ver
return self
end
function frame:GetAlignment()
return frame.b_alignmenth,frame.b_alignmentv
end
function frame:SetForeColor( color )
self.b_forecolor = color
return self
end
function frame:GetForeColor()
return self.b_forecolor
end
function frame:SetBackColor( color )
self.b_backcolor = color
return self
end
function frame:GetBackColor()
return self.b_backcolor
end
function frame:SetSelectionColor( color )
self.b_selccolor = color
return self
end
function frame:GetSelectionColor()
return self.b_selccolor
end
function frame.Cancel()
frame.b_typing = false
frame:OnCancel()
end
function frame.Enter( value )
frame.b_typing = false
frame:OnEnter( value )
end
function frame.Change( value )
frame:OnChange( value )
end
function frame:OnCancel()
end
function frame:OnEnter()
end
function frame:OnChange()
end
function frame:OnClick()
self.b_typing = true
GPhone.InputText( self.Enter, self.Change, self.Cancel, self:GetText() )
end
function frame:RenderText( x, y, w, h, text, hidecaret )
if self.b_backcolor.a > 0 then
draw.RoundedBox( 0, 0, 0, w, h, self.b_backcolor )
end
surface.SetFont(self:GetFont())
local start,stop = GPhone.GetSelectedRange()
local caretindex = GPhone.GetCaretPos()
local sizew,sizeh = surface.GetTextSize(text)
local sw = surface.GetTextSize(string.sub(text, start + 1, stop))
local tw = surface.GetTextSize(string.sub(text, 0, caretindex))
local sx = 0
local cx,cy = 0,0
local tx,ty = 0,0
if self.b_alignmenth == TEXT_ALIGN_LEFT then
if tw > w / 2 then
if stop > caretindex then
sx = w / 2 - 4
else
sx = w / 2 - sw
end
cx = w / 2 - 4
tx = w / 2 - 4 - tw
else
if stop > caretindex then
sx = tw
else
sx = tw - sw
end
cx = tw
tx = 4
end
elseif self.b_alignmenth == TEXT_ALIGN_RIGHT then
if !self.b_typing or sizew - tw < w / 2 then
if stop > caretindex then
sx = w - sizew + tw - 4
else
sx = w - sizew + tw - 4 - sw
end
cx = w - sizew + tw - 4
tx = w - 4
else
if stop > caretindex then
sx = w / 2 - 4
else
sx = w / 2 - 4 - sw
end
cx = w / 2 - 4
tx = w / 2 + sizew - 4 - tw
end
else
if self.b_typing then
if stop > caretindex then
sx = w / 2
else
sx = w / 2 - sw
end
tx = sizew / 2 + w / 2 - tw
cx = w / 2
else
tx = w / 2
end
end
if self.b_alignmentv == TEXT_ALIGN_TOP then
cy = 4
ty = 4
elseif self.b_alignmentv == TEXT_ALIGN_BOTTOM then
cy = h - 4 - sizeh
ty = h - 4
else
cy = h / 2 - sizeh / 2
ty = h / 2
end
draw.SimpleText(text, self:GetFont(), tx, ty, self.b_forecolor, frame.b_alignmenth, frame.b_alignmentv)
if !hidecaret and self.b_typing then
draw.RoundedBox( 0, sx, cy, sw, sizeh, self.b_selccolor )
draw.RoundedBox( 0, cx, cy, math.ceil(2 * GPhone.Resolution), sizeh, self.b_forecolor )
end
end
function frame:Paint( x, y, w, h )
local text = self.b_typing and GPhone.GetInputText() or self:GetText()
self:RenderText( x, y, w, h, text )
end
end,
["html"] = function(frame)
function frame:Init( url ) -- Call this after setting the size
if IsValid(self.d_html) then
GPhone.CloseHTMLPanel( self.d_html )
end
local w,h = self:GetSize()
self.d_html = GPhone.CreateHTMLPanel( w, h, url )
return self
end
function frame:GetHTML()
return self.d_html
end
function frame:GetTitle()
return IsValid(self.d_html) and self.d_html.Title or false
end
function frame:OnRemove()
GPhone.CloseHTMLPanel( self:GetHTML() )
end
function frame:Paint( x, y, w, h )
surface.SetDrawColor( 255, 255, 255 )
surface.SetMaterial( GPhone.GetHTMLMaterial( self:GetHTML() ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
function frame:OpenURL( url )
self.d_html:OpenURL( url )
return self
end
function frame:OnClick()
local mx,my = GPhone.GetCursorPos()
local x,y = GPhone.GetHTMLPos( self, self:GetHTML(), mx, my )
GPhone.PerformHTMLClick( self:GetHTML(), x, y )
end
function frame:OnScroll( num )
local val = -num * 75 * GPhone.Resolution
self.d_html:RunJavascript( [[window.scrollBy(0, ]]..val..[[);]] )
end
end,
["video"] = function(frame)
function frame:Open( path )
local ext = string.GetExtensionFromFilename(path)
if ext != "mp4" and ext != "webm" then return false end -- Only .mp4 and .webm supported
if !file.Exists(path, "GAME") then return false end
local r = file.Read(path, "GAME")
local data = util.Base64Encode( r ) -- This is very intense, but I don't see any other way
if IsValid(self.d_html) then
GPhone.CloseHTMLPanel( self.d_html )
end
local w,h = self:GetSize()
self.d_html = GPhone.CreateHTMLPanel( w, h )
self.d_html:SetHTML([[<!doctype html>
<html>
<body style="overflow:hidden">
<video id="player" width="100%" height="100%" loop autoplay>
<source src="data:video/]]..ext..[[;base64,]]..data..[[" type="video/]]..ext..[[">
Your browser does not support the video tag.
</video>
<script type="text/javascript">
var vid = document.getElementById("player");
</script>
</body>
</html>]])
return true
end
function frame:GetHTML()
return self.d_html
end
function frame:OnRemove()
GPhone.CloseHTMLPanel( self:GetHTML() )
end
function frame:Paint( x, y, w, h )
surface.SetDrawColor( 255, 255, 255 )
surface.SetMaterial( GPhone.GetHTMLMaterial( self:GetHTML() ) )
surface.DrawTexturedRect( 0, 0, w, h )
end
function frame:OnClick() -- TODO: Pause and play when clicked
end
end
}
local panelanims = {
["in-right"] = function(frame, delta, x, y)
frame:SetPos( x + frame:GetWidth() * (1-delta), y )
end,
["in-left"] = function(frame, delta, x, y)
frame:SetPos( x + frame:GetWidth() * (delta-1), y )
end,
["in-bottom"] = function(frame, delta, x, y)
frame:SetPos( x, y + frame:GetHeight() * (1-delta) )
end,
["in-top"] = function(frame, delta, x, y)
frame:SetPos( x, y + frame:GetHeight() * (delta-1) )
end,
["out-right"] = function(frame, delta, x, y)
frame:SetPos( x + frame:GetWidth() * delta, y )
end,
["out-left"] = function(frame, delta, x, y)
frame:SetPos( x - frame:GetWidth() * delta, y )
end,
["out-bottom"] = function(frame, delta, x, y)
frame:SetPos( x, y + frame:GetHeight() * delta )
end,
["out-top"] = function(frame, delta, x, y)
frame:SetPos( x, y - frame:GetHeight() * delta )
end
}
function GPnl.GetTypes()
return paneltypes
end
function GPnl.GetAnims()
return panelanims
end
function GPnl.AddType(name, func)
paneltypes[name] = func
end
function GPnl.AddAnimation(name, func)
panelanims[name] = func
end
function GPnl.AddPanel( parent, kind )
local frame = gframe( parent, kind )
return frame
end
function GPnl.DoAnimation( frame, time, func, stop )
if panelanims[func] then
func = panelanims[func]
elseif type(func) != "function" then
return false
end
local x,y = frame:GetPos()
GPhone.DebugFunction( func, frame, 0, x, y )
frame.f_anim = {
start = CurTime(),
pos = {x = x, y = y},
max = time,
func = func,
stop = stop
}
return true
end
hook.Add("PlayerBindPress", "_PlayerScrollGPanel", function(ply, bind, pressed)
local wep = ply:GetActiveWeapon()
if IsValid(wep) and wep:GetClass() == "gmod_gphone" and GPhone.CursorEnabled and pressed then
if bind == "invprev" or bind == "invnext" then
local frame = GPhone.CurrentFrame
local num = (bind == "invprev" and 1 or -1)
if GPhone.AppScreen and GPhone.AppScreen.Enabled then
local max = table.Count(GPhone.Panels) - 1
GPhone.AppScreen.Scroll = math.Clamp(GPhone.AppScreen.Scroll + num, -max, 0)
return true
elseif frame and frame.visible then
local x,y = GPhone.GetCursorPos()
local children = {}
local function scrollChildren( pnl )
local px,py = parentPos( pnl )
local bx,by,bw,bh = px,py,pnl.w,pnl.h
if x < bx or x > bx + bw or y < by or y > by + bh or !pnl.visible then return end
table.insert(children, pnl)
for _,child in pairs(pnl.children) do
scrollChildren( child )
end
end
scrollChildren( frame )
local function scrollParent( pnl )
if pnl.OnScroll then
pnl:OnScroll( num )
elseif pnl.parent then
scrollParent( pnl.parent )
end
end
local pnl = children[#children]
if pnl then
scrollParent( pnl )
end
return true
else
GPhone.Page = math.Clamp(GPhone.Page - num, 1, #GPhone.GetAppPos())
return true
end
end
end
end)<file_sep>if !GPhone then
GPhone = {}
GPhone.Data = {}
GPhone.SharedHooks = {}
GPhone.Panels = {}
GPhone.ImageQueue = {}
GPhone.ImageHistory = {}
GPhone.ImageCache = {}
GPhone.AppThumbnails = {}
GPhone.MusicStream = {}
GPhone.AwaitingCalls = {}
GPhone.HTML = {}
GPhone.Log = {}
GPhone.Apps = {}
GPhone.BackgroundMat = nil
GPhone.CurrentApp = nil
GPhone.CurrentFrame = nil
GPhone.MovingApp = nil
GPhone.MoveMode = nil
GPhone.MusicURL = nil
GPhone.InputField = nil
GPhone.VoiceChatter = nil
GPhone.Selfie = false
GPhone.Landscape = false
GPhone.CursorEnabled = false
GPhone.Page = 1
GPhone.Ratio = 56 / 83
GPhone.Height = ScrH() / 1.032 -- Scaling with rendertargets is weird
GPhone.Width = GPhone.Height * GPhone.Ratio
GPhone.Resolution = GPhone.Height / 830
GPhone.CursorPos = {x = 560, y = 830}
GPhone.Rows = 4 -- Placeholder
GPhone.Desk = {
Spacing = 24 * GPhone.Resolution,
Offset = 40 * GPhone.Resolution
}
GPhone.AppScreen = {
Enabled = false,
Scroll = 0,
Offset = 64 * GPhone.Resolution,
Spacing = 24 * GPhone.Resolution,
Scale = 0.6
}
local w,h = math.floor(GPhone.Width*1.032),math.floor(GPhone.Height*1.032)
GPhone.PhoneRT = GetRenderTarget("GPScreenRT_"..math.ceil(GPhone.Height), w, h, false)
GPhone.PhoneLSRT = GetRenderTarget("GPScreenLSRT_"..math.ceil(GPhone.Height), h, w, false)
GPhone.PhoneMT = CreateMaterial(
"GPScreenMT_"..math.ceil(GPhone.Height),
"UnlitGeneric",
{
["$basetexture"] = GPhone.PhoneRT,
["$basetexturetransform"] = "center .5 .5 scale 1 1 rotate 0 translate 0 0",
["$vertexcolor"] = 1,
["$vertexalpha"] = 1
}
)
GPhone.CamRT = GetRenderTarget("GPCameraRT_"..math.ceil(GPhone.Height), GPhone.Width, GPhone.Height, false)
GPhone.CamLSRT = GetRenderTarget("GPCameraLSRT_"..math.ceil(GPhone.Height), GPhone.Height, GPhone.Width, false)
GPhone.CamMT = CreateMaterial(
"GPCameraMT_"..math.ceil(GPhone.Height),
"GMODScreenspace",
{
["$basetexture"] = GPhone.CamRT,
["$basetexturetransform"] = "center .5 .5 scale -1 -1 rotate 0 translate 0 0",
["$vertexcolor"] = 1,
["$vertexalpha"] = 1,
}
)
end
local function get_width(str, font)
surface.SetFont(font)
local w, h = surface.GetTextSize(str)
return w
end
function GPhone.WordWrap(str, match_width, font)
local breakup = string.Explode(" ", str)
local storage = {}
local current_line = 1
if get_width(str, font) <= match_width then
return { str }
end
local function newtab(t)
local n = {}
for k,v in pairs(t) do
n[#n + 1] = v
end
return n
end
local function loopy( up )
for k,v in pairs(up) do
if not storage[current_line] then
storage[current_line] = ""
if get_width(v, font) > match_width then
-- break it up, yeee.
local solo = string.ToTable(v)
local s = ""
for a,char in pairs( solo ) do
if get_width(s .. char, font) > match_width then
local rest = string.sub( v, a, #v )
up[k] = rest
storage[current_line] = s
current_line = current_line + 1
local reset = newtab( up )
return loopy( reset )
else
s = s .. char
end
end
else
-- define that line with our first word.
storage[current_line] = v
up[k] = nil
end
else -- already did a word.
local current_text = storage[current_line]
if get_width(current_text .. " " .. v, font) > match_width then
current_line = current_line + 1
local reset = newtab( up )
return loopy( reset )
else
storage[current_line] = current_text .. " " .. v
up[k] = nil
end
end
end
end
loopy( breakup )
return storage
end
local function parentPos(p)
if p then
local px,py = parentPos(p.parent)
local x,y = p.x,p.y
return x+px,y+py
else
return 0,0
end
end
local function resetGPhoneData()
local data = table.Copy(GPDefaultData)
file.Write("gphone/users/client.txt", util.TableToJSON(data))
GPhone.Data = data
GPhone.FocusHome()
end
function GPhone.GetRows()
return math.ceil(GPhone.Rows * (GPhone.Landscape and GPhone.Resolution or 1))
end
function GPhone.GetAppSize(spacing)
local w = GPhone.Width
local spacing = spacing or GPhone.Desk.Spacing
local rows = GPhone.GetRows()
return (w/rows)-spacing*(1+(1/rows))
end
function GPhone.GetAppPos() -- Became tired of doing all this manually... This is a much better solution since it's dynamic
local apps = GPhone.GetData("apps", {})
local w = GPhone.Width
local h = GPhone.Height
local spacing = GPhone.Desk.Spacing
local rows = GPhone.GetRows()
local columns = math.ceil(rows * GPhone.Resolution)
local offset = GPhone.Desk.Offset
local size = GPhone.GetAppSize(spacing, rows)
local ratio = GPhone.Resolution
surface.SetFont("GPAppName"..GPhone.Rows)
local _,th = surface.GetTextSize("I")
local pages = {}
local highest = 0
for k,appid in pairs(apps) do
local app = GPhone.GetApp(appid)
if !app or app.Launcher then continue end
if k > highest then highest = k end
end
local posx = 0
local posy = math.floor((highest - 1) / rows)
local page = math.ceil((posy + 1) / (columns - 1))
for i = 1, math.max(page, GPhone.Page) do
pages[i] = {}
end
for k,appid in pairs(apps) do
local app = GPhone.GetApp(appid)
if !app or app.Launcher then continue end
posx = 1 + math.floor((k - 1) % rows)
posy = math.floor((k - 1) / rows)
page = math.ceil((posy + 1) / (columns - 1))
posy = posy - (page - 1) * (columns - 1)
local x,y = spacing + (posx - 1) * (size + spacing), offset + spacing + posy * (size + th * ratio)
table.insert(pages[page], {x = x, y = y, size = size, app = appid})
end
return pages
end
function GPhone.GetPage(id)
local windows = GPhone.GetAppPos()
local page = windows[math.Clamp(id or GPhone.Page, 1, #windows)]
return page
end
function GPhone.AppThumbnail(id)
local cv = GetConVar("gphone_thumbnail")
local appid = id or GPhone.CurrentApp
if !cv or !cv:GetBool() then return end
local frame = GPhone.Panels[appid]
if !frame then return false end
local name = math.ceil(GPhone.Height).."_"..appid
local rt = GetRenderTarget("GPAppRT_"..name, GPhone.Width*1.032, (GPhone.Height - GPhone.Desk.Offset)*1.032, false)
local mat = CreateMaterial(
"GPAppMT_"..name,
"UnlitGeneric",
{
["$basetexture"] = rt,
["$vertexcolor"] = 1,
["$vertexalpha"] = 1
}
)
render.PushRenderTarget(rt)
render.Clear(0, 0, 0, 255, true, true)
cam.Start2D()
local oldw,oldh = ScrW(), ScrH()
local function drawChildren(pnl)
if pnl.children then
for _,child in pairs(pnl.children) do
if !child.visible then continue end
if child.Paint then
local px,py = parentPos(child.parent)
local max,may = GPhone.Width*0.016 + math.max(px + child.x, 0), GPhone.Height*0.016 + math.max(py + child.y, 0)
local mix,miy = math.min(GPhone.Width*0.016 + px + child.x + child.w, GPhone.PhoneMT:Width()), math.min(GPhone.Height*0.016 + py + child.y + child.h, GPhone.PhoneMT:Height())
if mix < 0 or miy < 0 or max > GPhone.Width*1.032 or may > GPhone.Height*1.032 then continue end
render.SetViewPort(max, may, oldw, oldh)
render.SetScissorRect(max, may, mix, miy, true)
GPhone.DebugFunction(child.Paint, child, px + child.x, py + child.y, child.w, child.h)
render.SetScissorRect(0, 0, 0, 0, false)
end
drawChildren(child)
end
end
end
local old = frame.y
frame.y = 0
if frame.Paint then
render.SetViewPort(GPhone.Width*0.016, GPhone.Height*0.016, oldw, oldh)
GPhone.DebugFunction(frame.Paint, frame, frame.x, frame.y, GPhone.Width, GPhone.Height)
end
drawChildren(frame)
frame.y = old
render.SetViewPort(0, 0, oldw, oldh)
cam.End2D()
render.PopRenderTarget()
mat:SetTexture("$basetexture", rt)
GPhone.AppThumbnails[appid] = mat
return true
end
function GPhone.GetThumbnail(id)
return GPhone.AppThumbnails[id]
end
function GPhone.AddApp(name, tbl)
if !name or type(tbl) != "table" or !tbl.Name then return false end
GPhone.GetApps()[name] = tbl
return true
end
function GPhone.GetApp(name)
local app = GPhone.GetApps()[name]
return app or false
end
function GPhone.GetApps()
return GPhone.Apps
end
surface.CreateFont("GPTopBar", { font = "Open Sans Light", size = 34 * GPhone.Resolution, additive = false, shadow = false})
for i = 1, 6 do
surface.CreateFont("GPAppName"..i, { font = "Open Sans Light", size = 120 * GPhone.Resolution / i, additive = false, shadow = false})
end
surface.CreateFont("GPSmall", { font = "Open Sans", size = 28 * GPhone.Resolution, additive = false, shadow = false})
surface.CreateFont("GPMedium", { font = "Open Sans", size = 36 * GPhone.Resolution, additive = false, shadow = false})
surface.CreateFont("GPTitle", { font = "Open Sans", size = 44 * GPhone.Resolution, additive = false, shadow = false})
surface.CreateFont("GPBugReport", { font = "Open Sans", size = 48 * GPhone.Resolution, additive = false, shadow = false})
surface.CreateFont("GPLoading", { font = "Open Sans", size = 128, additive = false, shadow = false})
surface.CreateFont("GPAppBuilder", { font = "Open Sans", size = 30, additive = false, shadow = false})
concommand.Add("gphone_log_wipe", function()
GPhone.WipeLog()
end)
concommand.Add("gphone_log_print", function()
GPhone.PrintLog()
end)
concommand.Add("gphone_log_copy", function()
if #GPhone.Log <= 0 then return end
SetClipboardText(string.Implode("\r\n", GPhone.Log))
end)
concommand.Add("gphone_log_report", function()
if IsValid(GPReporter) then return end
if #GPhone.Log <= 0 then return end
local w,h = ScrW()/2,ScrH()/2
local padding = 10
local offset = 30
GPReporter = vgui.Create("DFrame")
GPReporter:SetSize(w, h)
GPReporter:SetTitle("")
GPReporter:SetDraggable(false)
GPReporter:ShowCloseButton(false)
GPReporter:SetSizable(false)
GPReporter.Paint = function(self)
draw.RoundedBox(0, 0, 0, self:GetWide(), self:GetTall(), Color(70,70,70))
end
GPReporter:MakePopup()
GPReporter:Center()
local message = vgui.Create("DTextEntry", GPReporter)
message:SetText("")
message:SetPos(padding, padding)
message:SetSize(w/2 - padding*2, h - padding*3 - offset)
message:SetDrawLanguageID(false)
message:SetMultiline(true)
message:SetPlaceholderText("What did you do for the error to appear?")
message:RequestFocus()
local log = vgui.Create("DTextEntry", GPReporter)
log:SetText(string.Implode("\n", GPhone.Log))
log:SetPos(w/2, padding)
log:SetSize(w/2 - padding, h - padding*3 - offset)
log:SetVerticalScrollbarEnabled(true)
log:SetDrawLanguageID(false)
log:SetMultiline(true)
log:SetEditable(false)
log:SetPlaceholderText("Nothing logged")
log.Log = string.Trim(string.Implode("\r\n", GPhone.Log))
local report = vgui.Create("DButton", GPReporter)
report:SetPos(padding, h - padding - offset)
report:SetSize(w/2 - padding * 2, offset)
report:SetText("Report")
report:SetTextColor(Color(255,255,255))
function report:Paint()
if self.Hovering then
surface.SetDrawColor(0, 200, 0)
else
surface.SetDrawColor(40, 150, 40)
end
surface.DrawRect(0, 0, self:GetWide(), self:GetTall())
end
function report:OnCursorEntered()
self.Hovering = true
if message:GetValue() == "" then
self:SetText("Write a message first")
else
self:SetText("PRESS CTRL + V IN THE DISCUSSION")
end
end
function report:OnCursorExited()
self:SetText("Report")
self.Hovering = false
end
function report:DoClick()
local err = message:GetValue()
if err == "" then
message:RequestFocus()
else
hook.Add("PostDrawHUD", "GPhoneBugReportOverlay", function()
surface.SetDrawColor(0, 0, 0)
surface.DrawRect(0, 0, ScrW(), ScrH())
draw.SimpleText("Press \"Yes\" and the error discussion will open", "GPBugReport", ScrW()/2, ScrH()/3, Color(255, 255, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
draw.SimpleText("Press Ctrl + V in the discussion to post the error report", "GPBugReport", ScrW()/2, ScrH()/3*2, Color(255, 255, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
hook.Add("HUDPaint", "GPhoneBugReportRemove", function()
hook.Remove("PostDrawHUD", "GPhoneBugReportOverlay")
hook.Remove("HUDPaint", "GPhoneBugReportRemove")
end)
end)
SetClipboardText(err.."\r\n[code]\r\n"..log.Log.."\r\n[/code]")
GPReporter:Remove()
gui.OpenURL("https://steamcommunity.com/workshop/filedetails/discussion/1370983401/1696045708645315297/")
end
end
local cancel = vgui.Create("DButton", GPReporter)
cancel:SetPos(w/2, h - padding - offset)
cancel:SetSize(w/2 - padding, offset)
cancel:SetText("Cancel")
cancel:SetTextColor(Color(255,255,255))
function cancel:Paint()
if self.Hovering then
surface.SetDrawColor(255, 0, 0)
else
surface.SetDrawColor(180, 40, 40)
end
surface.DrawRect(0, 0, self:GetWide(), self:GetTall())
end
function cancel:OnCursorEntered()
self.Hovering = true
self:SetText("Are you sure?")
end
function cancel:OnCursorExited()
self:SetText("Cancel")
self.Hovering = false
end
function cancel:DoClick()
GPReporter:Remove()
end
end)
concommand.Add("gphone_redownloadimages", function()
local tbl = table.Copy(GPhone.ImageHistory)
GPhone.ImageCache = {}
GPhone.ImageQueue = {}
GPhone.ImageHistory = {}
ImgReady = nil
ImgDownloadTime = nil
if IsValid(DownLoadHTML) then
DownLoadHTML:Remove()
DownLoadHTML = nil
end
for img,data in pairs(tbl) do
GPhone.DownloadImage(data.URL, data.Size, data.Style)
end
end)
concommand.Add("gphone_clearcache", function()
GPhone.ImageQueue = {}
GPhone.ImageCache = {}
GPhone.ImageHistory = {}
ImgReady = nil
ImgDownloadTime = nil
if IsValid(DownLoadHTML) then
DownLoadHTML:Remove()
DownLoadHTML = nil
end
end)
concommand.Add("gphone_reset", function()
GPhone.StopMusic()
GPhone.CloseInput()
GPhone.Log = {}
GPhone.MovingApp = nil
GPhone.MoveMode = nil
GPhone.MusicURL = nil
GPhone.AppScreen.Enabled = false
for name,_ in pairs(GPhone.Panels) do
GPhone.StopApp(name)
end
local cv = GetConVar("gphone_sync")
if game.SinglePlayer() or cv and cv:GetBool() then
resetGPhoneData()
else
net.Start("GPhone_Reset")
net.SendToServer()
end
end)
net.Receive("GPhone_Load_Client", function(len)
local cv = GetConVar("gphone_sync")
if game.SinglePlayer() or cv and cv:GetBool() then
if file.Exists("gphone/users/client.txt", "DATA") then
local tbl = util.JSONToTable(file.Read("gphone/users/client.txt", "DATA"))
if !tbl then
resetGPhoneData()
return
end
local apps = {}
for _,id in pairs(GPDefaultApps) do -- Fix default apps
if !table.HasValue(tbl.apps, id) then
table.insert(apps, id)
end
end
if #apps > 0 then
table.Add(tbl.apps, apps)
file.Write("gphone/users/client.txt", util.TableToJSON(tbl))
print("[GPhone] Added "..#apps.." missing default apps")
end
GPhone.Data = tbl
else
resetGPhoneData()
end
else
local tbl = net.ReadTable()
GPhone.Data = tbl
end
GPhone.FocusHome()
end)
local function ReceiveSharedData(ply, name, data)
local hookOverride = hook.Run("GPhoneDataReceived", ply, name, data)
if hookOverride then return end
local func = GPhone.SharedHooks[name]
if func then
local funcOverride = GPhone.DebugFunction(func, ply, name, data)
if funcOverride then return end
end
local shared = GPhone.GetData("shared", {})
shared[name] = data
GPhone.SetData("shared", shared)
end
net.Receive("GPhone_Share_Data", function(len)
local ply = net.ReadEntity()
local name = net.ReadString()
local data = net.ReadTable()
local enabled = GetConVar("gphone_sharedata")
if !enabled:GetBool() then return end
local ask = GetConVar("gphone_askdata")
if ask:GetBool() then
GPhone.ConfirmDialog("Allow packet?", ply:Nick().." wants to send a \""..name.."\" packet to you", function()
ReceiveSharedData(ply, name, data)
end)
else
ReceiveSharedData(ply, name, data)
end
end)
net.Receive("GPhone_Rotate", function(len)
GPhone.Rotate(!GPhone.Landscape)
end)
net.Receive("GPhone_VoiceCall_Request", function(len) -- Somebody requested your presence in a voicecall
local chatter = net.ReadEntity()
local calls = GPhone.GetIncomingVoiceChats()
table.insert(calls, chatter)
end)
net.Receive("GPhone_VoiceCall_Stop", function(len) -- Someone denied your voice request
GPhone.VoiceChatter = false
end)
function GPhone.LoadImages()
local background = GPhone.Data.background or ""
if string.StartWith(background, "http://") or string.StartWith(background, "https://") or background == "" then
GPhone.SetData("background", "materials/gphone/backgrounds/sky.jpg")
end
GPhone.BackgroundMat = Material(GPhone.Data.background, "smooth")
local css = GPhone.GetData("icon_css", "background-color: #FFF; border-radius: 32px 32px 32px 32px")
for k,app in pairs(GPhone.GetApps()) do
GPhone.DownloadImage(app.Icon, 128, css)
end
end
function GPhone.DebugFunction(func, ...)
local function catch(err)
local info = debug.getinfo(func)
local text = "[ERROR] "..err.."\n 1. unknown - "..info.short_src..":"..info.linedefined.."-"..info.lastlinedefined.."\n"
GPhone.Debug(text, false, true)
end
xpcall(func, catch, ...)
end
function GPhone.Debug(str, spam, err)
local last = GPhone.Log[#GPhone.Log]
if spam or last != str then -- Prevent spammed messages
table.insert(GPhone.Log, str)
if err then
ErrorNoHalt(str.."\n")
else
MsgN(str)
end
if IsValid(GPErrorTextField) then
GPErrorTextField:SetText(string.Implode("\n", GPhone.Log))
end
local cv = GetConVar("gphone_report")
if err and cv and cv:GetBool() then
RunConsoleCommand("gphone_log_report")
end
return true
end
return false
end
function GPhone.WipeLog()
GPhone.Log = {}
if IsValid(GPErrorTextField) then
GPErrorTextField:SetText("")
end
end
function GPhone.PrintLog()
for k,v in pairs(GPhone.Log) do
MsgN(v)
end
end
function GPhone.SetData(name, v)
GPhone.Data[name] = v
if name == "background" then
if string.StartWith(v, "http://") or string.StartWith(v, "https://") or v == "" or v == "https://raw.githubusercontent.com/KredeGC/GPhone/master/images/background.jpg" then
v = "materials/gphone/backgrounds/sky.jpg"
end
GPhone.BackgroundMat = Material(v, "smooth")
end
local cv = GetConVar("gphone_sync")
if !game.SinglePlayer() and (!cv or !cv:GetBool()) then
net.Start("GPhone_Change_Data")
net.WriteTable(GPhone.Data)
net.SendToServer()
else
file.Write("gphone/users/client.txt", util.TableToJSON(GPhone.Data))
end
end
function GPhone.GetData(name, def)
return GPhone.Data[name] or def or false
end
function GPhone.SetAppData(name, v, a)
local data = GPhone.GetAllAppData(a)
if !data then return end
data[name] = v
GPhone.SetAllAppData(data, a)
end
function GPhone.GetAppData(name, def, a)
local data = GPhone.GetAllAppData(a)
return data and data[name] or def or false
end
function GPhone.SetAllAppData(v, a)
local app = a or GPhone.CurrentApp
if !app then return false end
if !table.HasValue(GPhone.Data.apps, app) then return false end
local appdata = GPhone.GetData("appdata", {})
appdata[app] = v
GPhone.SetData("appdata", appdata)
end
function GPhone.GetAllAppData(a)
local app = a or GPhone.CurrentApp
if !app then return false end
local appdata = GPhone.GetData("appdata", {})
local data = appdata[app] or {}
return data
end
function GPhone.ClearAllAppData(a)
local app = a or GPhone.CurrentApp
if !app then return false end
local appdata = GPhone.GetData("appdata", {})
appdata[app] = nil
GPhone.SetData("appdata", appdata)
end
function GPhone.HookSharedData(name, func)
GPhone.SharedHooks[name] = func
end
function GPhone.UnHookSharedData(name)
GPhone.SharedHooks[name] = nil
end
function GPhone.SendSharedData(ply, name, data)
if IsValid(ply) and ply:IsPlayer() then -- and ply != LocalPlayer() then
net.Start("GPhone_Share_Data")
net.WriteEntity(ply)
net.WriteString(name)
net.WriteTable(data)
net.SendToServer()
return true
end
return false
end
function GPhone.GetSharedData(name, def)
local data = GPhone.GetData("shared", {})
return data[name] or def or false
end
function GPhone.TriggerDown()
local leftDown = input.IsMouseDown(MOUSE_LEFT)
if g_VR and g_VR.active then
leftDown = self.b_triggerdown
end
return leftDown
end
function GPhone.GetCursorPos()
local i = GPhone.Landscape
local p = GPhone.CursorPos
local x,y = p.x / 1120,p.y / 1660
return (i and y or x) * GPhone.Width,(i and (1 - x) or y) * GPhone.Height
end
function GPhone.LocalToRoot(pnl, x, y)
local px,py = parentPos(pnl)
return x + px, y + py
end
function GPhone.RootToLocal(pnl, x, y)
local px,py = parentPos(pnl)
return x - px, y - py
end
function GPhone.EnableSelfie(bool)
if GPhone.SelfieEnabled() == bool then return false end
GPhone.Selfie = bool
net.Start("GPhone_Selfie")
net.WriteBool(bool or false)
net.SendToServer()
return true
end
function GPhone.SelfieEnabled()
return GPhone.Selfie
end
function GPhone.CreateRootPanel()
local frame = GPnl.AddPanel(nil, "frame")
if !frame then return false end
local offset = GPhone.Desk.Offset
local w,h = GPhone.Width,GPhone.Height - offset
frame:SetPos(0, offset)
frame:SetSize(w, h)
frame.Remove = nil
frame.Landscape = GPhone.Landscape
function frame:SetFullScreen(bool)
self.b_fullscreen = bool
local offset = bool and 0 or GPhone.Desk.Offset
self:SetPos(0, offset)
self:SetHeight(GPhone.Height - offset)
return offset
end
function frame:GetFullScreen()
return self.b_fullscreen or false
end
return frame
end
function GPhone.RunApp(name, force)
local launcher = GPhone.GetData("launcher", "launcher")
local isLauncher = name == launcher
if !isLauncher and GPhone.Panels[name] and !force then -- Focus the app instead
GPhone.AppThumbnail()
GPhone.FocusApp(name)
return GPhone.Panels[name]
end
if !table.HasValue(GPhone.Data.apps, name) then return false end
local app = GPhone.GetApp(name)
if !app then return false end
local frame = GPhone.CreateRootPanel()
if !frame then return false end
local offset = GPhone.Desk.Offset
local w,h = GPhone.Width,GPhone.Height - offset
GPhone.AppThumbnail() -- In case it was run from inside an app
GPhone.CurrentFrame = frame
if !force then
GPhone.CurrentApp = name
if !isLauncher then
GPhone.Panels[name] = frame
end
end
if app.Run then
if type(app.Run) == "string" then
local str = RunString("appinit = "..app.Run, name, false)
if !str and appinit then
GPhone.DebugFunction(appinit, frame, w, h, GPhone.Resolution)
else
GPhone.Debug("[ERROR] App '"..(app.Name or name).."': "..str, false, true)
end
else
GPhone.DebugFunction(app.Run, frame, w, h, GPhone.Resolution)
end
end
local exclude = {}
local function checkChildren(pnl)
if pnl.children then
for _,child in pairs(pnl.children) do
if exclude[child] then
GPhone.CurrentFrame = nil
if GPhone.CurrentApp then
GPhone.Panels[GPhone.CurrentApp] = nil
end
GPhone.Debug("[ERROR] App '"..(app.Name or name).."' stuck in infinite loop\n 1. "..tostring(child).." - App terminated\n", true, true)
GPhone.FocusHome()
return false
end
exclude[child] = true
checkChildren(child)
end
end
end
checkChildren(frame)
return frame
end
function GPhone.StopApp(name)
local frame = GPhone.Panels[name]
if !frame then return false end
local app = GPhone.GetApp(name)
if app and app.Stop then
if type(app.Stop) == "string" then
local str = RunString("appdel = "..app.Stop, name, false)
if !str and appdel then
GPhone.DebugFunction(appdel, frame)
else
GPhone.Debug("[ERROR] App '"..(app.Name or name).."': "..str, false, true)
end
else
GPhone.DebugFunction(app.Stop, frame)
end
end
local function removeChildren(pnl)
if pnl.OnRemove then
pnl:OnRemove()
end
if pnl.children and #pnl.children > 0 then
for _,child in pairs(pnl.children) do
removeChildren(child)
end
end
end
removeChildren(frame)
GPhone.EnableSelfie(false)
GPhone.Panels[name] = nil
if GPhone.CurrentApp == name then
GPhone.CurrentApp = nil
GPhone.CurrentFrame = nil
end
return true
end
function GPhone.FocusApp(name)
local frame = GPhone.Panels[name]
if !frame then return false end
local app = GPhone.GetApp(name)
if frame.Landscape != GPhone.Landscape then
local new = GPhone.RunApp(name, true)
if !new then return false end
if app.Rotate then
app.Rotate(GPhone.Panels[name], new)
end
GPhone.StopApp(name)
GPhone.Panels[name] = new
GPhone.FocusApp(name)
return new
end
GPhone.CurrentApp = name
GPhone.CurrentFrame = frame
if app and app.Focus then
if type(app.Focus) == "string" then
local str = RunString("appfoc = "..app.Focus, name, false)
if !str and appfoc then
GPhone.DebugFunction(appfoc, frame)
else
GPhone.Debug("[ERROR] in app '"..(app.Name or name).."': "..str, false, true)
end
else
GPhone.DebugFunction(app.Focus, frame)
end
end
return frame
end
function GPhone.FocusHome()
local name = GPhone.CurrentApp
local frame = GPhone.CurrentFrame
if name and frame then
local app = GPhone.GetApp(name)
if app and app.UnFocus then
if type(app.UnFocus) == "string" then
local str = RunString("appunfoc = "..app.UnFocus, name, false)
if !str and appunfoc then
GPhone.DebugFunction(appunfoc, frame)
else
GPhone.Debug("[ERROR] in app '"..(app.Name or name).."': "..str, false, true)
end
else
GPhone.DebugFunction(app.UnFocus, frame)
end
end
end
GPhone.EnableSelfie(false)
local launcher = GPhone.GetData("launcher", "launcher")
GPhone.RunApp(launcher)
end
function GPhone.InstallApp(name)
local apps = GPhone.GetData("apps", {})
if table.HasValue(apps, name) then return end
if !GPhone.GetApp(name) then return end
table.insert(apps, name)
GPhone.SetData("apps", apps)
local launcher = GPhone.GetData("launcher", "launcher")
if GPhone.CurrentApp == launcher then
GPhone.FocusHome()
end
end
function GPhone.UninstallApp(name)
if table.HasValue(GPDefaultApps, name) then return end
local apps = GPhone.GetData("apps", {})
GPhone.ClearAllAppData(name)
if file.Exists("gphone/apps/"..name..".txt", "DATA") then
GPhone.Apps[name] = nil
file.Delete("gphone/apps/"..name..".txt")
end
if table.HasValue(apps, name) then
GPhone.StopApp(name)
for k,appid in pairs(apps) do
if name == appid then apps[k] = nil end
end
GPhone.SetData("apps", apps)
end
local launcher = GPhone.GetData("launcher", "launcher")
if GPhone.CurrentApp == launcher then
GPhone.FocusHome()
end
end
function GPhone.UpdateApp(url, success, failure)
if !url then return false end
local name = GPhone.SerializeAppName(url)
if !name then return false end
if !table.HasValue(GPhone.Data.apps, name) then return false end
if !file.Exists("gphone/apps/"..name..".txt", "DATA") then return false end
local r = file.Read("gphone/apps/"..name..".txt", "DATA")
http.Fetch(url, function(body, size, headers, code)
if success and (body.."\nAPP.URL = \""..url.."\"") != r then
success(body)
elseif failure then
failure("App is up to date")
end
end,
function(err)
if failure then
failure(err)
end
end)
return true
end
function GPhone.DownloadApp(url)
if !url then return false end
local cv = GetConVar("gphone_csapp")
if !cv or !cv:GetBool() then return false end
local name = GPhone.SerializeAppName(url)
http.Fetch(url, function(body, size, headers, code)
local content = body.."\nAPP.URL = \""..url.."\""
file.Write("gphone/apps/"..name..".txt", content)
APP = {}
RunString(content, name)
GPhone.AddApp(name, APP)
local css = GPhone.GetData("icon_css", "background-color: #FFF; border-radius: 32px 32px 32px 32px")
GPhone.DownloadImage(APP.Icon, 128, css)
APP = nil
GPhone.InstallApp(name)
end,
function(err)
print(err)
end)
return name
end
function GPhone.SerializeAppName(url)
return string.gsub(url, '[\\/:%*%?"<>|%.]', "-")
end
function GPhone.Vibrate()
local ply = LocalPlayer()
if !ply:Alive() then return false end
local wep = ply:GetActiveWeapon()
if IsValid(wep) and wep:GetClass() == "gmod_gphone" then
wep.b_vibrate = CurTime() + 1
end
if ply:HasWeapon("gmod_gphone") then
wep:EmitSound("sound/gphone/vibrate.wav")
return true
end
return false
end
function GPhone.Rotate(landscape)
if GPhone.Landscape == landscape then return false end
local wep = LocalPlayer():GetWeapon("gmod_gphone")
if IsValid(wep) then
wep.b_quickopen = nil
wep.b_quickhold = nil
end
GPhone.Landscape = landscape
local oldw = GPhone.Width
local oldh = GPhone.Height
if (landscape and oldh > oldw) or (!landscape and oldh < oldw) then
GPhone.Width = oldh
GPhone.Height = oldw
end
local name = GPhone.CurrentApp
local app = GPhone.GetApp(name)
if name and app then
local new = GPhone.RunApp(name, true)
if !new then return false end
if app.Rotate then
app.Rotate(GPhone.Panels[name], new)
end
GPhone.StopApp(name)
if name != GPhone.GetData("launcher", "launcher") then
GPhone.Panels[name] = new
end
GPhone.FocusApp(name)
elseif GPhone.CurrentFrame then
GPhone.FocusHome()
end
end
function GPhone.RenderCamera(fov, front, pre, post)
local ply = LocalPlayer()
local wep = ply:GetActiveWeapon()
if IsValid(wep) and wep:GetClass() == "gmod_gphone" then
local mtx = GPhone.CamMT:GetMatrix("$basetexturetransform")
if GPhone.Landscape then
mtx:SetAngles(Angle(0, -90, 0))
GPhone.CamMT:SetTexture("$basetexture", GPhone.CamLSRT)
render.PushRenderTarget(GPhone.CamLSRT)
else
mtx:SetAngles(Angle(0, 0, 0))
GPhone.CamMT:SetTexture("$basetexture", GPhone.CamRT)
render.PushRenderTarget(GPhone.CamRT)
end
GPhone.CamMT:SetMatrix("$basetexturetransform", mtx)
render.Clear(0, 0, 0, 255)
render.ClearDepth()
local ang = ply:EyeAngles()
local pos = ply:EyePos() + ang:Forward()*8
if front then
local attach_id = ply:LookupAttachment("anim_attachment_RH")
local attach = ply:GetAttachment(attach_id)
if attach then
pos = attach.Pos + ang:Up()*6 - ang:Right()*3
ang:RotateAroundAxis(ang:Up(), 180)
end
else
local vm = LocalPlayer():GetViewModel()
if IsValid(vm) then
ang = vm:GetAngles()
end
end
local oldLegs = nil
local oldDraw = nil
if front then
local oldlegs = ply.ShouldDisableLegs
ply.ShouldDisableLegs = true
if EnhancedCamera then
oldDraw = EnhancedCamera.ShouldDraw
EnhancedCamera.ShouldDraw = function() return false end
end
end
GPSelfieRendering = front
if pre then
GPhone.DebugFunction(pre, pos, ang, fov)
end
render.RenderView({
x = 0,
y = 0,
w = GPhone.Width,
h = GPhone.Height,
origin = pos,
angles = ang,
fov = fov or 90,
dopostprocess = true,
drawhud = false,
drawmonitors = true,
drawviewmodel = false
})
if post then
GPhone.DebugFunction(post, pos, ang, fov)
end
GPSelfieRendering = false
if front then
ply.ShouldDisableLegs = oldlegs
if EnhancedCamera and oldDraw then
EnhancedCamera.ShouldDraw = oldDraw
end
end
render.PopRenderTarget()
return GPhone.CamMT
end
return false
end
--[[function GPhone.SendSMS(number, text)
net.Start("GPhone_SMS_Send")
net.WriteString(number)
net.WriteString(text)
net.SendToServer()
return true
end]]
function GPhone.RequestVoiceChat(ply)
if !IsValid(ply) or !ply:IsPlayer() then return false end
if IsValid(g_VoicePanelList) then
g_VoicePanelList:SetVisible(false)
end
GPhone.VoiceChatter = ply
net.Start("GPhone_VoiceCall_Request")
net.WriteEntity(ply)
net.SendToServer()
LocalPlayer():ConCommand("+voicerecord")
return true
end
function GPhone.GetIncomingVoiceChats()
return GPhone.AwaitingCalls or {}
end
function GPhone.AnswerVoiceChat(index, accept)
local chats = GPhone.GetIncomingVoiceChats()
local ply = chats[index]
if !ply or !IsValid(ply) or !ply:IsPlayer() then return false end
if accept then
GPhone.VoiceChatter = ply
if IsValid(g_VoicePanelList) then
g_VoicePanelList:SetVisible(false)
end
net.Start("GPhone_VoiceCall_Answer")
net.WriteEntity(ply)
net.WriteBool(true)
net.SendToServer()
LocalPlayer():ConCommand("+voicerecord")
else
net.Start("GPhone_VoiceCall_Answer")
net.WriteEntity(ply)
net.WriteBool(false)
net.SendToServer()
end
table.remove(chats, index)
return true
end
function GPhone.StopVoiceChat()
GPhone.VoiceChatter = false
if IsValid(g_VoicePanelList) then
g_VoicePanelList:SetVisible(true)
end
net.Start("GPhone_VoiceCall_Stop")
net.SendToServer()
LocalPlayer():ConCommand("-voicerecord")
end
function GPhone.InputText(enter, change, cancel, starttext, keypress)
if IsValid(GPhone.InputField) then return false end
local frame = vgui.Create("DFrame")
frame:SetSize(ScrW()/2, ScrH()/2)
frame:SetPos(ScrW()/4, ScrH()/4)
frame:SetTitle("")
frame:SetVisible(true)
frame:SetDraggable(false)
frame:ShowCloseButton(false)
frame:MakePopup()
frame:SetMouseInputEnabled(false)
function frame:Paint()
return false
end
GPhone.InputField = vgui.Create("DTextEntry", frame)
GPhone.InputField:SetText(starttext or "")
GPhone.InputField:SetSize(200, 20)
GPhone.InputField:SetPos(0, 0)
GPhone.InputField:RequestFocus()
GPhone.InputField:SetCaretPos(string.len(starttext or ""))
GPhone.InputField:SetDrawLanguageID(false)
function GPhone.InputField:Paint()
return false
end
function GPhone.InputField:OnEnter()
self.m_entered = true
self:GetParent():Close()
if enter then
GPhone.DebugFunction(enter, self:GetValue())
end
end
if keypress then
function GPhone.InputField:OnKeyCodeTyped(key)
if key == 64 then
self:OnEnter()
end
keypress(key, true)
end
function GPhone.InputField:OnKeyCodeReleased(key)
keypress(key, false)
end
end
function GPhone.InputField:OnChange()
if change then
GPhone.DebugFunction(change, self:GetValue())
end
end
function GPhone.InputField:OnLoseFocus()
self:GetParent():Close()
if self.m_entered then return end
if cancel then
GPhone.DebugFunction(cancel)
end
end
end
function GPhone.CloseInput()
if !IsValid(GPhone.InputField) or !IsValid(GPhone.InputField:GetParent()) then return false end
GPhone.InputField:GetParent():Close()
return true
end
function GPhone.GetInputText()
if !IsValid(GPhone.InputField) then return false end
return GPhone.InputField:GetValue()
end
function GPhone.SetCaretPos(pos)
if !IsValid(GPhone.InputField) then return false end
GPhone.InputField:SetCaretPos(pos)
return true
end
function GPhone.GetCaretPos()
if !IsValid(GPhone.InputField) then return 0 end
return GPhone.InputField:GetCaretPos()
end
function GPhone.GetSelectedRange()
if !IsValid(GPhone.InputField) then return 0,0 end
return GPhone.InputField:GetSelectedTextRange()
end
function GPhone.ConfirmDialog(title, text, accept)
local frame = GPhone.CreateRootPanel()
GPhone.CurrentFrame = frame
frame.text = GPhone.WordWrap(text, GPhone.Width, "GPSmall")
function frame:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h, Color(240, 240, 240) )
draw.SimpleText(title, "GPTitle", w / 2, 64, Color(0, 0, 0), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
for k,v in pairs(frame.text) do
draw.SimpleText(v, "GPSmall", w / 2, 128 + k * 28 * GPhone.Resolution, Color(0, 0, 0), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
end
local confirm = GPnl.AddPanel( frame )
confirm:SetPos( 0, frame:GetHeight() - 128 * GPhone.Resolution )
confirm:SetSize( GPhone.Width / 2, 128 * GPhone.Resolution )
function confirm:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, 4, Color(160, 160, 160) )
draw.RoundedBox( 0, w - 2, 0, 2, h, Color(160, 160, 160) )
draw.SimpleText("Confirm", "GPMedium", w / 2, h / 2, Color(50, 150, 250), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
function confirm:OnClick()
accept()
GPhone.CurrentFrame = GPhone.CurrentApp and GPhone.Panels[GPhone.CurrentApp] or nil
end
local cancel = GPnl.AddPanel( frame )
cancel:SetPos( GPhone.Width / 2, frame:GetHeight() - 128 * GPhone.Resolution )
cancel:SetSize( GPhone.Width / 2, 128 * GPhone.Resolution )
function cancel:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, 4, Color(160, 160, 160) )
draw.RoundedBox( 0, 0, 0, 2, h, Color(160, 160, 160) )
draw.SimpleText("Cancel", "GPMedium", w / 2, h / 2, Color(50, 150, 250), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
function cancel:OnClick()
GPhone.CurrentFrame = GPhone.Panels[GPhone.CurrentApp]
end
end
function GPhone.CreateHTMLPanel(w, h, url, vol)
local html = vgui.Create("DHTML")
html.URL = url or "about:blank"
html.Title = "about:blank"
html:SetPos(0, 0)
html:SetSize(w or GPhone.Width, h or GPhone.Height)
html.b_keepvolume = vol
if url then
html:OpenURL(url)
end
function html:OnChangeTitle(title)
html.Title = title
end
GPhone.UpdateHTMLControl(html)
html:SetKeyBoardInputEnabled(false)
html:SetPaintedManually(false)
html:SetVisible(false)
timer.Simple(0, function()
html:SetPaintedManually(true)
end)
table.insert(GPhone.HTML, html)
return html
end
function GPhone.UpdateHTMLControl(html)
if !IsValid(html) then return end
function html:ConsoleMessage(str)
if string.find(str or "", "Uncaught ReferenceError: gmod is not defined") then
print("[ERROR] '"..tostring(html).."': "..str)
GPhone.UpdateHTMLControl(html)
elseif str then
print("[GPhone HTML] "..str)
end
end
html:AddFunction("gmod", "getURL", function( str)
if str != "about:blank" then
html.URL = str
end
end)
html:AddFunction("gmod", "inputField", function( tag, id, oldval)
if tag and id then
local function onChange(val)
if IsValid(html) and tag and id then
local js = [[var x = document.getElementsByTagName("]]..tag..[[")[]]..id..[[].value = "]]..val..[[";]]
html:RunJavascript(js)
end
end
local function onEnter(val)
if IsValid(html) then
if string.StartWith(html.URL, "https://www.google.com") then -- Why are javascript events so confusing to hack together?
html:OpenURL("https://www.google.com/search?q="..string.gsub(val, " ", "+"))
elseif tag and id then
local js = [[var el = document.getElementsByTagName("]]..tag..[[")[]]..id..[[];
var ev = new Event("keydown"); // Fuck Awesomium for being this old
ev.key = "Enter";
ev.keyCode = 13;
ev.charCode = ev.keyCode;
ev.which = ev.keyCode;
ev.altKey = false;
ev.ctrlKey = false;
ev.shiftKey = false;
ev.metaKey = false;
ev.bubbles = true;
el.dispatchEvent(ev);
]]
html:RunJavascript(js)
end
end
end
local function keyPress(key, pressed)
local chr = input.GetKeyName(key)
local asc = string.byte(chr)
if string.len(chr) > 1 then
if chr == "BACKSPACE" then chr = "Backspace" asc = 8 end
if chr == "LEFTARROW" then chr = "ArrowLeft" asc = 37 end
if chr == "UPARROW" then chr = "ArrowUp" asc = 38 end
if chr == "RIGHTARROW" then chr = "ArrowRight" asc = 39 end
if chr == "DOWNARROW" then chr = "ArrowDown" asc = 40 end
end
local js = [[var el = document.getElementsByTagName("]]..tag..[[")[]]..id..[[];
var ev = new Event("]]..(pressed and "keydown" or "keyup")..[["); // Fuck Awesomium for being this old
ev.key = "]]..chr..[[";
ev.keyCode = ]]..asc..[[;
ev.charCode = ev.keyCode;
ev.which = ev.keyCode;
ev.altKey = false;
ev.ctrlKey = false;
ev.shiftKey = false;
ev.metaKey = false;
ev.bubbles = true;
el.dispatchEvent(ev);
]]
html:RunJavascript(js)
end
GPhone.InputText(onEnter, onChange, nil, oldval, keyPress)
end
end)
html:AddFunction("gmod", "print", function( ...)
local str = string.Implode(" ", { ... })
print("[GPhone][HTML] "..str)
end)
--[[html:AddFunction("gmod", "run", function( ...) -- I don't even need this but whatever
local code = string.Implode(" ", { ... })
if code != "" then
this = html
local str = RunString(code, "gmod.run", false)
if str then
GPhone.Debug("[ERROR] '"..tostring(html).."': "..str, false, true)
end
this = nil
end
end)]]
html:AddFunction("gmod", "isAwesomium", function( str)
local bool = tobool(str)
GPhone.IsAwesomium = bool
if bool and GetConVar("gphone_chromium"):GetBool() then
html:SetHTML([[<!doctype>
<html>
<head>
<title>Fuck Awesomium</title>
<style>
p {
color: #acb2b8;
font-size: 40px;
}
</style>
</head>
<body style="background-color: #1b2838;">
<p>I would <b>HIGHLY</b> suggest switching to the Chromium branch due to the Awesomium browser being very old and unsupported on many sites.</p>
<img src="https://raw.githubusercontent.com/KredeGC/GPhone/master/tutorial/chromium.png" width="100%" />
<p>This can be done by right-clicking Garry's Mod in your Steam Library and selecting properties.
<br>In the properties-window, navigate to the 'BETAS' tab and select 'x86-64 - Chromium + 64-bit binaries' from the dropdown.</p>
<p>If you <b>DON'T</b> want to switch to Chromium, click <a style="color: #ffffff; text-decoration: none;" href="javascript:gmod.run('this:GoBack() this.Title=\'Google\' RunConsoleCommand(\'gphone_chromium\', 0)');">HERE</a> to turn off this notification and continue.</p>
</body>
</html>]])
end
end)
html:AddFunction("gmod", "redirect", function(url)
GPhone.ConfirmDialog("Redirect?", "You are about to redirect to: "..url, function()
html:OpenURL(url)
end)
end)
html:AddFunction("window", "open", function(...)
-- Remove popups
end)
end
function GPhone.CloseHTMLPanel(html)
if table.HasValue(GPhone.HTML, html) then
table.RemoveByValue(GPhone.HTML, html)
end
if IsValid(html) then
html:Remove()
end
end
local genicon = Material("vgui/spawnmenu/generating")
function GPhone.GetHTMLMaterial(html)
if IsValid(html) then
html:UpdateHTMLTexture()
if html.Mat then
return html.Mat
elseif html:GetHTMLMaterial() then
local mat = html:GetHTMLMaterial() -- Get the html material
local scale_x,scale_y = html:GetWide() / mat:Width(),html:GetTall() / mat:Height() -- Setup the material-data with the proper scaling
local matdata = {
["$basetexture"] = mat:GetName(),
["$basetexturetransform"] = "center 0 0 scale "..scale_x.." "..scale_y.." rotate 0 translate 0 0",
["$vertexcolor"] = 1,
["$vertexalpha"] = 1,
["$nocull"] = 1,
["$model"] = 1
}
local id = string.gsub(mat:GetName(), "__vgui_texture_", "")
html.Mat = CreateMaterial("GPhone_HTMLMaterial_"..id, "UnlitGeneric", matdata)
return html.Mat
end
end
return genicon
end
function GPhone.GetHTMLPos(frame, html, mx, my)
if !frame or !IsValid(html) then return mx,my end
local fx,fy = parentPos(frame)
local fw,fh = frame.w,frame.h
local mx,my = ((mx - fx) / fw) * html:GetWide(),((my - fy) / fh) * html:GetTall()
return mx,my
end
function GPhone.PerformHTMLClick(html, x, y)
if !IsValid(html) then return false end
html:RunJavascript([[
var elem = document.elementFromPoint(]]..x..[[, ]]..y..[[);
elem.focus();
function pressParents(el) {
if (el.tagName == "INPUT" && (el.type == "text" || el.type == "password")) {
var x = document.getElementsByTagName(el.tagName);
for (i = 0; i < x.length; i++) {
if (x[i] == el) {
gmod.inputField(el.tagName, i, el.value);
break;
}
}
} else if (el.tagName == "A" && el.target == "_blank") {
if (el.href) {
if (el.href.search(window.location.protocol) == 0 || el.href.search(window.location.protocol) == -1) {
gmod.redirect(el.href);
} else if (el.href.search("#")) {
gmod.redirect(window.location.href + el.href);
} else {
gmod.redirect(window.location.hostname + "/" + el.href);
}
}
} else if (el.click || el.onclick || el.onClick) {
var event = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
el.dispatchEvent(event);
} else if (el.tagName == "A") {
if (el.href) {
if (el.href.search("javascript:") > -1) {
eval(el.href.substr(11));
} else if (el.href.search(window.location.protocol) == 0 || el.href.search(window.location.protocol) == -1) {
window.location.href = el.href;
} else if (el.href.search("#")) {
window.location.href = window.location.href + el.href;
} else {
window.location.href = window.location.hostname + "/" + el.href;
}
}
} else if (el.parentElement) {
pressParents(el.parentElement);
}
}
pressParents(elem)
]])
return true
end
function GPhone.StartMusic(id)
if !id and !GPhone.MusicURL then return false end
GPhone.StopMusic()
GPhone.MusicURL = id or GPhone.MusicURL
local vol = GetConVar("gphone_volume")
local airpods = GetConVar("gphone_airpods")
if string.StartWith(id, "http://") or string.StartWith(id, "https://") then
if string.find(id, "youtube.com") then
local frame = GPhone.RunApp("furfox")
if frame then
frame:OpenURL(id)
end
GPhone.CloseInput()
else
sound.PlayURL(GPhone.MusicURL, "noplay noblock", function(channel)
if IsValid(channel) then
channel:SetVolume(vol and vol:GetFloat() or 1)
channel:Play()
if GPhone.MusicStream.Channel then
GPhone.MusicStream.Channel:Stop()
end
if airpods:GetBool() then
net.Start("GPhone_Music")
net.WriteBool(true)
net.SendToServer()
end
GPhone.MusicStream.URL = GPhone.MusicURL
GPhone.MusicStream.Playing = true
GPhone.MusicStream.Channel = channel
GPhone.MusicStream.Length = channel:GetLength()
end
end)
end
else
if !file.Exists(GPhone.MusicURL, "GAME") then
GPhone.MusicURL = "sound/"..GPhone.MusicURL
end
if !file.Exists(GPhone.MusicURL, "GAME") then return false end
sound.PlayFile(GPhone.MusicURL, "noplay noblock", function(channel)
if IsValid(channel) then
channel:SetVolume(vol and vol:GetFloat() or 1)
channel:Play()
if GPhone.MusicStream.Channel then
GPhone.MusicStream.Channel:Stop()
end
if airpods:GetBool() then
net.Start("GPhone_Music")
net.WriteBool(true)
net.SendToServer()
end
GPhone.MusicStream.URL = GPhone.MusicURL
GPhone.MusicStream.Playing = true
GPhone.MusicStream.Channel = channel
GPhone.MusicStream.Length = channel:GetLength()
end
end)
end
return true
end
function GPhone.StopMusic()
net.Start("GPhone_Music")
net.WriteBool(false)
net.SendToServer()
if GPhone.MusicStream.Channel then
GPhone.MusicStream.Channel:Stop()
GPhone.MusicStream = {}
end
end
function GPhone.ToggleMusic(play)
if GPhone.MusicStream.Channel then
if play == nil then
if GPhone.MusicStream.Playing then
GPhone.MusicStream.Playing = false
GPhone.MusicStream.Channel:Pause()
else
GPhone.MusicStream.Playing = true
GPhone.MusicStream.Channel:Play()
end
elseif GPhone.MusicStream.Playing and !play then
GPhone.MusicStream.Playing = false
GPhone.MusicStream.Channel:Pause()
elseif !GPhone.MusicStream.Playing and play then
GPhone.MusicStream.Playing = true
GPhone.MusicStream.Channel:Play()
end
end
end
function GPhone.GetMusic()
if GPhone.MusicStream.Channel then
return GPhone.MusicStream
end
return false
end
function GPhone.ChangeVolume(dec)
local dec = math.Clamp(math.Round(dec, 2), 0, 1)
RunConsoleCommand("gphone_volume", dec)
if GPhone.MusicStream.Channel then
GPhone.MusicStream.Channel:SetVolume(dec)
end
end
function GPhone.DownloadImage(url, size, style)
if !url then return false end
if GPhone.ImageCache[url] then return false end
local data = {URL = url, Size = size or 128, Style = style}
if string.StartWith(url, "http://") or string.StartWith(url, "https://") then -- Online files
http.Fetch(url, function(body, size, headers, code)
table.insert(GPhone.ImageHistory, data)
if code == 200 then
table.insert(GPhone.ImageQueue, data)
else
GPhone.ImageCache[url] = genicon
end
end,
function(err)
print("[GPhone] "..err)
end)
else
table.insert(GPhone.ImageHistory, data)
table.insert(GPhone.ImageQueue, data)
end
return true
end
function GPhone.GetImage(url)
if GPhone.ImageCache[url] and !GPhone.ImageCache[url]:IsError() then return GPhone.ImageCache[url] end
return GPLoadingMT or genicon
end<file_sep>--APP.Name = "Job Index"
APP.Author = "Krede"
APP.Icon = "asset://garrysmod/materials/gphone/apps/furfox.png"
function APP.Run( objects, screen )
function frame:Paint( x, y, w, h )
draw.RoundedBox( 0, 0, 0, w, h, Color( 50, 50, 50, 255 ) )
end
frame.Scroll = GPnl.AddPanel( frame, "scroll" )
frame.Scroll:SetPos( 0, 64 * ratio )
frame.Scroll:SetSize( w, h - (64 + 140) * ratio )
for _, data in pairs( RPExtraTeams ) do
if not data.team then
continue
end
local requiresVote = data.vote or data.RequiresVote and data.RequiresVote(LocalPlayer(), data.team)
local bgPanel = objects.Layout:Add("DPanel")
bgPanel:SetSize(screen:GetWide(), 120)
bgPanel.Paint = function( self, w, h )
draw.RoundedBox(0, 0, 0, w, h, gPhone.colors.whiteBG)
end
local jobName = vgui.Create( "DLabel", bgPanel )
jobName:SetText( data.name )
jobName:SetTextColor(Color(0,0,0))
jobName:SetFont("gPhone_20")
jobName:SizeToContents()
jobName:SetPos( 10 + playerModel:GetWide() + 10, 15 )
local function getMaxOfTeam(job)
if not job.max or job.max == 0 then return "∞" end
if job.max % 1 == 0 then return tostring(job.max) end
return tostring(math.floor(job.max * #player.GetAll()))
end
local space = vgui.Create( "DLabel", bgPanel )
space:SetText( team.NumPlayers(data.team).."/"..getMaxOfTeam(data) )
space:SetTextColor(Color(0,0,0))
space:SetFont("gPhone_16")
space:SizeToContents()
local x, y = jobName:GetPos()
space:SetPos( x + 3, y + space:GetTall() + 5 )
space.Think = function( self )
self:SetText( team.NumPlayers(data.team).."/"..getMaxOfTeam(data) )
end
local salary = vgui.Create( "DLabel", bgPanel )
salary:SetText( "$"..data.salary or "" )
salary:SetTextColor(Color(0,0,0))
salary:SetFont("gPhone_16")
salary:SizeToContents()
local x, y = space:GetPos()
salary:SetPos( x, y + space:GetTall() + 3 )
local becomeButton = vgui.Create("DButton", bgPanel )
becomeButton:SetSize( bgPanel:GetWide()/2, 30 )
becomeButton:SetPos( 10, bgPanel:GetTall() - becomeButton:GetTall() - 10 )
becomeButton:SetFont("gPhone_16")
becomeButton:SetTextColor( color_white )
becomeButton:SetText( requiresVote and DarkRP.getPhrase("create_vote_for_job") or DarkRP.getPhrase("become_job"))
becomeButton.Paint = function( self, w, h )
draw.RoundedBox(0, 0, 0, w, h, Color(140, 0, 0, 250) )
end
if requiresVote then
becomeButton.DoClick = fn.Compose{function()end, fn.Partial(RunConsoleCommand, "darkrp", "vote" .. data.command)}
else
becomeButton.DoClick = function()
LocalPlayer():ConCommand( "darkrp ".. data.command )
end
end
end
end
|
74c83ecabf048171e8c72d3eff0604494cc4353e
|
[
"Markdown",
"Lua"
] | 23
|
Lua
|
KredeGC/GPhone
|
784f02fadc8f1525862f65ee50aa823e8034fc6a
|
fd363a36b0d39ff0a35c0e94af0b996e84183d1e
|
refs/heads/master
|
<file_sep>/**
* Các function mặc định và các biến chung
*
* userOnline
* copy_user_name
* my_getcookie
* my_setcookie
*/
var user_setting = {
/*
buzz: 60, // Giới hạn thời gian giữa 2 lần buzz, nếu đặt 0 sẽ không sử dụng buzz
autoLogin: true, // Tự động đăng nhập
autoRefresh: true, // Tự động cập nhật
hideTabs: false, // Ẩn cột trái
noClear: true, // Không xóa tin nhắn khi clear chatbox, tự động lưu trữ
reverse: false // Đảo ngược thứ tự tin nhắn (mới nhất lên trên)
*/
};
var zzChat = {
uId: "", // User id (của mình)
uName: "", // User name (của mình)
/**
* Dữ liệu các kênh chat, thông số từng kênh
*
* time: Thời điểm tạo phòng
* uid: User id của người tạo
* name: Tên phòng
* users: Danh sách người trong phòng (bao gồm mình)
* other: Danh sách thành viên khác trong phòng (không bao gồm mình)
* mLength: Số tin nhắn cũ
* mLastContent: Nội dung tin nhắn cuối cùng
* mLastTime: Thời điểm tin nhắn cuối cùng
* close: Đánh dấu phòng đã đóng hay chưa
*/
data: {},
active: "publish", // Id của tab đang hiển thị
// Các đối tượng thường dùng
o: {
chat: $("#chatbox-forumvi"), // Khối bao quanh toàn chatbox
cTit: $("#chatbox-title > h2"), // Tiêu đề chatbox
wTit: $("title"), // Tiêu đề của trang
wrap: $("#chatbox-wrap"), // Khối bao quanh tin nhắn
mList: $("#chatbox-members"), // Danh sách thành viên trên chatbox
tabs: $("#chatbox-list"), // Danh sách tab chatbox
messenge : $("#chatbox-messenger-input"), // input nhập liệu
form : $("#chatbox-form"), // form gửi tin
},
firstTime: true, // Lần truy cập đầu tiên
refreshFunction: function(){}, // Hàm cập nhật tin nhắn
oldMessage: "" // Nội dung tin nhắn vừa nhập vào để phục hồi khi lỗi
};
var settings = $.extend({
buzz: 60, // Giới hạn thời gian giữa 2 lần buzz, nếu đặt 0 sẽ không sử dụng buzz
autoLogin: true, // Tự động đăng nhập
autoRefresh: true, // Tự động cập nhật
hideTabs: false, // Ẩn cột trái
noClear: true, // Không xóa tin nhắn khi clear chatbox, tự động lưu trữ
reverse: false // Đảo ngược thứ tự tin nhắn (mới nhất lên trên)
}, user_setting);
/**
* Lấy Link của người dùng trong danh sách bằng nickname
*
* @param {String} nickname của người cần lấy
* return {Object}
*/
var userOnline = function (user_name) {
return $("#chatbox-members").find('a[onclick="return copy_user_name(\'' + user_name + '\');"]');
};
/**
* Copy nickname vào khung soạn thảo
*
* @param {String} nickname người dùng
*/
function copy_user_name(user_name) {
$messenger[0].value += user_name;
$messenger.focus();
return false;
}
/**
* Lấy cookie
*
* @param {String} Tên cookie
*/
function my_getcookie(name) {
cname = name + '=';
cpos = document.cookie.indexOf(cname);
if (cpos != -1) {
cstart = cpos + cname.length;
cend = document.cookie.indexOf(";", cstart);
if (cend == -1) {
cend = document.cookie.length;
}
return unescape(document.cookie.substring(cstart, cend));
}
return null;
}
/**
* Đặt cookie
*
* @param1 {String} tên cookie
* @param2 {String} Giá tri cookie
* @param3 {Boolean} Thời gian lưu trữ theo session hoặc vĩnh viễn
* @param4 {URL} Đường dẫn trang lưu trữ
*/
function my_setcookie(name, value, sticky, path) {
expires = "";
domain = "";
if (sticky) {
expires = "; expires=Wed, 1 Jan 2020 00:00:00 GMT";
}
if (!path) {
path = "/";
}
document.cookie = name + "=" + value + "; path=" + path + expires + domain + ';';
}
|
679425d0b5f79c9ad189e41c3a058caba2d7afe1
|
[
"JavaScript"
] | 1
|
JavaScript
|
kDom/chatbox
|
8847dd01ea416d0300750ff67506893c1d9c306b
|
030da0cdad2f059287c557c2a8fd394364559c68
|
refs/heads/master
|
<file_sep>package com.legalzoom.bank.cards;
import java.time.YearMonth;
import com.fasterxml.jackson.annotation.JsonFormat;
public class Card {
String bankName;
String cardNumber;
@JsonFormat(pattern="MMM-yyyy")
YearMonth expiryDate;
public Card(String bankName, String cardNumber, YearMonth expiryDate) {
super();
this.bankName = bankName;
this.cardNumber = cardNumber;
this.expiryDate = expiryDate;
}
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
public YearMonth getExpiryDate() {
return expiryDate;
}
public void setExpiryDate(YearMonth expiryDate) {
this.expiryDate = expiryDate;
}
@Override
public String toString() {
return "Card [bankName=" + bankName + ", cardNumber=" + cardNumber + ", expiryDate=" + expiryDate + "]";
}
}
<file_sep>package com.legalzoom.bank.cards;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
public class CardUtilsTest {
CardUtils cardUtils = new CardUtils();
@Test
public void canCreateCardFromCsvLine() {
Card card = cardUtils.readCsvLine("bank1:1234-4567-8910-1233:Nov-2017");
assertNotNull(card);
assertEquals("bank1",card.bankName);
assertEquals("1234-4567-8910-1233",card.cardNumber);
assertEquals(0,YearMonth.of(2017, 11).compareTo(card.expiryDate));
}
@Test
public void canHideCardNumber() {
Card card = new Card("bank1", "1234-4567-8910-1233",YearMonth.of(2017, 11) );
card = cardUtils.hideCardNumber(card);
assertEquals("1234-XXXX-XXXX-XXXX", card.cardNumber);
}
@Test
public void canReadCvsStreamWith1Card() throws IOException {
String input = "bank1:1234-4567-8910-1233:Nov-2017";
InputStream is = new ByteArrayInputStream( input.getBytes() );
List<Card> cards = new ArrayList<>();
cardUtils.updateFromCvsFile(cards,is);
assertEquals(1, cards.size());
assertEquals("bank1",cards.get(0).bankName);
}
@Test
public void canReadCvsStreamWith2Cards() throws IOException {
String input = "bank1:1234-4567-8910-1233:Nov-2017\r\nbank2:1234-4567-8910-1233:Nov-2017";
InputStream is = new ByteArrayInputStream( input.getBytes() );
List<Card> cards = new ArrayList<>();
cardUtils.updateFromCvsFile(cards,is);
assertEquals(2, cards.size());
assertEquals("bank1",cards.get(0).bankName);
assertEquals("bank2",cards.get(1).bankName);
}
@Test
public void canSortbyExpiryDateDescendingOrder() {
List<Card> cards = new ArrayList<>();
cards.add(new Card("bank1", "1234-4567-8910-1233",YearMonth.of(2017, 11)));
cards.add(new Card("bank2", "1234-4567-8910-1233",YearMonth.of(2020, 10)));
cardUtils.sortByExpiryDate(cards);
assertEquals("bank2", cards.get(0).bankName);
}
}
<file_sep>package com.legalzoom.bank.cards;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import org.springframework.boot.jackson.JsonComponent;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
@JsonComponent
public class CardDateDeserializer extends JsonDeserializer<YearMonth> {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM-yyyy");
@Override
public YearMonth deserialize(JsonParser jsonParser, DeserializationContext
deserializationContext) throws IOException, JsonProcessingException {
String date = jsonParser.getText();
try {
return YearMonth.parse(date,formatter);
} catch (DateTimeParseException e) {
throw new RuntimeException(e);
}
}
}
<file_sep>package com.legalzoom.bank.cards;
import java.io.IOException;
import java.time.Month;
import java.time.YearMonth;
import java.util.List;
import java.util.Vector;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@CrossOrigin(origins = "http://localhost:3000")
@RestController
@RequestMapping("/cards")
public class CardsController {
Logger logger = Logger.getLogger(CardsController.class.getName());
@Autowired CardUtils cardUtils;
List<Card> cards;
@PostConstruct
public void init() {
cards = new Vector<Card>(); //thread safe
cards.add(new Card("HSBC Canada", "5601-XXXX-XXXX-XXXX", YearMonth.of(2019, Month.DECEMBER)));
cards.add(new Card("Royal Bank of Canada", "4519-XXXX-XXXX-XXXX", YearMonth.of(2020, Month.DECEMBER)));
cards.add(new Card("American Express", "3786-XXXX-XXXX-XXXX", YearMonth.of(2018, Month.DECEMBER)));
}
@GetMapping
@ResponseBody
public List<Card> getCards() {
logger.info("getCards invoked." +cards.size() +" cards returned");
cardUtils.sortByExpiryDate(cards);
return cards;
}
@PostMapping("/create")
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public void create(@RequestBody Card card) {
logger.info("create card invoked "+card);
cards.add(cardUtils.hideCardNumber(card));
}
@PostMapping("/upload")
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public void upload(@RequestBody @RequestParam("file") MultipartFile file) throws IOException {
logger.info("upload invoked "+file.getOriginalFilename());
cardUtils.updateFromCvsFile(cards,file.getInputStream());
}
@PostMapping("/clear")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public void clear() {
logger.info("clear cards invoked");
cards.clear();
}
}
<file_sep>import React, { Component } from 'react';
import axios from 'axios';
class UploadCsvFile extends Component {
state = { selectedFile:null }
onChangeHandler=event=>{
console.log(event.target.files[0].name)
this.setState({
selectedFile: event.target.files[0],
loaded: 0,
})
}
onClickHandler = async () => {
const data = new FormData()
data.append('file', this.state.selectedFile);
const {data: post} = await axios.post("http://localhost:8080/cards/upload", data);
this.props.onFileLoad();
}
render() {
const fileName = this.state.selectedFile && this.state.selectedFile.name || 'Choose csv file';
return (
<div className="input-group mb-3">
<div className="input-group-prepend">
<button className="btn btn-primary" type="button" id="inputGroupFileAddon03" onClick={this.onClickHandler}>Upload</button>
</div>
<div className="custom-file">
<input type="file" className="custom-file-input" id="inputGroupFile03" onChange={this.onChangeHandler} aria-describedby="inputGroupFileAddon03"/>
<label className="custom-file-label" for="inputGroupFile03">{fileName}</label>
</div>
</div>
);
}
}
export default UploadCsvFile;
<file_sep>## Bank cards test application
* legalZoomTest is a web application that uses React in the frontEnd and spring boot at the backend.
* the spring boot backend has embbeded tomcat server
* it is assumed that card numbers are 16-digit long.
* expiry date must be entered with the format like "Nov-2017" (capital N and hyphen to separate moth from year). There is not format validation so you need to enter the correct format
## How to build and run?
To build locally:
./mvn spring-boot:run
The first time the build it will take a bit as it runs "npm install" to download the node_modules for the frontend.
Alternatively:
./mvn package
java -jar target/legalZoomTest-0.0.1-SNAPSHOT.jar
## How to test?
Run from the brower:
http://localhost:8080
<file_sep>import React, { Component } from 'react';
import axios from 'axios';
class ClearCardsButton extends Component {
onHandleClick = async () => {
const {data: post} = await axios.post("http://localhost:8080/cards/clear");
console.log(post);
this.props.onCleared();
}
render() {
return (
<button
className="btn btn-secondary"
onClick={this.onHandleClick}
>
Clear all Cards
</button>
);
}
}
export default ClearCardsButton;
<file_sep>import React, { Component } from "react";
import { Route, Redirect, Switch } from "react-router-dom";
import "./App.css";
import Cards from "./Cards"
import CardForm from "./CardForm"
class App extends Component {
render() {
return (
<main className="container">
<Switch>
<Route path="/cards/create" component={CardForm} />
<Route path="/cards" component={Cards} />
<Redirect from="/" exact to="/cards" />
</Switch>
</main>
);
}
}
export default App;
|
edb230cf6e4f1040bf13ec56cd5ccc1d87f7f599
|
[
"JavaScript",
"Java",
"Markdown"
] | 8
|
Java
|
enricjaen/EJV_03062019
|
3a6887cf74affd043cc8233679713d8619861962
|
a9fcc4d7a1ffc99e1955487b799a00e25249f49c
|
refs/heads/master
|
<repo_name>Lightbpk/fly_killer<file_sep>/android/app/src/main/kotlin/com/example/fly_killer/MainActivity.kt
package com.example.fly_killer
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
|
776fbe2eb27fc756532220ac2a8517d35a77aa10
|
[
"Kotlin"
] | 1
|
Kotlin
|
Lightbpk/fly_killer
|
3d257680c79052fdf30b1c2469583b28d7f46e4e
|
8b90daf786e037ccfa9930118f8a32118b5734ed
|
refs/heads/master
|
<repo_name>EliEladElrom/ServicesHelper.PHP<file_sep>/models/services/abstract_services.php
<?php
/**
* Abstract_services
*
*
* @category CategoryName
* @package PackageName
* @author Original Author <<EMAIL>>
*/
include_once 'models/services/iservices.php';
class Abstract_services implements Iservices {
public $table_name = '';
public $primary_key_name = '';
public $vo_class_name = '';
public static $dbh;
public function setTableInformation( $table_name, $primary_key_name, $vo_class_name) {
// connect to db
include('include/connection.php');
Abstract_services::$dbh = Connection::connectToDatabase();
$this->table_name = $table_name;
$this->primary_key_name = $primary_key_name;
$this->vo_class_name = $vo_class_name;
}
public function create($data) {
// implement
}
public function read($id) {
$SqlStatement = "SELECT * FROM ".$this->table_name." WHERE ".$this->primary_key_name." = '$id'";
$row = Abstract_services::$dbh->getRow($SqlStatement, DB_FETCHMODE_ASSOC);
if (PEAR::isError($row)) {
echo "An error occurred while trying to run your query: $SqlStatement<br>\n";
echo "Error message: " . $row->getMessage() . "<br>\n";
echo "A more detailed error description: " . $row->getDebugInfo() . "<br>\n";
} else {
// EE: TODO push message to firebug
// echo 'success ' . $SqlStatement . '; ' . $row['username'];
}
if(!class_exists($this->vo_class_name,true)){
throw new Exception('Class: '.$this->vo_class_name.' not found.');
}
$methodName = 'setParams';
$classObj = new $this->vo_class_name();
$classObj->$methodName($row);
return $classObj;
$dbh->disconnect;
}
public function update($data) {
// implement
}
public function delete($id) {
// implement
}
}<file_sep>/README.md
[WORK IN PROGRESS]
This is a lightweight scaffolding to help creating a services layer regardless your framework codeigniter, smarty etc. Many of the frameworks out there
provide assistance connecting to database, getting results etc, however you end up marry the framework and in case you want to create a standalone component
or switch framework it would be difficault.
This helpers porpose is to sit on top of any framework you use and provide the necessery tools to connect to the database and generate a value object (vo).
You will need to install pear.
Than install the DB module:
pear install DB
<file_sep>/models/vo/user_vo.php
<?php
/**
* User_vo
*
* @category CategoryName
* @package PackageName
* @author Original Author <<EMAIL>>
*/
class User_vo
{
public $id;
public $username;
public $password;
public function __construct() {
}
public function setParams($array)
{
$this->id = $array['id'];
$this->username = $array['username'];
$this->password = $array['<PASSWORD>'];
}
}<file_sep>/models/services/user_service.php
<?php
/**
* User_service
*
*
* @category CategoryName
* @package PackageName
* @author Original Author <<EMAIL>>
*/
include_once 'models/services/abstract_services.php';
include_once 'models/vo/User_vo.php';
class User_service extends abstract_services {
const TABLE_NAME = 'user';
const PRIMARY_KEY_NAME = 'email';
const VO_CLASS_NAME = 'User_vo';
public function __construct() {
$this->setTableInformation($this::TABLE_NAME,$this::PRIMARY_KEY_NAME,$this::VO_CLASS_NAME);
}
// EE: additional methods will be declared here
public function validateUser($email, $password) {
}
}
?><file_sep>/models/services/iservices.php
<?php
/**
* Abstract_services
*
*
* @category CategoryName
* @package PackageName
* @author Original Author <<EMAIL>>
*/
interface Iservices {
function create($data);
function read($id);
function update($data);
function delete($id);
}<file_sep>/include/connection.php
<?
/**
* Connection
*
* @category CategoryName
* @package PackageName
* @author Original Author <<EMAIL>>
*/
class Connection
{
public static $dsn = array(
'phptype' => "mysql",
'hostspec' => "localhost",
'database' => "[someDatabase]",
'username' => "root",
'password' => ""
);
const PEAR_LOCATION = '/Users/elad/pear/share/pear';
public static function connectToDatabase() {
set_include_path(Connection::PEAR_LOCATION);
include("DB.php");
$dbh = DB::connect(Connection::$dsn);
if (PEAR::isError($dbh)) {
echo "An error occurred while trying to connect to the database server.<br>\n";
echo "Error message: " . $dbh->getMessage() . "<br>\n";
echo "Debug info: " . $dbh->getDebugInfo() . "<br>\n";
die();
}
return $dbh;
}
public static function disconnect($dbh) {
$dbh->disconnect;
}
}
|
dc14d9a2ad57c8fb4256eaac21dc47717a9d5ce5
|
[
"Markdown",
"PHP"
] | 6
|
PHP
|
EliEladElrom/ServicesHelper.PHP
|
8f61adf75f9f7e95c60b3dde25c33505ece81383
|
b7b0880f7c4608af2f2eeed6c6b65adac04c1de9
|
refs/heads/master
|
<repo_name>Sefact/PRSproject<file_sep>/Web/blog/views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from .models import Blike, Beditor, LikeComment
from .forms import CommentForm
def home(request):
blikes = Blike.objects
beditors = Beditor.objects
return render(request, 'home.html', {'blikes': blikes, 'beditors': beditors})
def beditordetail(request, beditor_id):
beditor_detail = get_object_or_404(Beditor, pk=beditor_id)
return render(request, 'beditor_detail.html', {'beditor': beditor_detail})
def introduce(request):
return render(request, 'introduce.html')
def contact(request):
return render(request, 'contact.html')
def blog_like_detail(request, blike_id):
blike = get_object_or_404(Blike, pk=blike_id)
#만약 post일때만 댓글 입력에 관한 처리를 더한다.
if request.method == "POST":
comment_form = CommentForm(request.POST)
comment_form.instance.author_id = request.user.id
comment_form.instance.blike_id = blike_id
if comment_form.is_valid():
comment = comment_form.save()
#models.py에서 document의 related_name을 comments로 해놓았다.
comment_form = CommentForm()
like_comments = blike.like_comments.all()
return render(request, 'blike_detail.html', {'blike':blike, "like_comments":like_comments, "comment_form":comment_form})
# Create your views here.<file_sep>/Final/blog/urls.py
from django.contrib import admin
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.home, name='home'),
path('like/<int:blike_id>', views.blog_like_detail, name="blog_like_detail"),
path('editor/<int:beditor_id>', views.beditordetail, name="beditordetail"),
path('introduce', views.introduce, name='introduce'),
path('contact', views.contact, name='contact'),
]<file_sep>/Final/photo/migrations/0001_initial.py
# Generated by Django 2.2 on 2020-08-22 06:13
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Photo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100)),
('text', models.TextField(blank=True)),
('division', models.CharField(max_length=100)),
('rating', models.CharField(blank=True, max_length=10, null=True)),
('address', models.CharField(max_length=200)),
('call', models.CharField(max_length=100)),
('park', models.CharField(max_length=50)),
('hours', models.CharField(max_length=50)),
('price', models.TextField(max_length=200)),
('image_one', models.ImageField(blank=True, null=True, upload_to='images/like/%Y/%m/%d')),
('image_two', models.ImageField(blank=True, null=True, upload_to='images/like/%Y/%m/%d')),
('image_three', models.ImageField(blank=True, null=True, upload_to='images/like/%Y/%m/%d')),
('image_four', models.ImageField(blank=True, null=True, upload_to='images/like/%Y/%m/%d')),
('image_five', models.ImageField(blank=True, null=True, upload_to='images/like/%Y/%m/%d')),
('maps', models.ImageField(blank=True, null=True, upload_to='images/maps/%Y/%m/%d')),
('updated', models.DateTimeField(auto_now=True)),
('created', models.DateTimeField(auto_now_add=True)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user', to=settings.AUTH_USER_MODEL)),
('favorite', models.ManyToManyField(blank=True, related_name='favorite_post', to=settings.AUTH_USER_MODEL)),
('like', models.ManyToManyField(blank=True, related_name='like_post', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ['-created'],
},
),
]
<file_sep>/Final/blog/models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Blike(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
division = models.CharField(max_length=100)
rating = models.CharField(max_length=10, null=True, blank=True)
address = models.CharField(max_length=200)
call = models.CharField(max_length=100)
park = models.CharField(max_length=50)
hours = models.CharField(max_length=50)
price = models.TextField(max_length=200)
context = models.TextField(max_length=500, null=True, blank=True)
image_one = models.ImageField(upload_to="images/blog/%Y/%m/%d", blank=True, null=True)
image_two = models.ImageField(upload_to="images/blog/%Y/%m/%d", blank=True, null=True)
image_three = models.ImageField(upload_to="images/blog/%Y/%m/%d", blank=True, null=True)
image_four = models.ImageField(upload_to="images/blog/%Y/%m/%d", blank=True, null=True)
image_five = models.ImageField(upload_to="images/blog/%Y/%m/%d", blank=True, null=True)
maps = models.ImageField(upload_to="images/maps/%Y/%m/%d", blank=True, null=True)
pub_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def summary(self):
return self.context[:200]
class Beditor(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
division = models.CharField(max_length=100)
rating = models.CharField(max_length=10, null=True, blank=True)
address = models.CharField(max_length=200)
call = models.CharField(max_length=100)
park = models.CharField(max_length=50)
hours = models.CharField(max_length=50)
price = models.TextField(max_length=200)
context = models.TextField(max_length=500, null=True, blank=True)
image_one = models.ImageField(upload_to="images/%Y/%m/%d", blank=True, null=True)
image_two = models.ImageField(upload_to="images/%Y/%m/%d", blank=True, null=True)
image_three = models.ImageField(upload_to="images/%Y/%m/%d", blank=True, null=True)
image_four = models.ImageField(upload_to="images/%Y/%m/%d", blank=True, null=True)
image_five = models.ImageField(upload_to="images/%Y/%m/%d", blank=True, null=True)
maps = models.ImageField(upload_to="images/maps/%Y/%m/%d", blank=True, null=True)
pub_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class LikeComment(models.Model):
blike = models.ForeignKey(Blike, on_delete=models.CASCADE, related_name='like_comments')
author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='like_comments')
text = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
like = models.IntegerField(default=0)
dislike = models.IntegerField(default=0)
def __str__(self):
return (self.author.username if self.author else "무명")+ "의 댓글"<file_sep>/Web/tag/templates/art.html
{% extends 'base.html' %}
{% block content %}
<!-- Page Content -->
<div class="container">
<!-- Page Heading/Breadcrumbs -->
<h1 class="mt-4 mb-3">미술관</h1>
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="{% url 'home' %}">Home</a>
</li>
<li class="breadcrumb-item">
<a href="{% url 'tag' %}">Tag</a>
</li>
<li class="breadcrumb-item active">Art</li>
</ol>
<div class="row">
{% for art in arts.all %}
<div class="col-md-7">
<a href="{% url 'artdetail' art.id %}">
<img class="img-fluid rounded mb-3 mb-md-0" src="{{ art.image_one.url }}" alt="">
</a>
</div>
<div class="col-md-5">
<h3>{{ art.title }}<span style="font-weight: bold; font-size: x-large; color: #FFA500;"> {{ art.rating }}</span></h3>
<a style="color: #D5D4D4;">{{ art.division }}</a>
<p>{{ art.summary }}...</p>
<p><hr>주소 : {{ art.address }}<br>
전화번호 : {{ art.call }}<br>
주차 : {{ art.park }}<br>
영업시간 : {{ art.hours }}<br>
입장료 : {{ art.price }}</p>
<a class="btn btn-primary" href="#">더 보기
<span class="glyphicon glyphicon-chevron-right"></span>
</a>
<p><br><br></p>
</div>
{% endfor %}
</div>
</div>
{% endblock content %}<file_sep>/Final/document/views.py
from django.shortcuts import render, redirect, get_object_or_404
from .models import Document, Comment
from .forms import CommentForm
def document(request):
documents = Document.objects
return render(request, 'document.html', {'documents': documents})
def document_detail(request, document_id):
document = get_object_or_404(Document, pk=document_id)
#만약 post일때만 댓글 입력에 관한 처리를 더한다.
if request.method == "POST":
comment_form = CommentForm(request.POST)
comment_form.instance.author_id = request.user.id
comment_form.instance.document_id = document_id
if comment_form.is_valid():
comment = comment_form.save()
#models.py에서 document의 related_name을 comments로 해놓았다.
comment_form = CommentForm()
comments = document.comments.all()
return render(request, 'document_detail.html', {'document':document, "comments":comments, "comment_form":comment_form})
# Create your views here.<file_sep>/Final/photo/models.py
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
# Create your models here.
class Photo(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user')
title = models.CharField(max_length=100)
text = models.TextField(blank=True)
division = models.CharField(max_length=100)
rating = models.CharField(max_length=10, null=True, blank=True)
address = models.CharField(max_length=200)
call = models.CharField(max_length=100)
park = models.CharField(max_length=50)
hours = models.CharField(max_length=50)
price = models.TextField(max_length=200)
image_one = models.ImageField(upload_to="images/like/%Y/%m/%d", blank=True, null=True)
image_two = models.ImageField(upload_to="images/like/%Y/%m/%d", blank=True, null=True)
image_three = models.ImageField(upload_to="images/like/%Y/%m/%d", blank=True, null=True)
image_four = models.ImageField(upload_to="images/like/%Y/%m/%d", blank=True, null=True)
image_five = models.ImageField(upload_to="images/like/%Y/%m/%d", blank=True, null=True)
maps = models.ImageField(upload_to="images/maps/%Y/%m/%d", blank=True, null=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
like = models.ManyToManyField(User, related_name='like_post', blank=True)
favorite = models.ManyToManyField(User, related_name='favorite_post', blank=True)
def __str__(self):
return "text : "+self.text
class Meta:
ordering = ['-created']
def get_absolute_url(self):
return reverse('photo:detail', args=[self.id])
# Create your models here.
<file_sep>/Web/accounts/views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import login as user_login
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login as user_login
from django.contrib.auth import logout as user_logout
from django.contrib.auth.forms import AuthenticationForm
from .forms import CustomUserCreationForm
from .models import Profile
def signup(request):
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
user = form.save()
user_login(request, user)
return redirect('blog:home')
else:
form = CustomUserCreationForm() # 비어있는 회원가입 폼을 생성한다.
return render(request, 'accounts/form.html', {'form': form})
# forms.html 파일을 렌더한다. 이때 위에서 생성한 회원가입 폼을 'form'이라는 이름으로 함께 보낸다.(딕셔너리)
def login(request):
if request.method == 'POST':
form = AuthenticationForm(request, request.POST)
# 회원가입과 다르게 맨 앞의 인자로 request가 들어간다.
if form.is_valid():
user_login(request, form.get_user())
return redirect('blog:home')
return redirect('accounts:login')
else:
form = AuthenticationForm()
return render(request, 'accounts/form.html', {'form': form})
def logout(request):
user_logout(request)
return redirect('blog:home')
# Create your views here.<file_sep>/Final/recommend/urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('like', views.like, name="like"),
path('like/<int:like_id>', views.ldetail, name="ldetail"),
path('recommend', views.recommend, name="recommend"),
path('recommend/<int:recommend_id>', views.rdetail, name="rdetail"),
path('editor', views.editor, name="editor"),
path('editor/<int:editor_id>', views.edetail, name="edetail"),
path('area', views.area, name="area"),
path('area/seoul', views.seoul, name="seoul"),
path('area/seoul/<int:seoul_id>', views.seoul_detail, name="seoul_detail"),
path('area/incheon', views.incheon, name="incheon"),
path('area/incheon/<int:incheon_id>', views.incheon_detail, name="incheon_detail"),
path('area/busan', views.busan, name="busan"),
path('area/busan/<int:busan_id>', views.busan_detail, name="busan_detail"),
path('area/gwanggu', views.gwanggu, name="gwanggu"),
path('area/gwanggu/<int:gwanggu_id>', views.gwanggu_detail, name="gwanggu_detail"),
path('area/daejon', views.daejon, name="daejon"),
path('area/daejon/<int:daejon_id>', views.daejon_detail, name="daejon_detail"),
path('area/gangwon', views.gangwon, name="gangwon"),
path('area/gangwon/<int:gangwon_id>', views.gangwon_detail, name="gangwon_detail"),
]<file_sep>/Web/recommend/migrations/0001_initial.py
# Generated by Django 2.2 on 2020-08-22 05:29
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Recommend',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100)),
('division', models.CharField(max_length=100)),
('rating', models.CharField(blank=True, max_length=10, null=True)),
('address', models.CharField(max_length=200)),
('call', models.CharField(max_length=100)),
('park', models.CharField(max_length=50)),
('hours', models.CharField(max_length=50)),
('price', models.TextField(max_length=200)),
('context', models.TextField(blank=True, max_length=500, null=True)),
('image_one', models.ImageField(blank=True, null=True, upload_to='images/%Y/%m/%d')),
('image_two', models.ImageField(blank=True, null=True, upload_to='images/%Y/%m/%d')),
('image_three', models.ImageField(blank=True, null=True, upload_to='images/%Y/%m/%d')),
('image_four', models.ImageField(blank=True, null=True, upload_to='images/%Y/%m/%d')),
('image_five', models.ImageField(blank=True, null=True, upload_to='images/%Y/%m/%d')),
('pub_date', models.DateTimeField(auto_now_add=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Like',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100)),
('division', models.CharField(max_length=100)),
('rating', models.CharField(blank=True, max_length=10, null=True)),
('address', models.CharField(max_length=200)),
('call', models.CharField(max_length=100)),
('park', models.CharField(max_length=50)),
('hours', models.CharField(max_length=50)),
('price', models.TextField(max_length=200)),
('context', models.TextField(blank=True, max_length=500, null=True)),
('image_one', models.ImageField(blank=True, null=True, upload_to='images/%Y/%m/%d')),
('image_two', models.ImageField(blank=True, null=True, upload_to='images/%Y/%m/%d')),
('image_three', models.ImageField(blank=True, null=True, upload_to='images/%Y/%m/%d')),
('image_four', models.ImageField(blank=True, null=True, upload_to='images/%Y/%m/%d')),
('image_five', models.ImageField(blank=True, null=True, upload_to='images/%Y/%m/%d')),
('pub_date', models.DateTimeField(auto_now_add=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Editor',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100)),
('division', models.CharField(max_length=100)),
('rating', models.CharField(blank=True, max_length=10, null=True)),
('address', models.CharField(max_length=200)),
('call', models.CharField(max_length=100)),
('park', models.CharField(max_length=50)),
('hours', models.CharField(max_length=50)),
('price', models.TextField(max_length=200)),
('context', models.TextField(blank=True, max_length=500, null=True)),
('image_one', models.ImageField(blank=True, null=True, upload_to='images/%Y/%m/%d')),
('image_two', models.ImageField(blank=True, null=True, upload_to='images/%Y/%m/%d')),
('image_three', models.ImageField(blank=True, null=True, upload_to='images/%Y/%m/%d')),
('image_four', models.ImageField(blank=True, null=True, upload_to='images/%Y/%m/%d')),
('image_five', models.ImageField(blank=True, null=True, upload_to='images/%Y/%m/%d')),
('pub_date', models.DateTimeField(auto_now_add=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Area',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100)),
('division', models.CharField(max_length=100)),
('rating', models.CharField(blank=True, max_length=10, null=True)),
('address', models.CharField(max_length=200)),
('call', models.CharField(max_length=100)),
('park', models.CharField(max_length=50)),
('hours', models.CharField(max_length=50)),
('price', models.TextField(max_length=200)),
('context', models.TextField(blank=True, max_length=500, null=True)),
('image_one', models.ImageField(blank=True, null=True, upload_to='images/%Y/%m/%d')),
('image_two', models.ImageField(blank=True, null=True, upload_to='images/%Y/%m/%d')),
('image_three', models.ImageField(blank=True, null=True, upload_to='images/%Y/%m/%d')),
('image_four', models.ImageField(blank=True, null=True, upload_to='images/%Y/%m/%d')),
('image_five', models.ImageField(blank=True, null=True, upload_to='images/%Y/%m/%d')),
('pub_date', models.DateTimeField(auto_now_add=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
<file_sep>/Web/recommend/admin.py
from django.contrib import admin
from .models import Like
from .models import Recommend
from .models import Editor
from .models import Seoul, Incheon, Busan, Gwanggu, Daejon, Gangwon
admin.site.register(Like)
admin.site.register(Recommend)
admin.site.register(Editor)
admin.site.register(Seoul)
admin.site.register(Incheon)
admin.site.register(Busan)
admin.site.register(Gwanggu)
admin.site.register(Daejon)
admin.site.register(Gangwon)
# Register your models here.
<file_sep>/Web/accounts/forms.py
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth import get_user_model
from django import forms
from .models import Profile
class CustomUserCreationForm(UserCreationForm):
username = forms.CharField(
label="",
widget=forms.TextInput(attrs={
"placeholder": "사용자 이름",
})
)
password1 = forms.CharField(
label="",
widget=forms.PasswordInput(attrs={
"placeholder": "비밀번호(8자 이상)",
})
)
password2 = forms.CharField(
label="",
widget=forms.PasswordInput(attrs={
"placeholder": "비밀번호 확인",
})
)
class Meta:
model = get_user_model()
fields = ['username', '<PASSWORD>', '<PASSWORD>',]<file_sep>/Final/recommend/migrations/0003_auto_20200822_1638.py
# Generated by Django 2.2 on 2020-08-22 07:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('recommend', '0002_auto_20200822_1513'),
]
operations = [
migrations.AddField(
model_name='area',
name='maps',
field=models.ImageField(blank=True, null=True, upload_to='images/maps/%Y/%m/%d'),
),
migrations.AddField(
model_name='editor',
name='maps',
field=models.ImageField(blank=True, null=True, upload_to='images/maps/%Y/%m/%d'),
),
migrations.AddField(
model_name='recommend',
name='maps',
field=models.ImageField(blank=True, null=True, upload_to='images/maps/%Y/%m/%d'),
),
migrations.AlterField(
model_name='area',
name='image_five',
field=models.ImageField(blank=True, null=True, upload_to='images/recommend/%Y/%m/%d'),
),
migrations.AlterField(
model_name='area',
name='image_four',
field=models.ImageField(blank=True, null=True, upload_to='images/recommend/%Y/%m/%d'),
),
migrations.AlterField(
model_name='area',
name='image_one',
field=models.ImageField(blank=True, null=True, upload_to='images/recommend/%Y/%m/%d'),
),
migrations.AlterField(
model_name='area',
name='image_three',
field=models.ImageField(blank=True, null=True, upload_to='images/recommend/%Y/%m/%d'),
),
migrations.AlterField(
model_name='area',
name='image_two',
field=models.ImageField(blank=True, null=True, upload_to='images/recommend/%Y/%m/%d'),
),
migrations.AlterField(
model_name='editor',
name='image_five',
field=models.ImageField(blank=True, null=True, upload_to='images/recommend/%Y/%m/%d'),
),
migrations.AlterField(
model_name='editor',
name='image_four',
field=models.ImageField(blank=True, null=True, upload_to='images/recommend/%Y/%m/%d'),
),
migrations.AlterField(
model_name='editor',
name='image_one',
field=models.ImageField(blank=True, null=True, upload_to='images/recommend/%Y/%m/%d'),
),
migrations.AlterField(
model_name='editor',
name='image_three',
field=models.ImageField(blank=True, null=True, upload_to='images/recommend/%Y/%m/%d'),
),
migrations.AlterField(
model_name='editor',
name='image_two',
field=models.ImageField(blank=True, null=True, upload_to='images/recommend/%Y/%m/%d'),
),
migrations.AlterField(
model_name='recommend',
name='image_five',
field=models.ImageField(blank=True, null=True, upload_to='images/recommend/%Y/%m/%d'),
),
migrations.AlterField(
model_name='recommend',
name='image_four',
field=models.ImageField(blank=True, null=True, upload_to='images/recommend/%Y/%m/%d'),
),
migrations.AlterField(
model_name='recommend',
name='image_one',
field=models.ImageField(blank=True, null=True, upload_to='images/recommend/%Y/%m/%d'),
),
migrations.AlterField(
model_name='recommend',
name='image_three',
field=models.ImageField(blank=True, null=True, upload_to='images/recommend/%Y/%m/%d'),
),
migrations.AlterField(
model_name='recommend',
name='image_two',
field=models.ImageField(blank=True, null=True, upload_to='images/recommend/%Y/%m/%d'),
),
]
<file_sep>/etc/test3.py
print('test git commit file')
<file_sep>/Web/tag/models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Cafe(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
division = models.CharField(max_length=100)
rating = models.CharField(max_length=10, null=True, blank=True)
address = models.CharField(max_length=200)
call = models.CharField(max_length=100)
park = models.CharField(max_length=50)
hours = models.CharField(max_length=50)
price = models.TextField(max_length=200)
context = models.TextField(max_length=500, null=True, blank=True)
image_one = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
image_two = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
image_three = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
image_four = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
image_five = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
maps = models.ImageField(upload_to="images/maps/%Y/%m/%d", blank=True, null=True)
pub_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def summary(self):
return self.context[:200]
class Art(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
division = models.CharField(max_length=100)
rating = models.CharField(max_length=10, null=True, blank=True)
address = models.CharField(max_length=200)
call = models.CharField(max_length=100)
park = models.CharField(max_length=50)
hours = models.CharField(max_length=50)
price = models.TextField(max_length=200)
context = models.TextField(max_length=500, null=True, blank=True)
image_one = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
image_two = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
image_three = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
image_four = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
image_five = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
maps = models.ImageField(upload_to="images/maps/%Y/%m/%d", blank=True, null=True)
pub_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def summary(self):
return self.context[:200]
class Food(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
division = models.CharField(max_length=100)
rating = models.CharField(max_length=10, null=True, blank=True)
address = models.CharField(max_length=200)
call = models.CharField(max_length=100)
park = models.CharField(max_length=50)
hours = models.CharField(max_length=50)
price = models.TextField(max_length=200)
context = models.TextField(max_length=500, null=True, blank=True)
image_one = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
image_two = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
image_three = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
image_four = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
image_five = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
maps = models.ImageField(upload_to="images/maps/%Y/%m/%d", blank=True, null=True)
pub_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def summary(self):
return self.context[:200]
class Theater(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
division = models.CharField(max_length=100)
rating = models.CharField(max_length=10, null=True, blank=True)
address = models.CharField(max_length=200)
call = models.CharField(max_length=100)
park = models.CharField(max_length=50)
hours = models.CharField(max_length=50)
price = models.TextField(max_length=200)
context = models.TextField(max_length=500, null=True, blank=True)
image_one = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
image_two = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
image_three = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
image_four = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
image_five = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
maps = models.ImageField(upload_to="images/maps/%Y/%m/%d", blank=True, null=True)
pub_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def summary(self):
return self.context[:200]
class Escape(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
division = models.CharField(max_length=100)
rating = models.CharField(max_length=10, null=True, blank=True)
address = models.CharField(max_length=200)
call = models.CharField(max_length=100)
park = models.CharField(max_length=50)
hours = models.CharField(max_length=50)
price = models.TextField(max_length=200)
context = models.TextField(max_length=500, null=True, blank=True)
image_one = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
image_two = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
image_three = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
image_four = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
image_five = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
maps = models.ImageField(upload_to="images/maps/%Y/%m/%d", blank=True, null=True)
pub_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def summary(self):
return self.context[:200]
class Travle(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
division = models.CharField(max_length=100)
rating = models.CharField(max_length=10, null=True, blank=True)
address = models.CharField(max_length=200)
call = models.CharField(max_length=100)
park = models.CharField(max_length=50)
hours = models.CharField(max_length=50)
price = models.TextField(max_length=200)
context = models.TextField(max_length=500, null=True, blank=True)
image_one = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
image_two = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
image_three = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
image_four = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
image_five = models.ImageField(upload_to="images/tag/%Y/%m/%d", blank=True, null=True)
maps = models.ImageField(upload_to="images/maps/%Y/%m/%d", blank=True, null=True)
pub_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def summary(self):
return self.context[:200]<file_sep>/Final/blog/admin.py
from django.contrib import admin
from .models import Blike, Beditor, LikeComment
admin.site.register(Blike)
admin.site.register(Beditor)
admin.site.register(LikeComment)
# Register your models here.<file_sep>/Web/blog/migrations/0002_beditor_maps.py
# Generated by Django 2.2 on 2020-08-22 15:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='beditor',
name='maps',
field=models.ImageField(blank=True, null=True, upload_to='images/maps/%Y/%m/%d'),
),
]
<file_sep>/Final/crawling/recommend.py
#-*- coding:utf-8 -*-
import grade_data as d
import sys
from math import sqrt
#==================================================================================================
# person1과 person2의 그레디언트 거리 계산
def sim_distance(prefs, person1, person2):
si = dict()
for item in prefs[person1]:
if item in prefs[person2]:
si[item] = 1
if len(si) == 0:
return 0
sum_of_squares = sum([(prefs[person1][item] - prefs[person2][item])**2 for item in prefs[person1] if item in prefs[person2]])
return 1/(1+sqrt(sum_of_squares))
#==================================================================================================
def sim_pearson(prefs, p1, p2):
si = dict() # 같이 평가한 항목들의 목록을 구함
for item in prefs[p1]:
if item in prefs[p2]:
si[item] = 1
n = len(si) # 공통 항목 갯수
# 공통 항목이 없으면 0
if n == 0:
return 0
# 모든 선호도 합 계산
sum1 = sum([prefs[p1][it] for it in si])
sum2 = sum([prefs[p2][it] for it in si])
# 제곱의 합 계산
sum1Sq = sum([(prefs[p1][it])**2 for it in si])
sum2Sq = sum([(prefs[p2][it])**2 for it in si])
# 곱의 합 계산
pSum = sum([prefs[p1][it] * prefs[p2][it] for it in si])
# 피어슨 점수 계산
num = pSum - (sum1*sum2/n)
den = sqrt((sum1Sq-pow(sum1,2)/n) * (sum2Sq-pow(sum2,2)/n))
if den==0:
return 0
r = num/den
return r
#==================================================================================================
# 선호도 dict를 사용하여 평가 유사도가 높은 상대편을 구함
def top_match(prefs, person, n=5, similarity=sim_pearson):
scores = [ (similarity(prefs, person, other), other) for other in prefs if other!=person ]
scores.sort()
scores.reverse()
return scores[:n]
#==================================================================================================
# 다른 사람과의 순위의 가중 평균값을 이용해서 특정 사람을 추천
def get_recommendations(prefs, person, similarity=sim_pearson):
total = dict()
sim_Sum = dict()
for other in prefs:
if other == person:
continue
sim = similarity(prefs, person, other) #person과 other 사이의 유사도 점수를 구함
# 0 이하 점수는 무시
if sim <= 0:
continue
# other가 평가한 데이트 장소
for item in prefs[other]:
# 내가 평가하지 않은 장소만을 대상으로 함
if item not in prefs[person] or prefs[person][item] == 0:
# 유사도*점수
total.setdefault(item, 0)
total[item] += prefs[other][item]*sim # other가 평가한 영화의 점수 * person과 other의 상관계수
# 유사도 합계
sim_Sum.setdefault(item, 0)
sim_Sum[item] += sim
# 정규화된 목록 생성
ranking = [ (total/sim_Sum[item], item) for item, total in total.items() ]
# 정렬된 목록 리턴
ranking.sort()
ranking.reverse()
return ranking
#==================================================================================================
# 결과값 출력
print("추천 데이트 장소 추출 완료")
sys.stdout=open('recommend.txt', 'a') # 결과값을 텍스트파일로 저장
place_grade_rank=0
print("★선호장소가 유사한 회원★")
for score, other in top_match(d.grade, "기원"):
place_grade_rank = place_grade_rank + 1
print(place_grade_rank, "순위", other, "(", round(score, 2), ")")
print()
recommend_grade_rank = 0
print("★추천 데이트장소★")
for score, item in get_recommendations(d.grade, "기원", similarity=sim_distance):
recommend_grade_rank = recommend_grade_rank + 1
print(recommend_grade_rank, "순위", item, "(", round(score,2), ")")
<file_sep>/Visualization/keyword_last.py
#-*- coding:utf-8 -*-
from konlpy.tag import Okt
from collections import Counter
def get_tags(text, ntags=50):
okt = Okt()
nouns = okt.nouns(text)
count = Counter(nouns)
noun_count_list = [] # 빈도수를 저장하는 변수
for n, c in count.most_common(ntags):
temp = {'tag': n, 'count': c}
noun_count_list.append(temp)
return noun_count_list
input_file_name = "tagdata.txt"
noun_count = 100 # 빈도수에 따른 키워드 결과값 최대 100개
output_file_name = "keyword.txt"
open_text_file = open(input_file_name, 'r', -1, "utf-8")
text = open_text_file.read()
tags = get_tags(text, noun_count)
open_text_file.close()
open_output_file = open(output_file_name, 'w', -1, "utf-8")
for tag in tags:
noun = tag['tag']
count = tag['count']
open_output_file.write('{} {}\n'.format(noun, count))
open_output_file.close()
print("키워드 추출 완료")<file_sep>/README.md
# PRSproject
# Senior project
데이트 장소 추천 웹 사이트
<file_sep>/Visualization/grade_data.py
grade = {
'기원': {
'N 서울타워': 4.5,
'차이나타운': 1.0,
'오륙도 스카이워크': 4.0
},
'효연': {
'대전엑스포 시민광장': 2.5,
'N 서울타워': 3.5,
'남이섬': 3.0,
'오륙도 스카이워크': 3.5,
'차이나타운': 2.5,
'헤이리마을': 3.0
},
'user2': {
'대전엑스포 시민광장': 3.0,
'N 서울타워': 3.5,
'남이섬': 1.5,
'오륙도 스카이워크': 5.0,
'헤이리마을': 3.0,
'차이나타운': 3.5
},
'user3': {
'대전엑스포 시민광장': 2.5,
'N 서울타워': 3.5,
'오륙도 스카이워크': 3.5,
'헤이리마을': 4.0
},
'user4': {
'N 서울타워': 3.5,
'남이섬': 3.0,
'헤이리마을': 4.5,
'오륙도 스카이워크': 4.0,
'차이나타운': 2.5
},
'user5': {
'대전엑스포 시민광장': 3.0,
'N 서울타워': 4.0,
'남이섬': 2.0,
'오륙도 스카이워크': 3.0,
'헤이리마을': 3.0,
'차이나타운': 2.0
},
'user6': {
'대전엑스포 시민광장': 3.0,
'N 서울타워': 4.0,
'헤이리마을': 3.0,
'오륙도 스카이워크': 5.0,
'차이나타운': 3.5
}
}
<file_sep>/Web/recommend/views.py
from django.shortcuts import render, get_object_or_404, redirect
from .models import Like, Recommend, Editor, Area
from .models import Seoul, Incheon, Busan, Gwanggu, Daejon, Gangwon
def like(request):
likes = Like.objects
return render(request, 'like.html', {'likes': likes})
def ldetail(request, like_id):
like_detail = get_object_or_404(Like, pk=like_id)
return render(request, 'ldetail.html', {'like': like_detail})
def recommend(request):
recommends = Recommend.objects
return render(request, 'recommend.html', {'recommends': recommends})
def rdetail(request, recommend_id):
recommend_detail = get_object_or_404(Recommend, pk=recommend_id)
return render(request, 'rdetail.html', {'recommend': recommend_detail})
def editor(request):
editors = Editor.objects
return render(request, 'editor.html', {'editors': editors})
def edetail(request, editor_id):
editor_detail = get_object_or_404(Editor, pk=editor_id)
return render(request, 'edetail.html', {'editor': editor_detail})
def area(request):
return render(request, 'area.html')
def seoul(request):
seouls = Seoul.objects
return render(request, 'area/seoul.html', {'seouls': seouls})
def seoul_detail(request, seoul_id):
seoul_detail = get_object_or_404(Seoul, pk=seoul_id)
return render(request, 'area/seoul_detail.html', {'seoul': seoul_detail})
def incheon(request):
incheons = Incheon.objects
return render(request, 'area/incheon.html', {'incheons': incheons})
def incheon_detail(request, incheon_id):
incheon_detail = get_object_or_404(Incheon, pk=incheon_id)
return render(request, 'area/incheon_detail.html', {'incheon': incheon_detail})
def busan(request):
busans = Busan.objects
return render(request, 'area/busan.html', {'busans': busans})
def busan_detail(request, busan_id):
busan_detail = get_object_or_404(Busan, pk=busan_id)
return render(request, 'area/busan_detail.html', {'busan': busan_detail})
def gwanggu(request):
gwanggus = Gwanggu.objects
return render(request, 'area/gwanggu.html', {'gwanggus': gwanggus})
def gwanggu_detail(request, gwanggu_id):
gwanggu_detail = get_object_or_404(Gwanggu, pk=gwanggu_id)
return render(request, 'area/gwanggu_detail.html', {'gwanggu': gwanggu_detail})
def daejon(request):
daejons = Daejon.objects
return render(request, 'area/daejon.html', {'daejons': daejons})
def daejon_detail(request, daejon_id):
daejon_detail = get_object_or_404(Daejon, pk=daejon_id)
return render(request, 'area/daejon_detail.html', {'daejon': daejon_detail})
def gangwon(request):
gangwons = Gangwon.objects
return render(request, 'area/gangwon.html', {'gangwons': gangwons})
def gangwon_detail(request, gangwon_id):
gangwon_detail = get_object_or_404(Gangwon, pk=gangwon_id)
return render(request, 'area/gangwon_detail.html', {'gangwon': gangwon_detail})
# Create your views here.<file_sep>/Web/recommend/templates/editor.html
{% extends 'base.html' %}
{% block content %}
<!-- Page Content -->
<div class="container">
<!-- Page Heading/Breadcrumbs -->
<h1 class="mt-4 mb-3">에디터 추천</h1>
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="{% url 'home' %}">Home</a>
</li>
<li class="breadcrumb-item active">Editor</li>
</ol>
<div class="row">
{% for editor in editors.all %}
<div class="col-md-7">
<a href="{% url 'edetail' editor.id %}">
<img class="img-fluid rounded mb-3 mb-md-0" src="{{ editor.image_one.url }}" alt="">
</a>
</div>
<div class="col-md-5">
<h3>{{ editor.title }}<span style="font-weight: bold; font-size: x-large; color: #FFA500;"> {{ editor.rating }}</span></h3>
<a style="color: #D5D4D4;">{{ editor.division }}</a>
<p>{{ editor.summary }}</p>
<p><hr>주소 : {{ editor.address }}<br>
전화번호 : {{ editor.call }}<br>
주차 : {{ editor.park }}<br>
영업시간 : {{ editor.hours }}<br>
</p>
<a class="btn btn-primary" href="#">더 보기
<span class="glyphicon glyphicon-chevron-right"></span>
</a>
<p><br><br></p>
</div>
{% endfor %}
</div>
</div>
{% endblock content %}<file_sep>/crawling/prac1_2.py
from urllib.request import urlopen, Request
from urllib.parse import quote_plus
from bs4 import BeautifulSoup
from selenium import webdriver
from tqdm import tqdm
import pandas as pd
import time
from selenium.webdriver.common.keys import Keys
import warnings
warnings.filterwarnings(action='ignore')
SCROLL_PAUSE_TIME = 1.0 # 스크롤 내리는 시간
#===============================================================================================
# Chrome Driver로 url 생성
baseUrl = "https://www.instagram.com/explore/tags/"
plusUrl = input('태그입력 : ')
url = baseUrl + quote_plus(plusUrl)
print('Chrome Driver 실행중...')
driver = webdriver.Chrome('C:\webdriver\chromedriver.exe')
driver.get(url)
time.sleep(3)
#==================================================================================================
# 자동로그인
login_section = '//*[@id="react-root"]/section/nav/div[2]/div/div/div[3]/div/span/a[1]/button'
driver.find_element_by_xpath(login_section).click()
time.sleep(2)
elem_login = driver.find_element_by_name("username")
elem_login.clear()
elem_login.send_keys('write ID')
elem_login = driver.find_element_by_name('password')
elem_login.clear()
elem_login.send_keys('<PASSWORD>')
time.sleep(2)
xpath = """//*[@id="react-root"]/section/main/div/article/div/div[1]/div/form/div[4]/button"""
driver.find_element_by_xpath(xpath).click()
time.sleep(2)
#==================================================================================================
# 총 게시물 숫자 불러오기
pageString = driver.page_source
bsObj = BeautifulSoup(pageString, 'lxml')
temp_data = bsObj.find_all(name='meta')[-1]
temp_data = str(temp_data)
start = temp_data.find('게시물') + 4
end = temp_data.find('개')
total_post_data = temp_data[start:end]
print("총 {0}개의 게시물이 검색되었습니다.".format(total_post_data))
print('태그를 수집하는 중입니다...')
#==================================================================================================
reallink = [] # 전체 게시물 링크 저장
# url 화면에서 스크롤을 내리면서 게시물 크롤링
while True:
pageString = driver.page_source
bsObj = BeautifulSoup(pageString, 'lxml')
for link1 in bsObj.find_all(name='div', attrs={"class":"Nnq7C weEfm"}):
for i in range(3):
title = link1.select('a')[i]
real = title.attrs['href']
reallink.append(real)
last_scroll = driver.execute_script('return document.body.scrollHeight')
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(SCROLL_PAUSE_TIME)
new_scroll = driver.execute_script("return document.body.scrollHeight")
if new_scroll == last_scroll:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(SCROLL_PAUSE_TIME)
new_scroll = driver.execute_script("return document.body.scrollHeight")
# 현재 게시물이 마지막 게시물일 때 break
if new_scroll == last_scroll:
break
else:
last_scroll = new_scroll
continue
time.sleep(2)
total_tag_data = len(reallink) # 전체 태그 데이터의 크기 저장
print('총 {0}개의 태그를 수집합니다.'.format(total_tag_data))
csvtext = []
#==================================================================================================
# 프로그램 실시간 진행률을 알기 위한 tqdm 라이브러리 사용
for i in tqdm(range(total_tag_data)):
csvtext.append([])
req = Request("https://www.instagram.com/p"+reallink[i], headers={'User-Agent': 'Mozila/5.0'})
webpage = urlopen(req).read()
soup = BeautifulSoup(webpage, 'lxml', from_encoding='utf-8')
soup1 = soup.find('meta', attrs={'property':"og:description"})
reallink1 = soup1['content']
reallink1 = reallink1[reallink1.find("@") + 1:reallink1.find(")")]
reallink1 = reallink1[:20]
if reallink1 == '':
reallink1 = "Null"
csvtext[i].append(reallink1)
for reallink2 in soup.find_all('meta', attrs={'property':"instapp:hashtags"}):
hashtags = reallink2['content'].rstrip(',')
csvtext[i].append(hashtags)
# 데이터를 csv파일, txt파일로 저장
data = pd.DataFrame(csvtext)
data.to_csv('tagdata.csv', encoding='utf-8-sig')
data.to_csv('tagdata.txt', encoding='utf-8')
#==================================================================================================
driver.close() # Chrome Driver 종료
# 검색어 : 옥산장날순대 게시물 45개, 구와우순두부 게시물 43개<file_sep>/Final/tag/admin.py
from django.contrib import admin
from .models import Cafe, Art, Food, Theater, Escape, Travle
admin.site.register(Cafe)
admin.site.register(Art)
admin.site.register(Food)
admin.site.register(Theater)
admin.site.register(Escape)
admin.site.register(Travle)
# Register your models here.
<file_sep>/crawling/prac1.py
from urllib.request import urlopen, Request
from urllib.parse import quote_plus
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import warnings
from tqdm import tqdm
from selenium.webdriver.common.keys import Keys
import pandas as pd
warnings.filterwarnings(action='ignore')
SCROLL_PAUSE_TIME = 1.0 # 스크롤 내리는 시간
#===============================================================================================
# 크롬드라이버로 url 생성
baseUrl = "https://www.instagram.com/explore/tags/"
plusUrl = input('태그입력 : ')
url = baseUrl + quote_plus(plusUrl)
print('Chrome Driver 실행중...')
driver = webdriver.Chrome('C:\webdriver\chromedriver.exe')
driver.get(url)
time.sleep(3)
#==================================================================================================
# 자동로그인
login_section = '//*[@id="react-root"]/section/nav/div[2]/div/div/div[3]/div/span/a[1]/button'
driver.find_element_by_xpath(login_section).click()
time.sleep(2)
elem_login = driver.find_element_by_name("username")
elem_login.clear()
elem_login.send_keys('<PASSWORD>')
elem_login = driver.find_element_by_name('password')
elem_login.clear()
elem_login.send_keys('<PASSWORD>')
time.sleep(2)
xpath = """//*[@id="react-root"]/section/main/div/article/div/div[1]/div/form/div[4]/button"""
driver.find_element_by_xpath(xpath).click()
time.sleep(2)
#==================================================================================================
# 총 게시물 숫자 불러오기
pageString = driver.page_source
bsObj = BeautifulSoup(pageString, 'lxml')
temp_data = bsObj.find_all(name='meta')[-1]
temp_data = str(temp_data)
start = temp_data.find('게시물') + 4
end = temp_data.find('개')
total_post_data = temp_data[start:end]
print("총 {0}개의 게시물이 검색되었습니다.".format(total_post_data))
print('태그를 수집하는 중입니다...')
#==================================================================================================
reallink = [] # 전체 게시물 링크 저장
# url 화면에서 스크롤을 내리면서 게시물 크롤링
while True:
pageString = driver.page_source
bsObj = BeautifulSoup(pageString, 'lxml')
for link1 in bsObj.find_all(name='div', attrs={"class":"Nnq7C weEfm"}):
for i in range(3):
title = link1.select('a')[i]
real = title.attrs['href']
reallink.append(real)
last_scroll = driver.execute_script('return document.body.scrollHeight')
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(SCROLL_PAUSE_TIME)
new_scroll = driver.execute_script("return document.body.scrollHeight")
if new_scroll == last_scroll:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(SCROLL_PAUSE_TIME)
new_scroll = driver.execute_script("return document.body.scrollHeight")
# 현재 게시물이 마지막 게시물일 때 break
if new_scroll == last_scroll:
break
else:
last_scroll = new_scroll
continue
time.sleep(2)
total_tag_data = len(reallink) # 전체 데이터의 크기 저장
print('총 {0}개의 태그를 수집합니다.'.format(total_tag_data))
csvtext = []
#==================================================================================================
# 프로그램 실시간 진행률을 알기 위한 tqdm 라이브러리 사용
for i in tqdm(range(total_tag_data)):
csvtext.append([])
req = Request("https://www.instagram.com/p"+reallink[i], headers={'User-Agent': 'Mozila/5.0'})
webpage = urlopen(req).read()
soup = BeautifulSoup(webpage, 'lxml', from_encoding='utf-8')
soup1 = soup.find('meta', attrs={'property':"og:description"})
reallink1 = soup1['content']
reallink1 = reallink1[reallink1.find("@") + 1:reallink1.find(")")]
reallink1 = reallink1[:20]
if reallink1 == '':
reallink1 = "Null"
csvtext[i].append(reallink1)
for reallink2 in soup.find_all('meta', attrs={'property':"instapp:hashtags"}):
hashtags = reallink2['content'].rstrip(',')
csvtext[i].append(hashtags)
# 데이터를 csv파일로 저장
data = pd.DataFrame(csvtext)
data.to_csv('tagdata.txt', encoding='utf-8')
#==================================================================================================
driver.close() # Chrome Driver 종료
#############################################################
# 검색어 : 옥산장날순대 게시물 45개, 구와우순두부 게시물 43개
<file_sep>/Final/tag/views.py
from django.shortcuts import render, get_object_or_404, redirect
from .models import Cafe, Art, Food, Theater, Escape, Travle
def tag(request):
return render(request, 'tag.html')
def cafe(request):
cafes = Cafe.objects # 쿼리셋 # 메소드
return render(request, 'cafe.html', {'cafes': cafes})
def cdetail(request, cafe_id):
cafe_detail = get_object_or_404(Cafe, pk=cafe_id)
return render(request, 'cdetail.html', {'cafe': cafe_detail})
def art(request):
arts = Art.objects # 쿼리셋 # 메소드
return render(request, 'art.html', {'arts': arts})
def artdetail(request, art_id):
art_detail = get_object_or_404(Art, pk=art_id)
return render(request, 'artdetail.html', {'art': art_detail})
def food(request):
foods = Food.objects
return render(request, 'food.html', {'foods': foods})
def fooddetail(request, food_id):
food_detail = get_object_or_404(Food, pk=food_id)
return render(request, 'fooddetail.html', {'food': food_detail})
def theater(request):
theaters = Theater.objects
return render(request, 'theater.html', {'theaters': theaters})
def theaterdetail(request, theater_id):
theater_detail = get_object_or_404(Theater, pk=theater_id)
return render(request, 'theaterdetail.html', {'theater': theater_detail})
def escape(request):
escapes = Escape.objects
return render(request, 'escape.html', {'escapes': escapes})
def escapedetail(request, escape_id):
escape_detail = get_object_or_404(Escape, pk=escape_id)
return render(request, 'escapedetail.html', {'escape': escape_detail})
def travle(request):
travles = Travle.objects
return render(request, 'travle.html', {'travles': travles})
def travledetail(request, travle_id):
travle_detail = get_object_or_404(Travle, pk=travle_id)
return render(request, 'travledetail.html', {'travle': travle_detail})
# Create your views here.<file_sep>/Final/document/models.py
from django.db import models
from django.contrib.auth.models import User
class Document(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
title = models.CharField(max_length=50)
text = models.TextField()
class Comment(models.Model):
document = models.ForeignKey(Document, on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='comments')
text = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
like = models.IntegerField(default=0)
dislike = models.IntegerField(default=0)
def __str__(self):
return (self.author.username if self.author else "무명")+ "의 댓글"
# Create your models here.
<file_sep>/Web/recommend/models.py
from django.db import models
from django.contrib.auth.models import User
class Like(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
division = models.CharField(max_length=100)
rating = models.CharField(max_length=10, null=True, blank=True)
address = models.CharField(max_length=200)
call = models.CharField(max_length=100)
park = models.CharField(max_length=50)
hours = models.CharField(max_length=50)
price = models.TextField(max_length=200)
context = models.TextField(max_length=500, null=True, blank=True)
image_one = models.ImageField(upload_to="images/recommend/%Y/%m/%d", blank=True, null=True)
image_two = models.ImageField(upload_to="images/recommend/%Y/%m/%d", blank=True, null=True)
image_three = models.ImageField(upload_to="images/recommend/%Y/%m/%d", blank=True, null=True)
image_four = models.ImageField(upload_to="images/recommend/%Y/%m/%d", blank=True, null=True)
image_five = models.ImageField(upload_to="images/recommend/%Y/%m/%d", blank=True, null=True)
maps = models.ImageField(upload_to="images/maps/%Y/%m/%d", blank=True, null=True)
pub_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def summary(self):
return self.context[:200]
class Recommend(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
division = models.CharField(max_length=100)
rating = models.CharField(max_length=10, null=True, blank=True)
address = models.CharField(max_length=200)
call = models.CharField(max_length=100)
park = models.CharField(max_length=50)
hours = models.CharField(max_length=50)
price = models.TextField(max_length=200)
context = models.TextField(max_length=500, null=True, blank=True)
image_one = models.ImageField(upload_to="images/recommend/%Y/%m/%d", blank=True, null=True)
image_two = models.ImageField(upload_to="images/recommend/%Y/%m/%d", blank=True, null=True)
image_three = models.ImageField(upload_to="images/recommend/%Y/%m/%d", blank=True, null=True)
image_four = models.ImageField(upload_to="images/recommend/%Y/%m/%d", blank=True, null=True)
image_five = models.ImageField(upload_to="images/recommend/%Y/%m/%d", blank=True, null=True)
maps = models.ImageField(upload_to="images/maps/%Y/%m/%d", blank=True, null=True)
pub_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def summary(self):
return self.context[:200]
class Editor(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
division = models.CharField(max_length=100)
rating = models.CharField(max_length=10, null=True, blank=True)
address = models.CharField(max_length=200)
call = models.CharField(max_length=100)
park = models.CharField(max_length=50)
hours = models.CharField(max_length=50)
price = models.TextField(max_length=200)
context = models.TextField(max_length=500, null=True, blank=True)
image_one = models.ImageField(upload_to="images/recommend/%Y/%m/%d", blank=True, null=True)
image_two = models.ImageField(upload_to="images/recommend/%Y/%m/%d", blank=True, null=True)
image_three = models.ImageField(upload_to="images/recommend/%Y/%m/%d", blank=True, null=True)
image_four = models.ImageField(upload_to="images/recommend/%Y/%m/%d", blank=True, null=True)
image_five = models.ImageField(upload_to="images/recommend/%Y/%m/%d", blank=True, null=True)
maps = models.ImageField(upload_to="images/maps/%Y/%m/%d", blank=True, null=True)
pub_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def summary(self):
return self.context[:200]
class Area(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
division = models.CharField(max_length=100)
rating = models.CharField(max_length=10, null=True, blank=True)
address = models.CharField(max_length=200)
call = models.CharField(max_length=100)
park = models.CharField(max_length=50)
hours = models.CharField(max_length=50)
price = models.TextField(max_length=200)
context = models.TextField(max_length=500, null=True, blank=True)
image_one = models.ImageField(upload_to="images/recommend/%Y/%m/%d", blank=True, null=True)
image_two = models.ImageField(upload_to="images/recommend/%Y/%m/%d", blank=True, null=True)
image_three = models.ImageField(upload_to="images/recommend/%Y/%m/%d", blank=True, null=True)
image_four = models.ImageField(upload_to="images/recommend/%Y/%m/%d", blank=True, null=True)
image_five = models.ImageField(upload_to="images/recommend/%Y/%m/%d", blank=True, null=True)
maps = models.ImageField(upload_to="images/maps/%Y/%m/%d", blank=True, null=True)
pub_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def summary(self):
return self.context[:200]
# Area-Model
class Seoul(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
division = models.CharField(max_length=100)
rating = models.CharField(max_length=10, null=True, blank=True)
address = models.CharField(max_length=200)
call = models.CharField(max_length=100)
park = models.CharField(max_length=50)
hours = models.CharField(max_length=50)
price = models.TextField(max_length=200)
context = models.TextField(max_length=500, null=True, blank=True)
image_one = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
image_two = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
image_three = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
image_four = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
image_five = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
maps = models.ImageField(upload_to="images/maps/%Y/%m/%d", blank=True, null=True)
pub_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def summary(self):
return self.context[:100]
class Incheon(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
division = models.CharField(max_length=100)
rating = models.CharField(max_length=10, null=True, blank=True)
address = models.CharField(max_length=200)
call = models.CharField(max_length=100)
park = models.CharField(max_length=50)
hours = models.CharField(max_length=50)
price = models.TextField(max_length=200)
context = models.TextField(max_length=500, null=True, blank=True)
image_one = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
image_two = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
image_three = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
image_four = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
image_five = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
maps = models.ImageField(upload_to="images/maps/%Y/%m/%d", blank=True, null=True)
pub_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def summary(self):
return self.context[:100]
class Busan(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
division = models.CharField(max_length=100)
rating = models.CharField(max_length=10, null=True, blank=True)
address = models.CharField(max_length=200)
call = models.CharField(max_length=100)
park = models.CharField(max_length=50)
hours = models.CharField(max_length=50)
price = models.TextField(max_length=200)
context = models.TextField(max_length=500, null=True, blank=True)
image_one = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
image_two = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
image_three = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
image_four = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
image_five = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
maps = models.ImageField(upload_to="images/maps/%Y/%m/%d", blank=True, null=True)
pub_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def summary(self):
return self.context[:100]
class Gwanggu(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
division = models.CharField(max_length=100)
rating = models.CharField(max_length=10, null=True, blank=True)
address = models.CharField(max_length=200)
call = models.CharField(max_length=100)
park = models.CharField(max_length=50)
hours = models.CharField(max_length=50)
price = models.TextField(max_length=200)
context = models.TextField(max_length=500, null=True, blank=True)
image_one = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
image_two = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
image_three = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
image_four = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
image_five = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
maps = models.ImageField(upload_to="images/maps/%Y/%m/%d", blank=True, null=True)
pub_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def summary(self):
return self.context[:100]
class Daejon(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
division = models.CharField(max_length=100)
rating = models.CharField(max_length=10, null=True, blank=True)
address = models.CharField(max_length=200)
call = models.CharField(max_length=100)
park = models.CharField(max_length=50)
hours = models.CharField(max_length=50)
price = models.TextField(max_length=200)
context = models.TextField(max_length=500, null=True, blank=True)
image_one = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
image_two = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
image_three = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
image_four = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
image_five = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
maps = models.ImageField(upload_to="images/maps/%Y/%m/%d", blank=True, null=True)
pub_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def summary(self):
return self.context[:100]
class Gangwon(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
division = models.CharField(max_length=100)
rating = models.CharField(max_length=10, null=True, blank=True)
address = models.CharField(max_length=200)
call = models.CharField(max_length=100)
park = models.CharField(max_length=50)
hours = models.CharField(max_length=50)
price = models.TextField(max_length=200)
context = models.TextField(max_length=500, null=True, blank=True)
image_one = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
image_two = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
image_three = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
image_four = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
image_five = models.ImageField(upload_to="images/area/%Y/%m/%d", blank=True, null=True)
maps = models.ImageField(upload_to="images/maps/%Y/%m/%d", blank=True, null=True)
pub_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def summary(self):
return self.context[:100]
# Create your models here.
<file_sep>/Web/document/urls.py
from django.contrib import admin
from django.urls import path
from . import views
app_name = 'document'
urlpatterns = [
path('', views.document, name='document'),
path('document/<int:document_id>', views.document_detail, name="document_detail"),
]<file_sep>/Final/blog/migrations/0003_likecomment.py
# Generated by Django 2.2 on 2020-08-23 06:25
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('blog', '0002_beditor_maps'),
]
operations = [
migrations.CreateModel(
name='LikeComment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('text', models.TextField()),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('like', models.IntegerField(default=0)),
('dislike', models.IntegerField(default=0)),
('author', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='like_comments', to=settings.AUTH_USER_MODEL)),
('blike', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='like_comments', to='blog.Blike')),
],
),
]
<file_sep>/etc/README.md
PRSProject 초기 제작시에 연습을 위해서 만들었던 프로젝트들을 모아두는 장소<file_sep>/Visualization/wordcloud1.py
# import 에러로 보류
#####################
import matplotlib.pyplot as plt
from wordcloud import WordCloud
font_path = 'c:\\windows\\fonts\\NanumGothic.ttf'
wordcloud = WordCloud(font_path = font_path, width = 800, height = 800)
text=open('tagdata.txt').read()
wordcloud = wordcloud.generate(text)
fig = plt.figure(figsize=(12,12))
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
fig.savefig('wordcloud_without_axisoff.png')
<file_sep>/Web/tag/urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('tag', views.tag, name="tag"),
path('cafe', views.cafe, name="cafe"),
path('cafe/<int:cafe_id>', views.cdetail, name="cdetail"),
path('art', views.art, name="art"),
path('art/<int:art_id>', views.artdetail, name="artdetail"),
path('food', views.food, name="food"),
path('food/<int:food_id>', views.fooddetail, name="fooddetail"),
path('theater', views.theater, name="theater"),
path('theater/<int:theater_id>', views.theaterdetail, name="theaterdetail"),
path('escape', views.escape, name="escape"),
path('escape/<int:escape_id>', views.escapedetail, name="escapedetail"),
path('travle', views.travle, name="travle"),
path('travle/<int:travle_id>', views.travledetail, name="travledetail"),
]
|
73fb94a0874bf92bb63d645b5b59172f6eaa1602
|
[
"Markdown",
"Python",
"HTML"
] | 34
|
Python
|
Sefact/PRSproject
|
f294eb65b2ee4462f3c8fcb8764bde523a314fb2
|
2d1a341286d5da80290ff48df2d3d4b385e48ffd
|
refs/heads/master
|
<repo_name>Catherinegichina/codeHive-Registration-App<file_sep>/app/src/main/java/com/example/registration/viewmodel/UserViewModel.kt
package com.example.registration.viewmodel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.registration.Models.RegistrationRequest
import com.example.registration.Models.RegistrationResponse
import com.example.registration.repository.UserRepository
import kotlinx.coroutines.launch
class UserViewModel: ViewModel() {
var registrationLiveData = MutableLiveData<RegistrationResponse>()
// the response is passed on this var.
var registrationFailedLiveData=MutableLiveData<String>()
// var r.failed is an instance of mutablelivedata.live data-observable object.
// pass the response tthe r.live data,update the ui concerning the data received from the repository.
// its an observable object.when we receive a response,we will be able to update te ui.
// 3. instance of our repository.
var userRepository=UserRepository()
// line 19-makes the network call n return a response.
// 4.call from the userviewmodel.
fun registerUser(registrationRequest: RegistrationRequest){
// makes the registratio request.
viewModelScope.launch {
var response= userRepository.registerStudent(registrationRequest)
if(response.isSuccessful){
registrationLiveData.postValue(response.body())
}
else{
registrationFailedLiveData.postValue(response.errorBody()?.string())
}
}
}
}<file_sep>/app/src/main/java/com/example/registration/LoginActivity.kt
package com.example.registration
import android.content.Context
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.activity.viewModels
import com.example.registration.Models.LoginRequest
import com.example.registration.databinding.ActivityLoginBinding
import com.example.registration.viewmodel.LoginViewModel
class LoginActivity : AppCompatActivity() {
lateinit var binding:ActivityLoginBinding
lateinit var sharedPreferences:SharedPreferences
val loginViewModel:LoginViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding= ActivityLoginBinding.inflate(layoutInflater)
setContentView(binding.root)
sharedPreferences=getSharedPreferences("CODEHIVE_REG_PREF", Context.MODE_PRIVATE)
binding.btnlogin.setOnClickListener{
var email=binding.etemail.text.toString()
if(email.isEmpty()){
binding.etemail.setError("Email Required")
}
var password=binding.etpassword.text.toString()
if (password.isEmpty()){
binding.etemail.setError("password required")
}
var loginRequest=LoginRequest(
email=email,
password = <PASSWORD>
)
loginViewModel.login(loginRequest)
}
}
override fun onResume(){
super.onResume()
loginViewModel.loginLiveData.observe(this,{loginResponse ->
Toast.makeText(baseContext,loginResponse.message,Toast.LENGTH_LONG).show()
var accessToken=loginResponse.accessToken
sharedPreferences.edit().putString("ACCESS TOKEN",accessToken).apply()
var x=sharedPreferences.getString("ACCESS TOKEN","")
})
loginViewModel.loginFailedLiveData.observe(this,{
error ->
Toast.makeText(baseContext,error,Toast.LENGTH_LONG).show()
})
}
}<file_sep>/app/src/main/java/com/example/registration/ui/CoursesDetailsActivity.kt
package com.example.registration.ui
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.registration.R
class CoursesDetailsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_courses_details)
}
}<file_sep>/app/src/main/java/com/example/registration/Course.kt
package com.example.registration
data class Course(var courseCode:String,
var courseName:String,
var description:String,
var instructor:String)
//what the courses entails and we get to store them in a variable.
//attributes of our course-reason we use the data class.
//next,we create attribute of each course-i res folder.
<file_sep>/app/src/main/java/com/example/registration/ui/CoursesAdapter.kt
package com.example.registration
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class CoursesAdapter(var courseList:List<Course>): RecyclerView.Adapter<CoursesViewHolder>() {
// list<course>-takes in a list of type course.
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CoursesViewHolder {
var itemView= LayoutInflater.from(parent.context)
.inflate(R.layout.course_list_item,parent,false)
return CoursesViewHolder(itemView)
// we have created our adapter next,bind the adapter to the reccyler view.
}
override fun onBindViewHolder(holder: CoursesViewHolder, position: Int) {
// gets the item at the current position.
// displays details we want to display our details in.-viewholder.
// TAKES DATA FROM OUR LIST AND DISPLAYS IT.GOES THROUGH IT ONE BY ONE.
// pick the view,a
var currentCourse=courseList.get(position)
holder.tvcourseName.text=currentCourse.courseName
holder.tvdescription.text=currentCourse.description
holder.tvinstructor.text=currentCourse.instructor
holder.tvcoursecode.text=currentCourse.courseCode
// .text-gets the value stored in the text edit
}
override fun getItemCount(): Int {
return courseList.size
}
// we will pass a list of courses to that adapter.
// 3 methods the adapter need(control and i)
// getting size of ur list
}
class CoursesViewHolder(itemView: View):RecyclerView.ViewHolder(itemView){
// what we get to see
var tvcourseName=itemView.findViewById<TextView>(R.id.tvcoursename)
var tvdescription=itemView.findViewById<TextView>(R.id.tvdescription)
var tvinstructor=itemView.findViewById<TextView>(R.id.tvinstructor)
var tvcoursecode=itemView.findViewById<TextView>(R.id.tvcoursecode)
// R.id.tvcoursecode is a way we have labeled the tvcoursecode.
}
//ALLOWS US TO ACCESS INDIVIDULA RTEXT VIEWS
//takes an item view as a parameter
//inherits from recyclerview.then we pass it to view holder and pass it to the parent class
//Adapter has 2 classes:view holder and adapter......viewholder||adapter||recycler view.<file_sep>/app/src/main/java/com/example/registration/CourseResponse.kt
package com.example.registration
import com.google.gson.annotations.SerializedName
data class CourseResponse(
@SerializedName("date_created") var date_created :String,
@SerializedName("date_updated") var date_updated :String,
@SerializedName("created_by") var created_by:String,
@SerializedName("updated_by") var updated_by:String,
var active :Boolean,
@SerializedName("course_id") var course_id:String,
@SerializedName("course_name") var course_name:String,
@SerializedName("course_code") var course_code:String,
var description:String,
var instructor:String,
)
<file_sep>/app/src/main/java/com/example/registration/coursesactivity.kt
package com.example.registration
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class coursesactivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_coursesactivity)
var rvCourses=findViewById<RecyclerView>(R.id.rvcourses)
var courseList= listOf(
Course("hhh06","Kotlin","introduction","john"),
Course("HFF88","backend","introduction","mwai"),
Course("jjj44","backend","intro","purity"),
// dont forget the comma after the bracket.
)
var coursesAdapter=CoursesAdapter(courseList)
rvCourses.layoutManager=LinearLayoutManager(baseContext)
rvCourses.adapter=coursesAdapter
// if horizontally,or gid-manager
// coursesList-what we have inputed.
// here we are creating our adapter.
}
}
//viewholder-multiple text views.
//Create a contacts app:list of contacts(in a recycler view)-name,number,email(recyclerview/cardview)<file_sep>/app/src/main/java/com/example/registration/ui/MainActivity.kt
package com.example.registration.ui
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.*
import androidx.activity.viewModels
import com.example.registration.API.ApiClient
import com.example.registration.API.ApiInterface
import com.example.registration.Models.RegistrationRequest
import com.example.registration.Models.RegistrationResponse
import com.example.registration.R
import com.example.registration.databinding.ActivityMainBinding
import com.example.registration.viewmodel.UserViewModel
import org.json.JSONObject
import retrofit2.Callback
import retrofit2.Response
class MainActivity : AppCompatActivity() {
// lateinit var etName: EditText
// lateinit var etDob: EditText
// lateinit var etPassword: EditText
// lateinit var etEmail: EditText
// lateinit var etPhoneNumber: EditText
// lateinit var btnRegister: Button
// lateinit var spNationality: Spinner
lateinit var binding:ActivityMainBinding
val userViewModel: UserViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding= ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
// castViews()
// clickRegister()
}
override fun onResume(){
super.onResume()
binding.btnRegisterLbl.setOnClickListener{
var registrationRequest=RegistrationRequest(
name=binding.tvname.text.toString(),
phoneNumber = binding.etPhoneNumber.text.toString(),
email = binding.tvemail.text.toString(),
dateOfBirth = binding.etdOB.text.toString(),
password =<PASSWORD>(),
nationality = binding.spNationality.selectedItem.toString(),
// name=binding.etName.text.toString()
// nationality=binding.spNationality.selectedItem.toString(),
)
userViewModel.registerUser(registrationRequest)
}
userViewModel.registrationLiveData.observe(this,{registrationResponse->
if(!registrationResponse.studentId.isNullOrEmpty()){
Toast.makeText(baseContext,"Registration successful",Toast.LENGTH_LONG).show()
}
})
userViewModel.registrationFailedLiveData.observe(this,{ error ->
Toast.makeText(baseContext, error,Toast.LENGTH_LONG).show()
})
}}
data class ApiError(var errors:List<String>)
//ERROR:LINE 57
// fun castViews() {
// etName = findViewById(R.id.etName)
// etDob = findViewById(R.id.etDob)
// etPhoneNumber = findViewById(R.id.etPhoneNumber)
// etEmail = findViewById(R.id.etEmail)
// etPassword = findViewById(R.id.etPassword)
// btnRegister = findViewById(R.id.btnRegisterLbl)
// spNationality = findViewById(R.id.spNationality)
// val nationalities = arrayOf("KENYAN", "RWANDAN", "SOUTH SUDAN", "UGANDAN")
// var adapter =
// ArrayAdapter<String>(baseContext, android.R.layout.simple_spinner_item, nationalities)
// adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
// spNationality.adapter = adapter
// }
//
// fun clickRegister() {
// var error = false
// btnRegister.setOnClickListener {
// var name = etName.text.toString() //validation
// if (name.isEmpty()) {
// error = true
// etName.setError("Name is required")
// }
// var dob = etDob.text.toString()
// if (dob.isEmpty()) {
// error = true
// etDob.setError("Dob is required")
// }
// var nationality = spNationality.selectedItem.toString()
//
// var password = etPassword.text.toString()
// if (password.isEmpty()) {
// error = true
// etPassword.setError("Password required")
// }
// var email = etEmail.text.toString()
// if (email.isEmpty()) {
// error = true
// etEmail.setError("Email required")
// }
// var phoneNumber = etPhoneNumber.text.toString()
// if (phoneNumber.isEmpty()) {
// error = true
// etPhoneNumber.setError("PhoneNumber required")
// }
//
// var registrationRequest = RegistrationRequest(
// name = name,
// phoneNumber = phoneNumber,
// email = email,
// nationality = nationality,
// dateOfBirth = dob,
// password = <PASSWORD>
// )
//
// var retrofit = ApiClient.buildApiClient(ApiInterface::class.java)
// var request = retrofit.registerStudent(registrationRequest)
// request.enqueue(object : Callback<RegistrationResponse?> {
// override fun onResponse(
// call: retrofit2.Call<RegistrationResponse?>,
// response: Response<RegistrationResponse?>
// ) {
// if (response.isSuccessful) {
//// var posts = response.body()
// Toast.makeText(
// baseContext,
// "Registration Successful",
// Toast.LENGTH_LONG
// ).show()
// var intent = Intent(baseContext, LoginActivity::class.java)
// startActivity(intent)
//
// } else {
// try {
// val error = JSONObject(response.errorBody()!!.string())
// Toast.makeText(baseContext, error.toString(), Toast.LENGTH_LONG)
// .show()
// } catch (e: Exception) {
// Toast.makeText(baseContext, e.message, Toast.LENGTH_LONG).show()
// }
// }
// }
//
// override fun onFailure(
// call: retrofit2.Call<RegistrationResponse?>,
// t: Throwable
// ) {
// Toast.makeText(baseContext, t.message, Toast.LENGTH_LONG).show()
// }
// })
// }
// data class ApiError(var errors: List<String>)
//
// }
//}<file_sep>/app/src/main/java/com/example/registration/ui/SessionManger.kt
package com.example.registration.ui
import android.content.Context
import android.content.SharedPreferences
class SessionManger {
var sharedPreferences: SharedPreferences =context.getSharedPreferences("CODE_HIVE_PREFS",
Context.MODE_PRIVATE)
fun saveAccToken(token:String){
sharedPreferences.edit().putString("ACCESS_TOKEN",token).apply()
}
fun fetchAccToken():String?{
return sharedPreferences.getString("ACCESS_TOKEN","")
}
}<file_sep>/app/src/main/java/com/example/registration/ui/LoginActivity.kt
package com.example.registration.ui
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.example.registration.API.ApiClient
import com.example.registration.API.ApiInterface
import com.example.registration.Models.LoginRequest
import com.example.registration.Models.LoginResponse
import com.example.registration.R
import com.example.registration.coursesactivity
import com.example.registration.databinding.ActivityLoginBinding
import com.example.registration.viewmodel.LoginViewModel
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
//class LoginActivity : AppCompatActivity() {
// lateinit var etLogInEmail: EditText
// lateinit var etLogInPassword: EditText
//edits.
// lateinit var btLogInButton: Button
// lateinit var binding:ActivityLoginBinding
//
// override fun onCreate(savedInstanceState: Bundle?) {
// super.onCreate(savedInstanceState)
// setContentView(R.layout.activity_login)
// castViews()
// userLogIn()
// }
//
// fun castViews() {
// etLogInEmail = findViewById(R.id.etLogInEmail)
// etLogInPassword = findViewById(R.id.etLogInPassword)
// btLogInButton = findViewById(R.id.btnLogInButton)
// }
//
// fun userLogIn() {
// btLogInButton.setOnClickListener {
// var email = etLogInEmail.text.toString()
// if (email.isEmpty()) {
// etLogInEmail.setError("Email required")
// }
// var password = etLogInPassword.text.toString()
// if (password.isEmpty()) {
// etLogInPassword.setError("Password required")
// }
//
// var logInRequest = LoginRequest(
// email = email,
// password = <PASSWORD>
// )
//
//
// var retrofit = ApiClient.buildApiClient(ApiInterface::class.java)
//// var request = retrofit.loginStudent(logInRequest)
//// request.enqueue(object : Callback<LoginResponse>{
// override fun onResponse(
// call: Call<LoginResponse>,
// response: Response<LoginResponse>
// ) {
// TODO("Not yet implemented")
// }
//
// override fun onFailure(call: Call<LoginResponse>, t: Throwable) {
// TODO("Not yet implemented")
// }
// })
//
//// request.enqueue(object : Callback<LoginRequest> {
// override fun onResponse(
// call: retrofit2.Call<LoginRequest>, response: Response<LoginRequest>
// ) {
// if (response.isSuccessful) {
// Toast.makeText(baseContext, "Login Successful", Toast.LENGTH_LONG)
// .show()
// var intent = Intent(baseContext, coursesactivity::class.java)
// startActivity(intent)
// } else {
// try {
// val error = JSONObject(response.errorBody()!!.string())
// Toast.makeText(baseContext, error.toString(), Toast.LENGTH_LONG)
// .show()
// } catch (e: Exception) {
// Toast.makeText(baseContext, e.message, Toast.LENGTH_LONG).show()
// }
// }
//
// }
//
// override fun onFailure(call: retrofit2.Call<LoginRequest>, t: Throwable) {
// Toast.makeText(baseContext, t.message, Toast.LENGTH_LONG).show()
// }
// })
// }
// }
//}
//
<file_sep>/app/src/main/java/com/example/registration/API/ApiInterface.kt
package com.example.registration.API
import com.example.registration.Models.LoginRequest
import com.example.registration.Models.LoginResponse
import com.example.registration.Models.RegistrationRequest
import com.example.registration.Models.RegistrationResponse
import retrofit2.Call
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.POST
interface ApiInterface {
@POST("/students/register")
suspend fun registerStudent(@Body registrationRequest: RegistrationRequest):Response<RegistrationResponse>
@POST("/students/login")
suspend fun loginStudent(@Body loginRequest: LoginRequest):Call<LoginResponse>
suspend fun login(@Body loginRequest: LoginRequest):Response<LoginResponse>
}
|
8b9dc238927944a3e0579729c581fe9e3c8902ca
|
[
"Kotlin"
] | 11
|
Kotlin
|
Catherinegichina/codeHive-Registration-App
|
0cf39da7432a5d9a8ac76e74fc773489af90e05f
|
813038eabd1ee366425abe4e7074273c8aa8e458
|
refs/heads/master
|
<repo_name>liusiying65200/Angular4.0<file_sep>/admin/Admin/Home/Controller/CommonController.class.php
<?php
namespace Home\Controller;
use Think\Controller;
Class CommonController extends Controller{
Public function _initialize()
{
$this->assign('Admin_title','后台管理系统 v1.0');
if (!isset($_SESSION['aid'])){
// if(session('?Admin_User')){
// $this->assign('Admin_User',session('Admin_User'));
// $this->assign('Admin_Uid',session('Admin_Uid'));
// }else{
$this->redirect('Home/Administrator/login');
//}
}
}
/**
* ajax分页及分页数据
* @param $model 数据库表名
* @param $where 条件
* @param $order 排序
* @param $listRows='' 每页显示行数
* @return array
*/
public function getPageInfo($model,$where,$order,$listRows,$link){
$total=M($model)->where($where)->count();
$pageobj=new \Common\PageAjax($total,$listRows,$link);
$pageobj->rollPage='5';
$pageobj->clickfunc='load_table';
$list=M($model)->where($where)->order($order)->limit(($pageobj->nowPage-1)*$listRows,$listRows)->select();
if(!$list){
$list=M($model)->where($where)->order($order)->limit(($pageobj->nowPage-2)*$listRows,$listRows)->select();
}
$this->assign('showPageHtml',$pageobj->show());
$this->assign('curPage',$pageobj->nowPage);
return $list;
}
}<file_sep>/ci/app/language/zh-cn/operate_lang.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$lang['add_ok'] = '添加成功';
$lang['add_fail'] = '添加失败';
$lang['edit_ok'] = '修改成功';
$lang['edit_fail'] = '修改失败';
$lang['open'] = '激活成功';
$lang['close'] = '禁用成功';
$lang['login_is_out'] = '登陆过期,请重新登陆';
$lang['password_error'] = '密码错误';
$lang['password_empty'] = '密码为空';
$lang['username_empty'] = '用户名为空';
$lang['username_not_exist'] = '用户名不存在';
$lang['not_file'] = '未上传文件';
$lang['file_ext_error'] = '文件格式不正确';
$lang['upload_ok'] = '文件格式不正确';
<file_sep>/admin/index.php
<?php
header("Content-type: text/html; charset=utf-8");
// 开启调试模建议开发阶段开部署阶段注释或者设为false
define('APP_DEBUG',True);
//↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓以下定义常常量必须大写字母
define("site_url","/");
define("JS_URL",site_url."/Public/JavaScript/");
//define("CSSCP_URL",site_url."caipiao/css/");
define("CSS_URL",site_url."Public/css/");
define("IMG_URL",site_url."Public/images/");
define("CZADMIN",site_url."Index.php/");
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑以上定义常
// 定义应用目录
define('APP_PATH','./Admin/');
// 引入ThinkPHP入口文件
require './ThinkPHP/ThinkPHP.php';
?><file_sep>/tp5/application/admin/controller/common.php
<?php
namespace app\admin\controller;
class Common extends \think\Controller {
public $userid=1;
public $roleid=1;
public function __construct() {
parent::__construct();
require_once APP_PATH.'init.php';
date_default_timezone_set('PRC');
}
/**
* 后台进入判断;
*/
final public function check_admin(){
//没有登录跳转到登录界面
if(!$_SESSION['userid']||!$_SESSION['roleid']) $this->go_to('public/login');
$this->userid=session('userid');
$this->roleid=session('roleid');
//检查访问权限
if(!in_array($this->url, $this->getAccessUrl())){
echo '<h1>Forbidden</h1>';
exit();
}
//得到菜单
$this->assign('menu', $this->getMenus());
//活跃菜单,根据菜单唯一标识实现高亮菜单
$this->assign('url', $this->url);
$this->assign('menu_id',$this->controller);
}
/**
* 得到每类角色所能访问的url地址
*/
final public function getAccessUrl(){
if(cache('accessUrl_'.$this->roleid)){
$access=cache('accessUrl_'.$this->roleid);
}else{
$this->updateAccessUrlCache($this->roleid);
$access=cache('accessUrl_'.$this->roleid);
}
return $access;
}
/**
* 更新每类角色所能访问的url地址到redis缓存
* @param $roleid 角色id
*/
public function updateAccessUrlCache($roleid){
$rules=M('role')->field('rules')->where('id='.$roleid)->find();
$auth_id='('.$rules['rules'].')';
$access_url=M('auth')->field('url')->where('id in '.$auth_id.' and status=1')->select();
$access=array();
for($i=0;$i<sizeof($access_url);$i++){
$size=sizeof(explode("/", $access_url[$i]['url']));
if($size==1)
$access[$i]=$access_url[$i]['url'].'/login/login';
if($size==2)
$access[$i]=$access_url[$i]['url'].'/login';
if($size==3)
$access[$i]=$access_url[$i]['url'];
}
cache('accessUrl_'.$roleid,$access);
}
/**
* 跳转到登录页面或跳转提示。注:和域名重定向有所不同,如果是ajax并不会跳转页面
*/
public function go_to($url){
if(IS_AJAX){
header("Content-Type:application/json");
echo json_encode(array('info'=>'登录过期,请重新登录','status'=>-1));exit();
}
header('Location:'.$url);
}
}<file_sep>/copy.js
/**
* Created by a1 on 2017/7/15.
*/
function copyToClipboard(maintext){
if (window.clipboardData){
window.clipboardData.setData("Text", maintext);
}else if (window.netscape){
try{
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
}catch(e){
alert("该浏览器不支持一键复制!n请手工复制文本框链接地址~");
}
var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
if (!clip) return;
var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
if (!trans) return;
trans.addDataFlavor('text/unicode');
var str = new Object();
var len = new Object();
var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
var copytext=maintext;
str.data=copytext;
trans.setTransferData("text/unicode",str,copytext.length*2);
var clipid=Components.interfaces.nsIClipboard;
if (!clip) return false;
clip.setData(trans,null,clipid.kGlobalClipboard);
}
alert("以下内容已经复制到剪贴板nn" + maintext);
}<file_sep>/tp5/thinkphp/library/think/Page.php
<?php
namespace think;
class Page{
private $total; //数据表中数据的总条数
private $listRows; //每页显示行数
private $limit;
private $uri;
private $pageNum; //页数
private $listNum=8; //列表数目 默认等于8
private $config=array("Header"=>"记录","Prev"=>"上一页","Next"=>"下一页","First"=>"首 页","Last"=>"尾 页");
public function __construct($total,$listRows=10){
$pages=$_GET['page'];
if ($pages==''){
$pages=1;
}
$this->total=$total;
$this->listRows=$listRows;
$this->uri=$this->getUri();
$this->page=!empty($pages) ? $pages:1 ;
$this->pageNum=ceil($this->total/$this->listRows);
$this->limit=$this->setLimit();
$this->ypages=$pages ."/". $this->pageNum;
}
private function setLimit(){
return "" . ($this->page - 1) * $this->listRows . ", {$this->listRows}";
}
//private function setLimit(){
//return "Limit " . ($this->page - 1) * $this->listRows . ", {$this->listRows}";
//}
private function getUri(){
$url=$_SERVER['REQUEST_URI'].(strpos($_SERVER['REQUEST_URI'],'?')?'':"?");
$parse=parse_url($url);
if(isset($parse["query"])){
parse_str($parse["query"],$params);
unset($params["page"]);
$url=$parse['path'].'?'.http_build_query($params);
}
return $url;
}
public function __get($args){
if ($args=="limit")
return $this->limit;
else
return null;
}
private function start(){
if ($this->total==0)
return 0;
else
return ($this->page-1)*$this->listRows+1;
}
private function end(){
return min($this->page*$this->listRows,$this->total);
}
private function First(){
if($this->page==1)
$html="<a href='#'>{$this->config["First"]}</a>";
else
$html="<a href='{$this->uri}&page=1'>{$this->config["First"]}</a>";
return $html;
}
private function Prev(){
if($this->page==1)
$html="<a href='#'>{$this->config["Prev"]}</a>";
else
$html="<a href='{$this->uri}&page=".($this->page-1)."'>{$this->config["Prev"]}</a>";
return $html;
}
private function pageList(){
$linkpage="";
$iunm=floor($this->listNum/2);
for($i=$iunm;$i>=1;$i--){
$page=$this->page-$i;
if($page<1)
continue;
$linkpage.="<a href='{$this->uri}&page={$page}'>{$page}</a>";
}
$linkpage.="<span class='current'>{$this->page}</span>";
for($i=1;$i<$iunm;$i++){
$page=$this->page+$i;
if($page<=$this->pageNum)
$linkpage.="<a href='{$this->uri}&page={$page}'>{$page}</a>";
else
break;
}
return $linkpage;
}
private function Next(){
if($this->page==$this->pageNum)
$html="<a href='#'>{$this->config["Next"]}</a>";
else
$html="<a href='{$this->uri}&page=".($this->page+1)."'>{$this->config["Next"]}</a>";
return $html;
}
private function Last(){
if($this->page==$this->pageNum)
$html="<a href='#'>{$this->config["Last"]}</a>";
else
$html="<a href='{$this->uri}&page=".($this->pageNum)."'>{$this->config["Last"]}</a>";
return $html;
}
private function Gopage(){
return '<input onkeyup="value=this.value.replace(/\D+/g,\'\')" type="text" onKeyDown="javascript:if(event.keyCode==13){var page=(this.value>'.$this->pageNum.')?'.$this->pageNum.':this.value;location=\''.$this->uri.'&page=\'+page+\'\'}" value="'.$this->page.'" style="width:25px"';
}
private function total(){
$html="<a href='#'>总记录: $this->total 条 页次: $this->ypages </a>";
return $html;
}
function paging(){
$html="<div class='pager'>";
$html.=$this->total();
$html.=$this->First();
$html.=$this->Prev();
$html.=$this->pageList();
$html.=$this->Next();
$html.=$this->Last();
$html.="</div>";
//$html.=$this->Gopage();//页面跳转
return $html;
}
}
?><file_sep>/dateTools/app/js/Controllers/SignUpController.js
/**
* Created by a1 on 2017/7/11.
*/
app.controller('SignUpController',['$scope',function ($scope) {
$scope.data=[1,3,5,36,474,75,7];
}])<file_sep>/tp5/application/admin/controller/index.php
<?php
namespace app\admin\controller;
class Index extends Common{
public function __construct()
{
parent::__construct();
}
public function index()
{
return view();
}
/**
* 菜单
*/
public function getMenu()
{
$rules=db('role')->field('rules')->where('id='.$this->roleid)->find();
$auth_id='('.$rules['rules'].')';
$list=db('auth')->where('id in '.$auth_id.' and category in (1,2) and status=1')->order('sort asc')->select();
$menus = list_to_tree($list);
echo json_encode($menus);
// if(cache('menu_'.$this->roleid)){
// $menus=cache('menu_'.$this->roleid);
// }else{
// $this->updateMenusCache($this->roleid);
// $menus=cache('menu_'.$this->roleid);
// }
// return $menus;
}
/**
* @param $roleid
*/
public function updateMenusCache($roleid){
$rules=db('role')->field('rules')->where('id='.$roleid)->find();
$auth_id='('.$rules['rules'].')';
$list=db('auth')->where('id in '.$auth_id.' and category in (1,2) and status=1')->order('sort asc')->select();
$menus = list_to_tree($list);
cache('menu_'.$roleid,$menus);
}
}
<file_sep>/ci/app/controllers/login.php
<?php
class Login extends MY_Controller {
function __construct()
{
parent::__construct();
$this->load->model('login_model');
}
/**
* ww 登陆
*/
function index()
{
//return_json($this->redis->del_all());
if($this->redis->get('times')>=MAX_ERROR_TIMES){
return_json('请一小时后重新登录');
}
if(!$data=$this->login_model->check('','login')){
return_json($this->login_model->getError);
}
$info=$this->login_model->get_userInfo();
if($info['password']!=$data['password']){
$this->redis->incr('times');
if($this->redis->get('times')==MAX_ERROR_TIMES){
$this->redis->expire('times',3600);
}
return_json('密码输入有误');
}
$this->redis->del('times');
$info['login_time']=$_SERVER['REQUEST_TIME'];//记录登陆的时间
$info['visit_time']=$_SERVER['REQUEST_TIME'];//记录最后访问的时间
unset($info['password']);
$token=$this->get_token($info);
return_json('登陆成功',['token'=>$token],1);
}
/**
* ww:用token保存用户信息并返回token
* @param $userInfo
* @return string
*/
function get_token($userInfo)
{
$this->load->helper('token');
$mr = explode('.', microtime(true));
$t = strval(substr($mr[0],3).$mr[1]);
$tokenStr = TOKEN_PRIVATE_ADMIN_KEY.$t.uniqid();
$token = token_encrypt($tokenStr,TOKEN_PRIVATE_ADMIN_KEY);//token密码
//redis记录用户信息的键值
$tokenKey='token:'.TOKEN_CODE_ADMIN.':'.$token;
//redis里用token_ID(基于用户id)记录token
$tokenIDKey='token_ID:'.TOKEN_CODE_ADMIN.':'.$userInfo['id'];
if($existToken=$this->redis->get($tokenIDKey))
{
$data=$this->redis->get('token:'.TOKEN_CODE_ADMIN.':'.$existToken);
$data['be_outed_time']=$_SERVER['REQUEST_TIME'];//有人登陆,记录被踢出的时间
$this->redis->set('token:'.TOKEN_CODE_ADMIN.':'.$existToken,$data,MAX_LIFE_TIME);
}
$this->redis->set($tokenKey,$userInfo,MAX_LIFE_TIME);
$this->redis->set($tokenIDKey,$token,MAX_LIFE_TIME);
return $token;
}
/**
* ww
*/
function logout()
{
if(!$this->admin){
return_json('参数异常');
}
$this->redis->del('token:'.TOKEN_CODE_ADMIN.':'.$this->token);
$this->redis->del('token_ID:'.TOKEN_CODE_ADMIN.':'.$this->admin['id']);
return_json('退出成功');
}
}<file_sep>/admin/Admin/Common/Controller/CommonController.class.php
<?php
namespace Common\Controller;
use Think\Controller;
class CommonController extends Controller{
public function _empty(){
$this->error('此操作无效');
}
}<file_sep>/tp5/application/admin/model/Cp.php
<?php
namespace app\index\model;
use think\Model;
class Cp extends Model
{
// 查询
public function selectcp($number)
{
parent::initialize();
//$user = User::all();
$cpone = Db::table('cp')->where('id',$number)->find();
//$caipiao = Cp::get($number);
return $cpone;
}
}<file_sep>/admin/Admin/Home/Controller/LogoutController.class.php
<?php
namespace Home\Controller;
use Think\Controller;
class LogoutController extends Controller {
public function index(){
session('Admin_User',null); // 删除session
$this->success('您已成功退出系统!!!',U('/Home/Login'));
}
}<file_sep>/ci/app/language/zh-cn/upload_lang.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$lang['upload_userfile_not_set'] = '未上传任何文件';
$lang['upload_file_exceeds_limit'] = '文件过大,建议压缩';
$lang['upload_file_exceeds_form_limit'] = 'The uploaded file exceeds the maximum size allowed by the submission form.';
$lang['upload_file_partial'] = 'The file was only partially uploaded.';
$lang['upload_no_temp_directory'] = 'The temporary folder is missing.';
$lang['upload_unable_to_write_file'] = '文件无法写入';
$lang['upload_stopped_by_extension'] = 'The file upload was stopped by extension.';
$lang['upload_no_file_selected'] = '未上传任何文件';
$lang['upload_invalid_filetype'] = '文件类型有误';
$lang['upload_invalid_filesize'] = '文件过大';
$lang['upload_invalid_dimensions'] = 'The image you are attempting to upload doesn\'t fit into the allowed dimensions.';
$lang['upload_destination_error'] = 'A problem was encountered while attempting to move the uploaded file to the final destination.';
$lang['upload_no_filepath'] = '保存地址异常';
$lang['upload_no_file_types'] = 'You have not specified any allowed file types.';
$lang['upload_bad_filename'] = '文件以存在';
$lang['upload_not_writable'] = '文件无法写入,请检查权限';
<file_sep>/ci/app/models/login_model.php
<?php
class login_model extends MY_Model
{
public $getError = '';
protected $pk='id';//当前表的主键
public function __construct()
{
parent::__construct();
$this->table = 'admin';
}
//规则
protected $rule = [
'username|用户名'=>'require|min:4|',
'password|密码'=>'require|min:4'
];
//消息提示
protected $message = [
'username.check_user_is_exists'=>'用户名不存在',
];
//验证规则扩展
protected $extend = [
'check_user_is_exists' => 'check_user_is_exists',//规则=>回调函数
];
//验证场景
protected $scene = [
'login' => ['username'=>'require|check_user_is_exists','password'],
];
//数据手动处理
protected function handle($data){
$data['password']=md5($data['password']);
return $data;
}
//通过用户名得到一行信息
function get_userInfo()
{
return $this->get_one('*',['username'=>get('username')]);
}
//检查用户名是否存在
function check_user_is_exists()
{
return $this->get_userInfo()?true:false;
}
}
<file_sep>/ocLazyLoad/pulic/homeCtroller.js
/**
* Created by a1 on 2017/7/13.
*/
app.controller('homeCtrl',['$scope','$controllerProvider','$compileProvider','$filterProvider',function ($scope,$controllerProvider,$compileProvider,$filterProvider) {
app.controller=$controllerProvider.register;
app.directive=$compileProvider.directive;
app.filter=$filterProvider.filter;
}])<file_sep>/admin/Admin/Home/Controller/ZiliaoController.class.php
<?php
namespace Home\Controller;
use Think\Controller;
use Common\Controller\AuthController;
use Think\Auth;
use Think\Db;
use OT\Database;
class ZiliaoController extends AuthController {
public function liuxiao(){
$Daoinfo= M("liuxiao");
$count =$Daoinfo->count();
$Page = new \Common\Page($count,20);
$show = $Page->paging();
$parent=$Daoinfo->where('id')->order("id DESC")->limit($Page->limit)->select();
$this->assign('list',$parent);
$this->assign('page',$show);// 赋值分页输出
$this->display();
}
public function liuxiao_add(){
$this->display();
}
public function liuxiao_runadd(){
if (!IS_AJAX){
$this->error('提交方式不正确',0,0);
}else{
$liuxiao=M('liuxiao');
$sldata=array(
'qihao'=>I('qihao'),
'liuxiao'=>I('liuxiao'),
'shaxiao'=>I('shaxiao'),
'jg'=>I('jg'),
'haoma'=>I('haoma'),
'que'=>I('que'),
'begtime'=>time(),
);
$liuxiao->field('qihao,liuxiao,shaxiao,jg,haoma,que,begtime')->add($sldata);
$this->success('添加成功',U('liuxiao'),1);
}
}
public function liuxiao_edit(){
$id=I('id');
$liuxiao=M('liuxiao')->where(array('id'=>$id))->find();
$this->assign('liuxiao',$liuxiao);
$this->display();
}
public function liuxiao_runedit(){
if (!IS_AJAX){
$this->error('提交方式不正确',0,0);
}else{
$liuxiao=M('liuxiao');
$sldata=array(
'id'=>I('id'),
'qihao'=>I('qihao'),
'liuxiao'=>I('liuxiao'),
'shaxiao'=>I('shaxiao'),
'jg'=>I('jg'),
'haoma'=>I('haoma'),
'que'=>I('que'),
);
M('liuxiao')->field('id,qihao,liuxiao,shaxiao,jg,haoma,que')->save($sldata);
$this->success('修改成功',U('liuxiao'),1);
}
}
public function tms(){
$Daoinfo= M("tms");
$count =$Daoinfo->count();
$Page = new \Common\Page($count,10);
$show = $Page->paging();
$parent=$Daoinfo->where('id')->order("id DESC")->limit($Page->limit)->select();
$this->assign('list',$parent);
$this->assign('page',$show);// 赋值分页输出
$this->display();
}
public function pt(){
$Daoinfo= M("pt");
$count =$Daoinfo->count();
$Page = new \Common\Page($count,20);
$show = $Page->paging();
$parent=$Daoinfo->where('id')->order("id DESC")->limit($Page->limit)->select();
$this->assign('list',$parent);
$this->assign('page',$show);// 赋值分页输出
$this->display();
}
public function pt_add(){
$this->display();
}
public function pt_runadd(){
if (!IS_AJAX){
$this->error('提交方式不正确',0,0);
}else{
$pt=M('pt');
$sldata=array(
'qihao'=>I('qihao'),
'pt'=>I('pt'),
'jg'=>I('jg'),
'begtime'=>time(),
);
$pt->field('qihao,pt,jg,begtime')->add($sldata);
$this->success('添加成功',U('pt'),1);
}
}
public function pt_edit(){
$id=I('id');
$pt=M('pt')->where(array('id'=>$id))->find();
$this->assign('pt',$pt);
$this->display();
}
public function pt_runedit(){
if (!IS_AJAX){
$this->error('提交方式不正确',0,0);
}else{
$pt=M('pt');
$sldata=array(
'id'=>I('id'),
'qihao'=>I('qihao'),
'pt'=>I('pt'),
'jg'=>I('jg'),
);
M('pt')->field('id,qihao,pt,jg')->save($sldata);
$this->success('修改成功',U('pt'),1);
}
}
public function tms_add(){
$this->display();
}
public function tms_runadd(){
if (!IS_AJAX){
$this->error('提交方式不正确',0,0);
}else{
$tms=M('tms');
$sldata=array(
'qihao'=>I('qihao'),
'temashi'=>I('temashi'),
'tema'=>I('tema'),
'jieshi'=>I('jieshi'),
'bose'=>I('bose'),
'shengxiao'=>I('shengxiao'),
'begtime'=>time(),
);
$tms->field('qihao,temashi,tema,jieshi,bose,shengxiao,begtime')->add($sldata);
$this->success('添加成功',U('tms'),1);
}
}
public function tms_edit(){
$id=I('id');
$tms=M('tms')->where(array('id'=>$id))->find();
$this->assign('tms',$tms);
$this->display();
}
public function tms_runedit(){
if (!IS_AJAX){
$this->error('提交方式不正确',0,0);
}else{
$tms=M('tms');
$sldata=array(
'id'=>I('id'),
'qihao'=>I('qihao'),
'temashi'=>I('temashi'),
'tema'=>I('tema'),
'jieshi'=>I('jieshi'),
'bose'=>I('bose'),
'shengxiao'=>I('shengxiao'),
);
M('tms')->field('id,qihao,temashi,tema,jieshi,bose,shengxiao')->save($sldata);
$this->success('修改成功',U('tms'),1);
}
}
//特码诗广告设置
public function tmsad(){
$tms_ad=M('tms_ad')->where(array('id'=>1))->find();
$this->assign('tms_ad',$tms_ad)->display();
}
//保存特码诗广告设置
public function runtmsad(){
if (!IS_AJAX){
$this->error('提交方式不正确',0,0);
}else{
$tms_ad=M('tms_ad');
if (!$tms_ad->autoCheckToken($_POST)){
$this->error('表单令牌错误',0,0);
}else{
$sl_data=array(
'id'=>I('id'),
'biaoti'=>I('biaoti'),
'ad_1'=>I('ad_1','','htmlspecialchars'),
'ad_2'=>I('ad_2','','htmlspecialchars'),
'ad_3'=>I('ad_3','','htmlspecialchars'),
'ad_4'=>I('ad_4','','htmlspecialchars'),
'ad_5'=>I('ad_5','','htmlspecialchars'),
'ad_6'=>I('ad_6','','htmlspecialchars'),
);
$tms_ad->field('id,biaoti,ad_1,ad_2,ad_3,ad_4,ad_5,ad_6')->save($sl_data);
$this->success('特码诗广告保存成功',U('tms_ad'),1);
}
}
}
}<file_sep>/ci/app/controllers/admin/index.php
<?php
class Index extends WW_Controller{
public function ww(){
var_dump($this->input->get());exit();
$this->load->view('index/ww',['a'=>111]);
}
}<file_sep>/admin/Admin/Common/Conf/config.php
<?php
return array(
//↓↓↓↓↓↓↓↓↓↓↓数据库配置资料
'DB_TYPE' => 'mysql',
'DB_HOST' => '192.168.8.102',
'DB_NAME' => 'lhc',//需要新建一个数据库!名字叫
'DB_USER' => 'root', //数据库用户名
'DB_PWD' => '<PASSWORD>',//数据库登录密码
'DB_PORT' => '3306',
'DB_PREFIX' => 'cz_',//数据库表名前缀
'DB_PARAMS' => array(), // 数据库连接参数
//'DB_DEBUG' => TRUE, // 数据库调试模式 开启后可以记录SQL日志
'DB_FIELDS_CACHE' => true, // 启用字段缓存
'DB_CHARSET' => 'utf8', // 数据库编码默认采用utf8
'DB_DEPLOY_TYPE' => 0, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
'DB_RW_SEPARATE' => false, // 数据库读写是否分离 主从式有效
'DB_MASTER_NUM' => 1, // 读写分离后 主服务器数量
'DB_SLAVE_NO' => '', // 指定从服务器序号
//↑↑↑↑↑↑↑↑↑↑↑↑数据库配置资料
// 'URL_MODEL' =>2,// URL访问模式,可选参数0、1、2、3 已分离! Index\Home\Conf 和 Admin\Home\Conf
//'SHOW_PAGE_TRACE' =>true,//让页面显示追踪日志信息
//'SHOW_RUN_TIME' =>true, //显示运行时间
//'SHOW_ADV_TIME' =>true, //显示详细的运行时间
//'SHOW_DB_TIMES'=>true,//显示数据库操作次数
//'SHOW_CACHE_TIMES'=>true,//显示缓存操作次数
//'SHOW_USE_MEM'=>true,//显示内存开销
/*
* 返回参数类型,用于判断返回值
*/
'CUE_0'=>0,
'CUE_1'=>1,
'CUE_2'=>2,
'CUE_3'=>3,
'DB_FIELD_CACHE'=>false,
'HTML_CACHE_ON'=>false,
'AUTH_CONFIG' => array(
'AUTH_ON' => true, //是否开启权限
'AUTH_TYPE' => 1, //
'AUTH_GROUP' => 'cz_auth_group', //用户组
'AUTH_GROUP_ACCESS' => 'cz_auth_group_access', //用户组规则
'AUTH_RULE' => 'cz_auth_rule', //规则中间表
'AUTH_USER' => 'cz_admin'// 管理员表
),
/* 自动运行配置 */
'CRON_CONFIG_ON' => true, // 是否开启自动运行
'CRON_CONFIG' => array(
'采集开奖' => array('Home/Caiji/kjcj', '18000', ''), //路径(格式同R)、间隔秒(0为一直运行)、指定一个开始时间
'心水资料' => array('Home/Caiji/zxcj1', '14400', ''), //路径(格式同R)、间隔秒(0为一直运行)、指定一个开始时间
'心水资料' => array('Home/Caiji/zxcj2', '18400', ''), //路径(格式同R)、间隔秒(0为一直运行)、指定一个开始时间
'心水资料' => array('Home/Caiji/zxcj3', '18000', ''), //路径(格式同R)、间隔秒(0为一直运行)、指定一个开始时间
'心水资料' => array('Home/Caiji/zxcj4', '18400', ''), //路径(格式同R)、间隔秒(0为一直运行)、指定一个开始时间
'心水资料' => array('Home/Caiji/zxcj6', '23400', ''), //路径(格式同R)、间隔秒(0为一直运行)、指定一个开始时间
'心水资料' => array('Home/Caiji/zxcj9', '23400', ''), //路径(格式同R)、间隔秒(0为一直运行)、指定一个开始时间
'图库采集' => array('Home/Caiji/tkcj', '25400', ''), //路径(格式同R)、间隔秒(0为一直运行)、指定一个开始时间
),
'TOKEN_ON' => false, // 是否开启令牌验证 默认关闭
'TOKEN_NAME' => '__hash__', // 令牌验证的表单隐藏字段名称,默认为__hash__
'TOKEN_TYPE' => 'md5', //令牌哈希验证规则 默认为MD5
'TOKEN_RESET' => true, //令牌验证出错后是否重置令牌 默认为true
'DEFAULT_FILTER' => 'strip_tags,stripslashes',//使用函数过滤
// 布局设置
'TMPL_ENGINE_TYPE' => 'Think', // 默认模板引擎 以下设置仅对使用Think模板引擎有
'LOAD_EXT_FILE'=>'Common', //项目中的conf.php
);
/**
* 将U函数生成的链接转换为路由链接
* @param string $url U函数生成的链接
*/
function RU($url){
// 兼容 category/:cid\d 路由
if(preg_match('/\/Home\/Index\/category\/cid\/\d+/', $url)){
$url=str_replace(array('/Home/Index','/cid'), '', $url);
}
// 兼容 tag/:tid\d 路由
if(preg_match('/\/Home\/Index\/tag\/tid\/\d+/', $url)) {
$url=str_replace(array('/Home/Index','/tid'), '', $url);
}
// 兼容article/cid/:cid\d/:aid\d
if(preg_match('/\/Home\/Index\/article\/cid\/\d+\/aid\/\d+/', $url)){
$url=str_replace(array('/Home/Index','/aid'), '', $url);
}
// 兼容 article/sw/:search_word\S/:aid\d
if(preg_match('/\/Home\/Article\/lists\/id\/\d+/', $url)){
$url=str_replace(array('/Home','/id'), '', $url);
}
// 兼容 article/:aid\d=>Index/article
if(preg_match('/\/Home\/(.*)\/detail\/id\/\d+/', $url)){
$url=str_replace(array('/Home','/id'), '', $url);
$url=str_replace('/detail', '', $url);
}
// 兼容 index/:p\d=>'Index/index
if(preg_match('/\/Home/', $url)){
$url=str_replace('/Home', '', $url);
}
return $url;
//return $url;
}
?><file_sep>/tp5/runtime/temp/08ff75ec9d5f3a8ee856c07b611b8f2e.php
<?php if (!defined('THINK_PATH')) exit(); /*a:1:{s:78:"/Applications/MAMP/htdocs/tp5/public/../application/admin/view/auth/index.html";i:1500214932;}*/ ?>
<div class="box-body table-responsive">
<table id="example2" class="table table-striped table-hover">
<thead>
<tr>
<th><input type="checkbox" ></th>
<th>名称</th>
<th>URL</th>
<th>标识符</th>
<th>排序</th>
<th>类型</th>
<th>图标</th>
<th>状态</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<?php if(is_array($list) || $list instanceof \think\Collection || $list instanceof \think\Paginator): $i = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?>
<tr>
<td><input type="checkbox" value='<?php echo $vo['id']; ?>' name="id[]" ></td>
<td><?php echo $vo['name']; ?></td>
<td><?php echo $vo['url']; ?></td>
<td><?php echo $vo['menu_id']; ?></td>
<td><?php echo $vo['sort']; ?></td>
<td><?php if($vo['category'] == 1): ?>主菜单<?php elseif($vo['category'] == 2): ?>二级菜单<?php else: ?>操作<?php endif; ?></td>
<td><?php echo $vo['icon']; if(!(empty($vo['icon_size']) || (($vo['icon_size'] instanceof \think\Collection || $vo['icon_size'] instanceof \think\Paginator ) && $vo['icon_size']->isEmpty()))): ?>(<?php echo $vo['icon_size']; ?>)<?php endif; ?></td>
<td><?php if(in_array(($vo['status']), explode(',',"1"))): ?><span class="badge bg-green">启用</span><?php else: ?><span class="badge bg-red">禁用</span><?php endif; ?></td>
<td><button onclick='load_modal("__CONTROLLER__/edit?id=<?php echo $vo['id']; ?>")' class="btn btn-xs btn-info">编辑</button></td>
</tr>
<?php endforeach; endif; else: echo "" ;endif; ?>
</tbody>
</table>
</div><file_sep>/ci/app/controllers/index.php
<?php
class Index extends MY_Controller {
public function __construct(){
parent::__construct();
}
public function index()
{
return_json('api接口连接成功',$this->redis->get_all());
}
}<file_sep>/admin/Admin/Home/Common/Common.php
<?php
function begtime(){
return strtotime(date("Y-m-d G:i:s"));
}
function datetime($var){
return date("Y-m-d G:i:s",$var);
}
function dingdanhao(){
$dingdanhao = date("Y-m-dH-i-s");
$dingdanhao = str_replace("-","",$dingdanhao);
$dingdanhao .= rand(10000,90000);
return $dingdanhao;
}
//使用说明 Yo_Directory_Title(数据表,1显示下级 0 不显示,.编号)
function czdirectory($table,$val=0,$var1=0,$config=0){
$len=strlen($var1);
$Dao = M();
if ($var1==''){
return "";
exit();
}
$list = $Dao->query("select * from cz_".$table."_class where NumberID=".$var1);
if ($val==0){
return $list[0][title];
}
}
//↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓以下是更新数据操作方法
function Cupdate($id){
$Dao = M();
$num = $Dao->execute("update cz_article set title='<EMAIL>' where id=".$id);
}
/*===============================说明开始=========================*/
/*table 代表哪个数据表 way 代表的是方式 0 是默认从低到高 1 是从高到低排序
/*Point 代表移动方式 up上移 down 下移
/*id 代表数据本身Id
/*where 代表移动数据的方向 从低到高 或者从高到低
/*===============================说明结束=========================*/
function getsorting($table,$Point='up',$id,$where=0,$search="1=1",$numberid="0001"){
$Dao = M();
if ($search=='0'){
$search=" LagID=0";
}elseif ($search=='1'){
$search=" LagID=1 and Root4=".substr($numberid,0,4);
}elseif ($search=='2'){
$search=" LagID=1 and Root4=".substr($numberid,0,8);
}elseif ($search=='3'){
$search=" LagID=1 and Root4=".substr($numberid,0,12);
}
if ($Point=='up' && $where==0){
$list = $Dao->query("select * from `".$table."` where sorting>$id and $search order by sorting asc limit 1");
}elseif ($Point=='up' && $where==1){
$list = $Dao->query("select * from `".$table."` where sorting<$id and $search order by sorting desc limit 1");
}elseif ($Point=='down' && $where==0){
$list = $Dao->query("select * from `".$table."` where sorting<$id and $search order by sorting desc limit 1");
}elseif ($Point=='down' && $where==1){
$list = $Dao->query("select * from `".$table."` where sorting>$id and $search order by sorting asc limit 1");
}
return $list[0][sorting];
}
function cz_sorting($table,$way=0,$Point,$id,$sid,$config){
/*===============================说明开始=========================*/
/*table 代表哪个数据表 way 代表的是方式 0 是默认从低到高 1 是从高到低排序
/*Point 代表移动方式 1 置顶 2 上移 3 下移 4 置底
/*id 代表数据本身Id sid 代表移动到哪个Id
/*===============================说明结束=========================*/
//-----------------------------------------------------------进行数据验证 Start
if (($Point==1 || $Point==2 )and ($sid=='' || $sid==$id)){
echo "<script>alert('操作失败,已经到顶部了!');history.go(-1);</script>";
exit();
}elseif(($Point==3 || $Point==4 )and ($sid=='' || $sid==$id)){
echo "<script>alert('操作失败,已经到底部了!');history.go(-1);</script>";
exit();
}
if ($way==1){
//===========================================================排序条件 Start
if ($Point==1){//==============置顶
$search="where sorting<='$sid' and sorting>='$id' order by sorting asc";
}elseif($Point==2){//==============上移
$search="where sorting>='$id' and sorting<='$sid' order by sorting desc";
}elseif($Point==3){//==============下移
$search="where sorting<='$id' and sorting>='$sid' order by sorting desc";
}elseif($Point==4){//==============置底
$search="where sorting<='$id' and sorting>='$sid' order by sorting desc";
}
}elseif ($way==0){
if ($Point==1){//==============置顶
$search="where sorting>='$sid' and sorting<='$id' order by sorting desc";
}elseif($Point==2){//==============上移
$search="where sorting<='$id' and sorting>='$sid' order by sorting asc";
}elseif($Point==3){//==============下移
$search="where sorting>='$id' and sorting<='$sid' order by sorting asc";
}elseif($Point==4){//==============置底
$search="where sorting>='$id' and sorting<='$sid' order by sorting asc";
}
}
//============================================================排序条件 End
//===================================================================================按条件搜索并组合成数组
$Arrsorting=array(); ###定义数组
$Arrid=array(); ###定义数
$Dao = M();
$total= count($Dao->query("select * from $table $search"));//获取数量
$list = $Dao->query("select * from $table $search");
foreach ($list as $val){
$Arrsorting[]=$val['sorting']; ###组合数组
$Arrid[]=$val['id']; ###组合数组
}
//===================================================================================按条件搜索并组合成数组 The End
//===================================================================================进行数据的整合及更新
$Arrsorting=array_reverse($Arrsorting);//让数组倒序
foreach($Arrid as $vale){ //循环数组准备更新
$sorting=$Arrsorting[$total];
if ($sorting==''){$sorting=$Arrsorting[0];}//把本身的Id等于置底的排序
//echo $vale.'==='.$sorting."<br>";
$Dao = M();
$Dao->execute("update $table set sorting=$sorting where id=".$vale);
$total--;
}
//===================================================================================进行数据的整合及更新 The End
}
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑以上是更新数据操作方法
function cz_class_sorting($table,$way=0,$Point,$id,$sid,$numberid,$config){
$len=strlen($numberid);
if ($numberid==''){
$search="where LagID=0 ";
}elseif($len==4 and $numberid!=''){
$search="where LagID=1 and Root1='$numberid'";
}elseif($len==8 and $numberid!=''){
$search="where LagID=2 and Root2='$numberid'";
}elseif($len==12 and $numberid!=''){
$search="where LagID=3 and Root3='$numberid'";
}
//-----------------------------------------------------------进行数据验证 Start
if (($Point==1 || $Point==2 )and ($sid=='' || $sid==$id)){
echo "<script>alert('操作失败,已经到顶部了!');history.go(-1);</script>";
exit();
}elseif(($Point==3 || $Point==4 )and ($sid=='' || $sid==$id)){
echo "<script>alert('操作失败,已经到底部了!');history.go(-1);</script>";
exit();
}
if ($way==1){
//===========================================================排序条件 Start
if ($Point==1){//==============置顶
$searchs=$search." and sorting<='$sid' and sorting>='$id' order by sorting asc";
}elseif($Point==2){//==============上移
$searchs=$search." and sorting>='$id' and sorting<='$sid' order by sorting desc";
}elseif($Point==3){//==============下移
$searchs=$search." and sorting<='$id' and sorting>='$sid' order by sorting desc";
}elseif($Point==4){//==============置底
$searchs=$search." and sorting<='$id' and sorting>='$sid' order by sorting desc";
}
}elseif ($way==0){
if ($Point==1){//==============置顶
$searchs=$search." and sorting>='$sid' and sorting<='$id' order by sorting desc";
}elseif($Point==2){//==============上移
$searchs=$search." and sorting<='$id' and sorting>='$sid' order by sorting asc";
}elseif($Point==3){//==============下移
$searchs=$search." and sorting>='$id' and sorting<='$sid' order by sorting asc";
}elseif($Point==4){//==============置底
$searchs=$search." and sorting>='$id' and sorting<='$sid' order by sorting asc";
}
}
$Arrsorting=array();
$Arrid=array();
$Dao = M();
$total= count($Dao->query("select * from $table $searchs"));
$list = $Dao->query("select * from $table $searchs");
foreach ($list as $val){
$Arrsorting[]=$val['sorting'];
$Arrid[]=$val['id'];
}
$Arrsorting=array_reverse($Arrsorting);
foreach($Arrid as $vale){
$sorting=$Arrsorting[$total];
if ($sorting==''){$sorting=$Arrsorting[0];}
$Dao = M();
$Dao->execute("update $table set sorting=$sorting where id=".$vale);
$total--;
}
//===================================================================================进行数据的整合及更新 The End
}
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑以上是更新数据操作方法
function cz_lhc_xiao($type=0,$value){
$lhc_rgb=array(
"red_arr"=>array("01","02","07","08","12","13","18","19","23","24","29","30","34","35","40","45","46"),
"green_arr"=>array("05","06","11","16","17","21","22","27","28","32","33","38","39","43","44","49"),
"blue_arr"=>array("03","04","09","10","14","15","20","25","26","31","36","37","41","42","47","48"),
"SX"=>array(
"兔"=>array("06","18","30","42"),
"龍"=>array("05","17","29","41"),
"蛇"=>array("04","16","28","40"),
"蛇"=>array("04","16","28","40"),
"馬"=>array("03","15","27","39"),
"羊"=>array("02","14","26","38"),
"猴"=>array("01","13","25","37","49"),
"雞"=>array("12","24","36","48"),
"狗"=>array("11","23","35","47"),
"豬"=>array("10","22","34","46"),
"鼠"=>array("09","21","33","45"),
"牛"=>array("08","20","32","44"),
"虎"=>array("07","19","31","43")
),
"JQ"=>array("牛","馬","羊","雞","狗","豬","猪","鸡","马"),//家禽
"WH"=>array(
'金'=>array("02", "03", "16", "17", "24", "25", "32", "33", "46", "47"),
'木'=>array("06", "07", "14", "15", "28", "29", "36", "37", "44", "45"),
"水"=>array("04", "05", "12", "13", "20", "21", "34", "35", "42", "43"),
"火"=>array("01", "08", "09", "22", "23", "30", "31", "38", "39"),
"土"=>array("10", "11", "18", "19", "26", "27", "40", "41", "48", "49"),
),
"HB"=>array(
'黑'=>array("兔","龍","蛇","馬","羊","猴"),
'白'=>array("鼠","牛","虎","雞","狗","豬"),
),
"YY"=>array(
'阴'=>array("鼠","龍","蛇","馬","狗","豬"),
'阳'=>array("牛","虎","兔","羊","猴","雞"),
),
"JX"=>array(
'吉'=>array("兔","龍","蛇","馬","羊","雞"),
'凶'=>array("鼠","牛","虎","猴","狗","豬"),
),
"TD"=>array(
'天'=>array("兔","馬","猴","豬","牛","龍"),
'地'=>array("蛇","羊","雞","狗","鼠","虎"),
),
"SEX"=>array(
'女'=>array("兔","蛇","羊","雞","豬"),
'男'=>array("鼠","牛","虎","龍","馬","猴","狗"),
),
"sexiao"=>array(
'紅肖'=>array("馬","兔","鼠","雞"),
'藍肖'=>array("蛇","虎","豬","猴"),
'綠肖'=>array("羊","龍","牛","狗"),
),
"bihua"=>array(
'单笔'=>array("鼠","龍","馬","蛇","雞","豬"),
'双笔'=>array("虎","猴","狗","兔","羊","牛"),
),
);
if ($type==0){
if(in_array($value,$lhc_rgb['red_arr']) ){
return '紅';
}else if( in_array($value,$lhc_rgb['green_arr']) ){
return '綠';
}else if( in_array($value,$lhc_rgb['blue_arr']) ){
return '藍';
}
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑以上是获取波段
}elseif($type==1){
$SX=$lhc_rgb['SX'];
foreach($SX as $key=>$val){
if(in_array($value,$val) ){return $key;}
}
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑以上是获取生肖
}elseif($type==2){
$SX=$lhc_rgb['WH'];
foreach($SX as $key=>$val){
if(in_array($value,$val) ){return $key;}
}
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑以上是获取生肖
}elseif($type==3){
if(in_array($value,$lhc_rgb['JQ']) ){
return '家禽';
}else{
return '野兽';
}
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑以上是获取家野
}elseif($type==4){
if($value<=9){
return "1";
}elseif($value<=18){
return "2";
}elseif($value<=27){
return "3";
}elseif($value<=37){
return "4";
}elseif($value<=49){
return "5";
}
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑以上是五门走势
}elseif($type==5){
if($value<=7){
return "1";
}elseif($value<=14){
return "2";
}elseif($value<=21){
return "3";
}elseif($value<=28){
return "4";
}elseif($value<=35){
return "5";
}elseif($value<=42){
return "6";
}elseif($value<=49){
return "7";
}
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑以上是7段走势
}elseif($type==6){
$SX=$lhc_rgb['HB'];
foreach($SX as $key=>$val){
if(in_array($value,$val) ){return $key;}
}
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑以上是获取黑白
}elseif($type==7){
$SX=$lhc_rgb['YY'];
foreach($SX as $key=>$val){
if(in_array($value,$val) ){return $key;}
}
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑以上是获取阴阳
}elseif($type==8){
$SX=$lhc_rgb['TD'];
foreach($SX as $key=>$val){
if(in_array($value,$val) ){return $key;}
}
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑以上是获取天地
}elseif($type==9){
$SX=$lhc_rgb['JX'];
foreach($SX as $key=>$val){
if(in_array($value,$val) ){return $key;}
}
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑以上是获取吉凶
}elseif($type==10){
$SX=$lhc_rgb['sexiao'];
foreach($SX as $key=>$val){
if(in_array($value,$val) ){return $key;}
}
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑以上是获取色肖
}elseif($type==11){
$SX=$lhc_rgb['bihua'];
foreach($SX as $key=>$val){
if(in_array($value,$val) ){return $key;}
}
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑以上是获取笔画
}elseif($type==12){
$SX=$lhc_rgb['SEX'];
foreach($SX as $key=>$val){
if(in_array($value,$val) ){return $key;}
}
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑以上是获取男女
}
}
?><file_sep>/ci/app/core/MY_Model.php
<?php
class MY_Model extends CI_Model{
public $table;
protected $rule=[];//验证规则
protected $message=[];//消息提示
protected $extend=[];//验证规则扩展
protected $scene=[];//验证场景
public function __construct()
{
parent::__construct();
//加载db
$this->load->database();
}
/**
* 得到多条数据
* @param string $field
* @param array $tj_arr
* @param array $condition
* @return mixed
*/
public function get_all($field = '*', $tj_arr = array(), $condition = array())
{
$tj1 = array();
$tj_arr=$tj_arr?$tj_arr:array();
foreach ($tj_arr as $k => $v) {
if (isset($v) && !empty($v)) {
$tj1[$k] = $v;
}
}
$this->db->from($this->table.' as a');
$this->db->select($field);
if (array_key_exists('join', $condition)) {
if(is_array($condition['join'])){
foreach ($condition['join'] as $joinData) {
$this->db->join($joinData['table'], $joinData['on'], 'left');
}
}
else{
$this->db->join($condition['join'].' as b', $condition['on'], 'left');
}
}
if (array_key_exists('limit', $condition)) {
$this->db->limit($condition['limit']);
}
if (array_key_exists('page_limit', $condition)) {
$this->db->limit($condition['page_limit'][1], $condition['page_limit'][0]);
}
if (array_key_exists('wherein', $condition)) {
foreach ($condition['wherein'] as $k => $v) {
$this->db->where_in($k, $v);
}
}
if (array_key_exists('orwhere', $condition)) {
foreach ($condition['orwhere'] as $k => $v) {
$this->db->or_where($k, $v);
}
}
if (array_key_exists('like', $condition)) {
foreach ($condition['like'] as $k => $v) {
if (!empty($v)) {
$this->db->like($k, $v);
}
}
}
if (array_key_exists('orlike', $condition)) {
foreach ($condition['orlike'] as $k => $v) {
if (!empty($v)) {
$this->db->or_like($k, $v);
}
}
}
if (array_key_exists('notlike', $condition)) {
foreach ($condition['nolike'] as $k => $v) {
if (!empty($v)) {
$this->db->not_like($k, $v);
}
}
}
if (array_key_exists('orderby', $condition)) {
foreach ($condition['orderby'] as $k => $v) {
$this->db->order_by($k, $v);
}
}
if (array_key_exists('groupby', $condition)) {
foreach ($condition['groupby'] as $k => $v) {
$this->db->group_by($v);
}
}
if (array_key_exists('orwhere', $condition)) {
foreach ($condition['orwhere'] as $k => $v) {
$this->db->or_where($k, $v);
}
}
if (array_key_exists('wheresql', $condition)) {
foreach ($condition['wheresql'] as $v) {
$this->db->where($v);
}
}
if ($tj1 == array()) {
$query = $this->db->get();
} else {
$query = $this->db->get_where('', $tj1);
}
$rows = $query->result_array();
return $rows;
}
/**
* @param string $field
* @param array $tj_arr
* @param array $condition
* @return array
*/
public function get_one($field = '*', $tj_arr = array(), $condition = array())
{
$this->db->select($field);
if (array_key_exists('orderby', $condition)) {
foreach ($condition['orderby'] as $k => $v) {
$this->db->order_by($k, $v);
}
}
if (array_key_exists('join', $condition)) {
if(is_array($condition['join'])){
foreach ($condition['join'] as $joinData) {
$this->db->join($joinData['table'], $joinData['on'], 'left');
}
}
else{
$this->db->join($condition['join'].' as b', $condition['on'], 'left');
}
}
if (array_key_exists('wherein', $tj_arr)) {
foreach ($tj_arr['wherein'] as $k => $v) {
if ($v != '') {
$this->db->where_in($k, $v);
}
}
unset($tj_arr['wherein']);
}
$this->db->limit(1);
$query = $this->db->get_where($this->table, $tj_arr);
if ($row = $query->row_array()) {
return $row;
}
return array();
}
//得到总数
public function count(){
$res=$this->db->get($this->table);
return $res->num_rows();
}
//添加
public function add($data){
return $this->db->insert($this->table,$data);
}
//更新
public function update($data,$where){
if($where){
$this->db->where($where);
}
$this->db->update($this->table,$data);
return $this->db->affected_rows() > 0?true:false;
}
/**
* 删除
* @param array $ids
* @return bool
*/
public function delete($ids = array())
{
if (empty($ids)) {
exit('ERROR:where is null');
}
$this->db->where_in('id',$ids);
$this->db->delete($this->table);
return $this->db->affected_rows() > 0?true:false;
}
/**
* 数据验证
* @param string $data 数据
* @param string $sceneName 场景名 'edit'
* @return bool
*/
public function check($data = '', $sceneName = '')
{
$CI =& get_instance();
$CI->load->library('validate');
if (!$data) {
$data = get();
}
//规则
$rule = $this->rule ? $this->rule : [];
//提示消息
$message = $this->message ? $this->message : [];
//验证扩展
if ($this->extend) {
foreach ($this->extend as $type => $callback) {
if(method_exists($this,$callback)){
$CI->validate->extend([$type=>[$this,$callback]]);
}
}
}
//验证
$CI->validate->rule($rule, $message);
if(!empty($sceneName)&&isset($this->scene[$sceneName])){
//场景验证
$CI->validate->scene($sceneName, $this->scene[$sceneName]);
$result = $CI->validate->scene($sceneName)->check($data);
}else{
$result = $CI->validate->check($data);
}
if ($result) {
//返回自动创建、完成后的数据
return method_exists($this,'handle')?$this->handle($data):$data;
} else {
$this->getError = $CI->validate->getError();
return false;
}
}
}<file_sep>/admin/Admin/Runtime/Cache/Home/4e2025ae531f8df746b8e682315f01d9.php
<?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta charset="utf-8" />
<title>Wmzz-Lhc网站后台系统管理</title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<!-- bootstrap & fontawesome -->
<link rel="stylesheet" href="/lh3/Public/js/assets/css/bootstrap.css" />
<link rel="stylesheet" href="/lh3/Public/js/assets/css/font-awesome.css" />
<link rel="stylesheet" href="/lh3/Public/css/font-awesome.min.css" />
<!-- ace styles -->
<link rel="stylesheet" href="/lh3/Public/js/assets/css/ace.css" class="ace-main-stylesheet" id="main-ace-style" />
<!--[if lte IE 9]>
<link rel="stylesheet" href="/lh3/Public/js/assets/css/ace-part2.css" class="ace-main-stylesheet" />
<![endif]-->
<!--[if lte IE 9]>
<link rel="stylesheet" href="/lh3/Public/js/assets/css/ace-ie.css" />
<![endif]-->
<!-- inline styles related to this page -->
<link rel="stylesheet" href="/lh3/Public/js/assets/css/slackck.css" />
<!-- ace settings handler -->
<script src="/lh3/Public/js/assets/js/ace-extra.js"></script>
<script src="/lh3/Public/js/assets/js/jquery.min.js"></script>
<script src="/lh3/Public/js/assets/js/jquery.form.js"></script>
<script src="/lh3/Public/js/assets/layer/layer.js"></script>
<!--<script src="<?php echo (JS_URL); ?>/assets/js/jquery.leanModal.min.js"></script>-->
<!--[if lte IE 8]>
<script src="/lh3/Public/js/assets/js/html5shiv.js"></script>
<script src="/lh3/Public/js/assets/js/respond.js"></script>
<![endif]-->
</head>
<body class="no-skin">
<!-- #section:basics/navbar.layout -->
<div id="navbar" class="navbar navbar-default navbar-collapse">
<script type="text/javascript">
try{ace.settings.check('navbar' , 'fixed')}catch(e){}
</script>
<div class="navbar-container" id="navbar-container">
<!-- #section:basics/sidebar.mobile.toggle -->
<button type="button" class="navbar-toggle menu-toggler pull-left" id="menu-toggler" data-target="#sidebar">
<span class="sr-only">Toggle sidebar</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<!-- /section:basics/sidebar.mobile.toggle -->
<div class="navbar-header pull-left">
<!-- #section:basics/navbar.layout.brand -->
<a href="<?php echo U('Index/index');?>" class="navbar-brand">
<small>
<i class="fa fa-leaf"></i>
Wmzz-Lhc
</small>
</a>
<!-- /section:basics/navbar.layout.brand -->
<!-- #section:basics/navbar.toggle -->
<button class="pull-right navbar-toggle navbar-toggle-img collapsed" type="button" data-toggle="collapse" data-target=".navbar-buttons">
<span class="sr-only">Toggle user menu</span>
<img src="/lh3/Public/js/assets/avatars/user.jpg" alt="Jason's Photo" />
</button>
<!-- /section:basics/navbar.toggle -->
</div>
<!-- #section:basics/navbar.dropdown -->
<div class="navbar-buttons navbar-header pull-right collapse navbar-collapse" role="navigation">
<ul class="nav ace-nav">
<li class="transparent"></li>
<li class="transparent">
<a style="cursor:pointer;" id="cache" class="dropdown-toggle">清除缓存</a>
</li>
<!-- #section:basics/navbar.user_menu -->
<li class="light-blue">
<a data-toggle="dropdown" href="#" class="dropdown-toggle">
<img class="nav-user-photo" src="/lh3/Public/js/assets/avatars/user.jpg" alt="Jason's Photo" />
<span class="user-info">
<small>管理员</small>
<?php echo ($_SESSION['admin_username']); ?>
</span>
<i class="ace-icon fa fa-caret-down"></i>
</a>
<ul class="user-menu dropdown-menu-right dropdown-menu dropdown-yellow dropdown-caret dropdown-close">
<li class="divider"></li>
<li>
<a href="javascript:;" id="logout">
<i class="ace-icon fa fa-power-off"></i>
注销
</a>
</li>
</ul>
</li>
<!-- /section:basics/navbar.user_menu -->
</ul>
</div>
<!-- /section:basics/navbar.dropdown -->
</div><!-- /.navbar-container -->
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#logout").click(function(){
layer.confirm('你确定要退出吗?', {icon: 3}, function(index){
layer.close(index);
window.location.href="<?php echo U('Administrator/logout');?>";
});
});
});
$(function(){
$('#cache').click(function(){
if(confirm("确认要清除缓存?")){
var $type=$('#type').val();
var $mess=$('#mess');
$.post('/lh3/index.php/Home/Ziliao/clear',{type:$type},function(data){
alert("缓存清理成功");
});
}else{
return false;
}
});
});
</script>
<STYLE type=text/css>
TD {
FONT-STYLE: normal; FONT-SIZE: 9pt
}
TABLE {
COLOR: #000000; FONT-SIZE: 9pt
}
UNKNOWN {
PADDING-BOTTOM: 0px; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; PADDING-TOP: 0px
}
TABLE {
COLOR: #000000; FONT-SIZE: 9pt
}
TD {
COLOR: #000000; FONT-SIZE: 9pt
}
.title_283 {
TEXT-ALIGN: center; BACKGROUND-COLOR: #0460bb; COLOR: #ffffff; FONT-SIZE: 13px
}
.main_760 {
BORDER-BOTTOM: #d2d3d9 1px solid; TEXT-ALIGN: center; BORDER-LEFT: #d2d3d9 1px solid; PADDING-BOTTOM: 2px; PADDING-LEFT: 8px; PADDING-RIGHT: 2px; FONT-SIZE: 14px; BORDER-TOP: #d2d3d9 1px solid; BORDER-RIGHT: #d2d3d9 1px solid; PADDING-TOP: 2px
}
.t5 {
BORDER-BOTTOM: #c7e1ef 1px solid; BORDER-LEFT: #c7e1ef 1px solid; BORDER-TOP: #c7e1ef 1px solid; BORDER-RIGHT: #c7e1ef 1px solid
}
.t5 {
MARGIN: 0px auto 10px; HEIGHT: auto; OVERFLOW: hidden
}
.r_one {
BACKGROUND: #f5fcff
}
.tr1 TH {
TEXT-ALIGN: left; PADDING-BOTTOM: 5px; PADDING-LEFT: 10px; PADDING-RIGHT: 10px; VERTICAL-ALIGN: top; FONT-WEIGHT: normal; PADDING-TOP: 5px
}
.tpc_content {
PADDING-BOTTOM: 2em; LINE-HEIGHT: 2em; MARGIN: 0px; PADDING-LEFT: 15px; PADDING-RIGHT: 15px; FONT-FAMILY: Arial; PADDING-TOP: 0px
}
.qs36{
font-size: 30px;
color: #000000;
font-weight: bold;
}
.q36{
font-size: 30px;
color: #6699CC;
font-weight: bold;
}
.z14r {color: #FF0000;font: bold 14px "华文中宋";}
.xj1{font: bold 16px "华文中宋";
color: #0000FF;
}
.xj2{font: bold 24px "华文中宋";
color: #0000FF;
}
.xj3{
font: bold 18px "华文中宋";
color: #0000FF;
}
.xj4t{
font: bold 30px "华文中宋";
color: #FF0000;
}
.xj4b{
font: bold 30px "华文中宋";
color: #000000;
}
.z12z1 {font-size: 12px;
color:#6633CC;
}
.tdz{text-align: left;}
.z14{
font-size: 16px;
}
.gg116 {color: #FF0000;font: bold 16px "华文中宋";}
.xj2h{
font: bold 24px "华文中宋";
color: #FF0000;
}
.xj3h{
font: bold 18px "华文中宋";
color: #FF0000;
}
.xj1h{
font: bold 16px "华文中宋";
color: #FF0000;
}
.bs18{
font-size: 20px;
font-weight: bold;
color: #FFFFFF;
}
.hs18{
font-size: 20px;
font-weight: bold;
color: #FFFF33;
}
.xj3f{
font: bold 18px "华文中宋";
color: #FF00FF;
}
.z161 { font: bold 16px "华文中宋";
color: #FF00FF;
}
.bgff00{
background: #FFFFCC;
}
</STYLE>
<link href="<?php echo (CSS_URL); ?>common.css" rel="stylesheet" type="text/css"/>
<div class="main-container" id="main-container">
<div id="sidebar" class="sidebar responsive">
<div class="sidebar-shortcuts" id="sidebar-shortcuts">
<!--左侧顶端按钮-->
<div class="sidebar-shortcuts-large" id="sidebar-shortcuts-large">
<a class="btn btn-success" href="<?php echo U('Article/index');?>" role="button" title="文章列表"><i class="ace-icon fa fa-signal"></i></a>
<a class="btn btn-info" href="<?php echo U('Article/info_add');?>" role="button" title="添加文章"><i class="ace-icon fa fa-pencil"></i></a>
<a class="btn btn-warning" href="<?php echo U('Kaijiang/index');?>" role="button" title="开奖管理"><i class="ace-icon fa fa-users"></i></a>
<a class="btn btn-danger" href="<?php echo U('Sys/sys');?>" role="button" title="站点设置"><i class="ace-icon fa fa-cogs"></i></a>
</div>
<!--左侧顶端按钮(手机)-->
<div class="sidebar-shortcuts-mini" id="sidebar-shortcuts-mini">
<a class="btn btn-success" href="<?php echo U('Article/index');?>" role="button" title="文章列表"></a>
<a class="btn btn-info" href="<?php echo U('Article/info_add');?>" role="button" title="添加文章"></a>
<a class="btn btn-warning" href="<?php echo U('Kaijiang/index');?>" role="button" title="开奖管理"></a>
<a class="btn btn-danger" href="<?php echo U('Sys/sys');?>" role="button" title="站点设置"></a>
</div>
</div>
<ul class="nav nav-list">
<?php use Common\Controller\AuthController; use Think\Auth; $m = M('auth_rule'); $field = 'id,name,title,css'; $data = $m->field($field)->where('pid=0 AND status=1')->order('sort')->select(); $auth = new Auth(); foreach ($data as $k=>$v){ if(!$auth->check($v['name'], $_SESSION['aid']) && $_SESSION['aid'] != 1){ unset($data[$k]); } } ?>
<?php if(is_array($data)): foreach($data as $key=>$v): ?><li class="<?php if(CONTROLLER_NAME == $v['name']): ?>active open<?php endif; ?>"><!--open代表打开状态-->
<a href="#" class="dropdown-toggle">
<i class="menu-icon fa <?php echo ($v["css"]); ?>"></i>
<span class="menu-text">
<?php echo ($v["title"]); ?>
</span>
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<?php $m = M('auth_rule'); $dataa = $m->where(array('pid'=>$v['id'],'menustatus'=>1))->order('sort')->select(); foreach ($dataa as $kk=>$vv){ if(!$auth->check($vv['name'], $_SESSION['aid']) && $_SESSION['aid'] != 1){ unset($dataa[$kk]); } } $id_4=$m->where(array('name'=>CONTROLLER_NAME.'/'.ACTION_NAME,'level'=>4))->field('pid')->find(); if($id_4){ $id_3=$m->where(array('id'=>$id_4['pid'],'level'=>3))->field('pid')->find(); }else{ $id_3=$m->where(array('name'=>CONTROLLER_NAME.'/'.ACTION_NAME,'level'=>3))->field('pid')->find(); if(!$id_3){ $id_2=$m->where(array('name'=>CONTROLLER_NAME.'/'.ACTION_NAME,'level'=>2))->field('id')->find(); $id_3['pid']=$id_2['id']; } } ?>
<?php if(is_array($dataa)): foreach($dataa as $key=>$j): $m = M('auth_rule'); $dataaa = $m->where(array('pid'=>$j['id'],'status'=>1))->order('sort')->select(); foreach ($dataaa as $kkk=>$vvv){ if(!$auth->check($vvv['name'], $_SESSION['aid']) && $_SESSION['aid'] != 1){ unset($dataaa[$kkk]); } } ?>
<li class="<?php if(($_SESSION['se'] == $j['id'])): ?>active<?php endif; ?>">
<a href="<?php echo U($j['name'],array('se'=>$j['id']));?>">
<i class="menu-icon fa fa-caret-right"></i>
<?php echo ($j["title"]); ?>
</a>
<b class="arrow"></b>
</li><?php endforeach; endif; ?>
</ul>
</li><?php endforeach; endif; ?>
</ul><!-- /.nav-list -->
<!-- #section:basics/sidebar.layout.minimize -->
<div class="sidebar-toggle sidebar-collapse" id="sidebar-collapse">
<i class="ace-icon fa fa-angle-double-left" data-icon1="ace-icon fa fa-angle-double-left" data-icon2="ace-icon fa fa-angle-double-right"></i>
</div>
<!-- /section:basics/sidebar.layout.minimize -->
<script type="text/javascript">
try{ace.settings.check('sidebar' , 'collapsed')}catch(e){}
</script>
</div>
<div class="main-content">
<div class="main-content-inner">
<div class="page-content">
<div class="row maintop">
<div class="col-xs-12 col-sm-8">
<form action="/lh3/index.php/Home/Ziliao/" method="get">
<input type="button" value="添加特码诗" onclick="location.href='/lh3/index.php/Home/Ziliao/tms_add.html'" class="btn btn-xs btn-danger" />
</form>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div>
<div class="table-responsive">
<table width="100%" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th width="10%">彩票期号</th>
<th width="70%">特码诗</th>
<th width="10%">特码波色</th>
<th width="5%">生肖</th>
<th width="5%" style="border-right:#CCC solid 1px;">操作</th>
</tr>
</thead>
<tbody>
<tr>
<?php $ad=M('tms_ad')->where(array('id'=>1))->find(); ?>
<?php if(is_array($list)): foreach($list as $key=>$vo): ?><tr style="margin: 0px; padding: 0px">
<td width="108" rowspan="2" id="td3477" style="font-size: 12px; font-style: normal; color: rgb(0, 0, 0); font-family: 宋体; border: 1px solid rgb(240, 145, 0); margin: 0px; padding: 3px">
<table width="102" border="0" cellspacing="0" cellpadding="0" align="center" id="table18457" height="73" style="font-size: 12px; color: buttontext; cursor: default; margin: 0px; padding: 0px">
<tbody style="margin: 0px; padding: 0px">
<tr style="margin: 0px; padding: 0px">
<td width="102" height="37" style="font-size: 16px; font-style: normal; color: rgb(0, 0, 0); font-family: arial, sans-serif, 宋体; margin: 0px; padding: 0px">
<div align="center" style="margin: 0px; padding: 0px">
<font size="6" style="margin: 0px; padding: 0px">
<span style="margin: 0px; padding: 0px">
<font style="margin: 0px; padding: 0px"><?php echo ($vo["qihao"]); ?><font color="#6699CC" style="margin: 0px; padding: 0px">期</font></span></font>
</div>
</td>
</tr>
</tbody>
</table>
</td>
<td width="609" id="td3478" height="47" style="font-size: 12px; font-style: normal; color: rgb(0, 0, 0); font-family: 宋体; border: 1px solid rgb(240, 145, 0); margin: 0px; padding: 3px">
<p align="left"><b><font size="4">【一起发特码诗】-≤<font color="#0000FF"><?php echo ($vo["temashi"]); ?></font>≥-</font></b></td>
<td width="127" rowspan="2" id="td3479" style="font-size: 12px; font-style: normal; color: rgb(0, 0, 0); font-family: 宋体; border: 1px solid rgb(240, 145, 0); margin: 0px; padding: 3px">
<table width="127" border="0" cellspacing="0" cellpadding="0" id="table18458" style="font-size: 12px; color: buttontext; cursor: default; margin: 0px; padding: 0px">
<tbody style="margin: 0px; padding: 0px">
<tr style="margin: 0px; padding: 0px">
<td style="font-size: 16px; font-style: normal; color: rgb(0, 0, 0); font-family: arial, sans-serif, 宋体; margin: 0px; padding: 0px">
<div align="center" class="style326" style="font-size: x-small; margin: 0px; padding: 0px">
特 碼--波色</div>
</td>
</tr>
</tbody>
</table>
<table width="90" border="0" cellspacing="0" cellpadding="0" id="table18459" style="font-size: 12px; color: buttontext; cursor: default; margin: 0px; padding: 0px">
<tbody style="margin: 0px; padding: 0px">
<tr style="margin: 0px; padding: 0px">
<td style="font-size: 16px; font-style: normal; color: rgb(0, 0, 0); font-family: arial, sans-serif, 宋体; margin: 0px; padding: 0px">
<table width="63" border="0" cellspacing="0" cellpadding="0" id="table18460" style="font-size: 12px; color: buttontext; cursor: default; margin: 0px; padding: 0px">
<tbody style="margin: 0px; padding: 0px">
<tr style="margin: 0px; padding: 0px">
<td style="font-size: 16px; font-style: normal; color: rgb(0, 0, 0); font-family: arial, sans-serif, 宋体; margin: 0px; padding: 0px">
<div align="center" style="margin: 0px; padding: 0px">
<font size="6" color="#FF0000"><b><?php echo ($vo["tema"]); ?></b></font>
</div>
</td>
</tr>
</tbody>
</table>
</td>
<td style="font-size: 16px; font-style: normal; color: rgb(0, 0, 0); font-family: arial, sans-serif, 宋体; margin: 0px; padding: 0px">
<table width="65" border="0" cellspacing="0" cellpadding="0" id="table18461" style="font-size: 12px; color: buttontext; cursor: default; margin: 0px; padding: 0px">
<tbody style="margin: 0px; padding: 0px">
<tr style="margin: 0px; padding: 0px">
<td style="font-size: 16px; font-style: normal; color: rgb(0, 0, 0); font-family: arial, sans-serif, 宋体; margin: 0px; padding: 0px">
<div align="center" style="margin: 0px; padding: 0px">
<font size="6"><b><?php echo ($vo["bose"]); ?></b></font>
</div>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
<td width="40" rowspan="2" id="td3480" style="font-size: 12px; font-style: normal; color: rgb(0, 0, 0); font-family: 宋体; border: 1px solid rgb(240, 145, 0); margin: 0px; padding: 3px">
<table width="40" border="0" cellspacing="0" cellpadding="0" align="center" id="table18462" style="font-size: 12px; color: buttontext; cursor: default; margin: 0px; padding: 0px">
<tbody style="margin: 0px; padding: 0px">
<tr style="margin: 0px; padding: 0px">
<td style="font-size: 16px; font-style: normal; color: rgb(0, 0, 0); font-family: arial, sans-serif, 宋体; margin: 0px; padding: 0px">
<div align="center" class="style326" style="font-size: x-small; margin: 0px; padding: 0px">
生 肖</div>
</td>
</tr>
</tbody>
</table>
<table width="40" border="0" align="center" cellpadding="0" cellspacing="0" id="table18463" height="62" style="font-size: 12px; color: buttontext; cursor: default; margin: 0px; padding: 0px">
<tbody style="margin: 0px; padding: 0px">
<tr style="margin: 0px; padding: 0px">
<td style="font-size: 16px; font-style: normal; color: rgb(0, 0, 0); font-family: arial, sans-serif, 宋体; margin: 0px; padding: 0px" width="40">
<table width="40" border="0" cellspacing="0" cellpadding="0" id="table18464" style="font-size: 12px; color: buttontext; cursor: default; margin: 0px; padding: 0px">
<tbody style="margin: 0px; padding: 0px">
<tr style="margin: 0px; padding: 0px">
<td style="font-size: 16px; font-style: normal; color: rgb(0, 0, 0); font-family: arial, sans-serif, 宋体; margin: 0px; padding: 0px">
<div align="center" style="margin: 0px; padding: 0px">
<strong><font size="6"><?php echo ($vo["shengxiao"]); ?></font></strong>
</div>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
<td width="10" rowspan="2" id="td3477" style="font-size: 12px; font-style: normal; color: rgb(0, 0, 0); font-family: 宋体; border: 1px solid rgb(240, 145, 0); margin: 0px; padding: 3px">
<table width="40" border="0" cellspacing="0" cellpadding="0" align="center" id="table18457" height="73" style="font-size: 12px; color: buttontext; cursor: default; margin: 0px; padding: 0px">
<tbody style="margin: 0px; padding: 0px">
<tr style="margin: 0px; padding: 0px">
<td width="40" height="37" style="font-size: 12px; font-style: normal; color: rgb(0, 0, 0); font-family: arial, sans-serif, 宋体; margin: 0px; padding: 0px">
<div align="center" style="margin: 0px; padding: 0px">
<font size="3" style="margin: 0px; padding: 0px">
<span style="margin: 0px; padding: 0px">
<font style="margin: 0px; padding: 0px"><a href="/lh3/index.php/Home/Ziliao/tms_edit/id/<?php echo ($vo["id"]); ?>">修改</a></font></span></font>
</div>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr style="margin: 0px; padding: 0px">
<td width="636" id="td3481" style="font-size: 12px; font-style: normal; color: rgb(0, 0, 0); font-family: 宋体; border: 1px solid rgb(240, 145, 0); margin: 0px; padding: 3px" height="38">
<p align="left" style="margin: 0px; padding: 0px">
<font face="微软雅黑">
<b><font size="4" color="#0000FF">特码诗</font></b></font>:<b><font color="#FF0000" style="font-size: 9pt">解:</font></b><font color="#FF0000"><b><?php echo ($vo["jieshi"]); ?></b>
</font>
</td>
</tr><?php endforeach; endif; ?>
<tr>
<td colspan="8" align="right"><?php echo ($page); ?></td>
</tr>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="breadcrumbs breadcrumbs-fixed" id="breadcrumbs">
<div class="row">
<div class="col-xs-12">
<div class="">
<div id="sidebar2" class="sidebar h-sidebar navbar-collapse collapse collapse_btn">
<ul class="nav nav-list header-nav" id="header-nav">
<?php $m = M('auth_rule'); $dataaa = $m->where(array('pid'=>$_SESSION['se'],'menustatus'=>1))->order('sort')->select(); foreach ($dataaa as $kkk=>$vvv){ if(!$auth->check($vvv['name'], $_SESSION['aid']) && $_SESSION['aid']!= 1){ unset($dataaa[$kkk]); } } ?>
<?php if(is_array($dataaa)): foreach($dataaa as $key=>$k): ?><li>
<a href="<?php echo U(''.$k['name'].'');?>">
<o class="font12 <?php if((CONTROLLER_NAME.'/'.ACTION_NAME == $k['name'])): ?>rigbg<?php endif; ?>"><?php echo ($k["title"]); ?></o>
</a>
<b class="arrow"></b>
</li><?php endforeach; endif; ?>
</ul><!-- /.nav-list -->
</div><!-- .sidebar -->
</div>
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
</div>
<div class="footer">
<div class="footer-inner">
<!-- #section:basics/footer -->
<div class="footer-content">
<span class="bigger-120">
<span class="blue bolder">Wmzz.Cn</span>
Lhc系统 © 2015-2016
</span>
</div>
<!-- /section:basics/footer -->
</div>
</div>
<!-- basic scripts -->
<!--[if IE]>
<script type="text/javascript">
window.jQuery || document.write("<script src='/lh3/Public/js/assets/js/jquery1x.js'>"+"<"+"/script>");
</script>
<![endif]-->
<script src="/lh3/Public/js/assets/js/bootstrap.js"></script>
<script src="/lh3/Public/js/assets/js/maxlength.js"></script>
<script src="/lh3/Public/js/assets/js/ace/ace.js"></script>
<script src="/lh3/Public/js/assets/js/ace/ace.sidebar.js"></script>
<!-- inline scripts related to this page -->
<script type="text/javascript">
jQuery(function($) {
$('#sidebar2').insertBefore('.page-content');
$('.navbar-toggle[data-target="#sidebar2"]').insertAfter('#menu-toggler');
$(document).on('settings.ace.two_menu', function(e, event_name, event_val) {
if(event_name == 'sidebar_fixed') {
if( $('#sidebar').hasClass('sidebar-fixed') ) {
$('#sidebar2').addClass('sidebar-fixed');
$('#navbar').addClass('h-navbar');
}
else {
$('#sidebar2').removeClass('sidebar-fixed')
$('#navbar').removeClass('h-navbar');
}
}
}).triggerHandler('settings.ace.two_menu', ['sidebar_fixed' ,$('#sidebar').hasClass('sidebar-fixed')]);
})
</script>
</div>
<script src="<?php echo (JS_URL); ?>jquery.min.js"></script>
<script>
function CheckAll(value,obj) {
var form=document.getElementsByTagName("form")
for(var i=0;i<form.length;i++){
for (var j=0;j<form[i].elements.length;j++){
if(form[i].elements[j].type=="checkbox"){
var e = form[i].elements[j];
if (value=="selectAll"){e.checked=obj.checked}
else{e.checked=!e.checked;}
}
}
}
}
</script>
<script>
//==========设置几秒跳转
var i = 2;
var intervalid;
function TiaoSecond(Yoyo){
if (i ==0) {
window.location.href =Yoyo;
clearInterval(intervalid);
}
document.getElementById("mes").innerHTML = i;
i--;
}
//==========设置几秒结束
//=======================获取数据
function Get_add_Save(){
var site_name =$("#site_name").attr("value");
var site_title =$("#site_title").attr("value");
var site_url =$("#site_url").attr("value");
var site_describe=$("#site_describe").attr("value");
var site_keywords=$("#site_keywords").attr("value");
var Token =$("#Token").attr("value");
jQuery.ajax({
url: "/lh3/index.php/Home/Ziliao/RightSave.html",
dataType:"json",
type:"POST",
data:{Action:"Config_Add",site_name:site_name,site_title:site_title,site_url:site_url,site_describe:site_describe,site_keywords:site_keywords},
beforeSend: function(XHR){
$('#msg').html('<center><br><br><img alt="正在加载中..." src="<?php echo (IMG_URL); ?>Loading/load1.gif" ></center>');
},
success:function(data) {
$("#msg").html(data.msg)
intervalid =setInterval("TiaoSecond('/lh3/index.php/Home/Ziliao/index.html')",1000);//==========执行几秒跳转
}
});
}
//=======================获取删除数据
function Get_Del_Save(){
var $check_boxes = $('input[type=checkbox][checked=checked][id!=check_all_box]');
if($check_boxes.length<=0){ alert('您未勾选任何数据,请先勾选!');return;}
if(confirm('您确定要删除此数据?')){
var dropIds = new Array();
$check_boxes.each(function(){
dropIds.push($(this).val());
});
jQuery.ajax({
url: "/lh3/index.php/Home/Ziliao/infodelete.html",
dataType:"json",
type:"POST",
data:{Action:"Alldel",id:dropIds},
beforeSend: function(){
$('#msg').html('<center><br><br><img alt="正在加载中..." src="<?php echo (IMG_URL); ?>Loading/load1.gif" ></center>');
},
success:function(data){
$("#msg").html(data.msg)
intervalid =setInterval("TiaoSecond('/lh3/index.php/Home/Ziliao/index.html')",1000);//==========执行几秒跳转
}
});
}
}
//=======================获取其他操作
function Get_Ation_Save(oo1,oo2){
if(confirm('您确定要执行此操作?')){
jQuery.ajax({
url: "/lh3/index.php/Home/Ziliao/infodelete.html",
dataType:"json",
type:"POST",
data:{Action:"del",id:oo2},
beforeSend: function(){
$('#msg').html('<center><br><br><img alt="正在加载中..." src="<?php echo (IMG_URL); ?>Loading/load1.gif" ></center>');
},
success:function(data){
$("#msg").html(data.msg)
intervalid =setInterval("TiaoSecond('/lh3/index.php/Home/Ziliao/index.html')",1000);//==========执行几秒跳转
}
});
}
}
</script>
</body>
</html><file_sep>/admin/Admin/Home/Controller/TukuController.class.php
<?php
namespace Home\Controller;
use Think\Controller;
use Common\Controller\AuthController;
use Think\Auth;
class TukuController extends AuthController {
//-----------------------以下调用彩色图库内容
public function caise(){
$Article=D("Home/Tuku");
$count =$Article->count();
$Page = new \Common\Page($count,30);
$show = $Page->paging();
$keywords=I('get.keywords','','strip_tags');
$search="1=1";
if ($keywords!='')$search.=" and title like '%$keywords%' ";
$list = $Article->field(array('id','title','begtime','hits','directory4','sorting'))->where($search)->order("id desc")->limit($Page->limit)->select();
#######读取第一条排序
$Start = $Article->field(array('sorting'))->where($search)->order("id desc,begtime desc")->limit(1)->select();
#######读取后一条排序
$End = $Article->field(array('sorting'))->where($search)->order("id asc,begtime desc")->limit(1)->select();
$this->assign('Startid',$Start[0]['sorting']);
$this->assign('Endid',$End[0]['sorting']);
$this->assign('list',$list);
$this->assign('page',$show);// 赋值分页输出
$this->display();
}
public function caise_info_add(){
if ($_POST['Action']==''){
$this->display();
}else{
$title=I('post.title','','strip_tags'); ######安全模式过滤获取标题
$picurl=I('post.path','','strip_tags'); ######安全模式过滤获取标题
$ClassID=I('post.ClassID','','strip_tags'); ######安全模式过滤获取标题
$directory1=substr($ClassID,0,4); ######文章一级栏目
$directory2=substr($ClassID,0,8); ######文章二级栏目
$directory3=substr($ClassID,0,12); ######文章三级栏目
$directory4=substr($ClassID,0,16); ######文章四级栏目
$content=$_POST['content']; ###内容
session(tuku_class,$ClassID);
//$Article=D("Home/article"); // 实例化Data数据对象
//$array=array(
//"title"=>$title,
//"picurl"=>$picurl,
//"content"=>$content,
//"directory1"=>$directory1,
//"directory2"=>$directory2,
//"directory3"=>$directory3,
//"directory4"=>$directory4,
//"begtime"=>$begtime
//);
//$request=$Article->add($array); // 实例化Data数据对象
//↓↓↓↓↓↓↓↓↓↓↓利用AR数据添加方法
$Article=D("Home/tuku"); // 实例化Data数据对象
$Article->title=$title;
$Article->picurl=$picurl;
$Article->content=$content;
$Article->directory1=$directory1;
$Article->directory2=$directory2;
$Article->directory3=$directory3;
$Article->directory4=$directory4;
$Article->begtime=begtime();
$request=$Article->add();
$Article->where('id='.$request)->save(array("sorting"=>$request));
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑利用AR数据添加方法
if ($request>0){
$msg="<div class='Yoerror3'>操作成功!<br>系统将在 <span id=\"mes\">3</span> 秒钟后返回!</div>";
echo json_encode(array("msg"=>$msg,"error"=>0));
}else{
$msg="<div class='Yoerror1'>操作失败!产生错误的原因:可能是您没有输入信息<br>系统将在 <span id=\"mes\">3</span> 秒钟后返回!</div>";
echo json_encode(array("msg"=>$msg,"error"=>1));
}
//↑↑↑↑以上开始数据的更新
}
}
//↓↓↓利用AR方法执行数据的修改
public function caise_info_edit(){
if ($_POST['Action']==''){
$id=I('get.Id',0,'intval');######安全模式过滤获取标签
$Article=D("Home/tuku")->find($id); ###实例化Data数据对象
$this->assign('info',$Article); ######赋值Id
$this->display();
}elseif($_POST['Action']=='Edit'){
$Id=I('post.Id',0,'intval'); ######安全模式过滤获取标签
$title=I('post.title','','strip_tags'); ######安全模式过滤获取标题
$picurl=I('post.path','','strip_tags'); ######安全模式过滤获取标题
$ClassID=I('post.ClassID','','strip_tags'); ######安全模式过滤获取标题
$directory1=substr($ClassID,0,4); ######文章一级栏目
$directory2=substr($ClassID,0,8); ######文章二级栏目
$directory3=substr($ClassID,0,12); ######文章三级栏目
$directory4=substr($ClassID,0,16); ######文章四级栏目
$content=$_POST['content']; ###内容
$Article=D("Home/tuku"); ###实例化Data数据对象
$Article->title=I('post.title','','strip_tags');
$Article->picurl=$picurl;
$Article->content=$content;
$Article->directory1=$directory1;
$Article->directory2=$directory2;
$Article->directory3=$directory3;
$Article->directory4=$directory4;
$begtime->begtime=$begtime;
$request=$Article->where('id='.$Id)->save();
if ($request>0){
$msg="<div class='Yoerror3'>操作成功!<br>系统将在 <span id=\"mes\">3</span> 秒钟后返回!</div>";
echo json_encode(array("msg"=>$msg,"error"=>0));
}else{
$msg="<div class='Yoerror1'>操作失败!产生错误的原因:可能是您没有输入信息<br>系统将在 <span id=\"mes\">3</span> 秒钟后返回!</div>";
echo json_encode(array("msg"=>$msg,"error"=>1));
}
}
}
//↑↑以上开始数据的修改
//↓↓执行数据的删除
public function caise_infodelete(){
$id=$_POST['id'];
$Article=D("Home/tuku"); ###实例化Data数据对象
if ($_POST['Action']=='del'){
$request=$Article->where('id='.$id)->delete();
}else{
$request=$Article->where(array('id'=>array('in',$id)))->delete();
}
if ($request>0){
$msg="<div class='Yoerror3'>操作成功!<br>系统将在 <span id=\"mes\">3</span> 秒钟后返回!</div>";
echo json_encode(array("msg"=>$msg,"error"=>0));
}else{
$msg="<div class='Yoerror1'>操作失败!产生错误的原因:可能该信息已经被删除<br>系统将在 <span id=\"mes\">3</span> 秒钟后返回!</div>";
echo json_encode(array("msg"=>$msg,"error"=>1));
}
}
//↑↑以上开始数据的删除
public function caise_directory(){
$NumberID=I('get.NumberID','','strip_tags');
$NumberID1 = substr ("$NumberID",0,4);
$NumberID2 = substr ("$NumberID",0,8);
$NumberID3 = substr ("$NumberID",0,12);
$NumberID4 = substr ("$NumberID",0,16);
$len=strlen($NumberID);
$this->assign('len',$len);
$this->assign('NumberID',$NumberID);
$this->assign('NumberID1',$NumberID1);
$this->assign('NumberID2',$NumberID2);
$this->assign('NumberID3',$NumberID3);
$this->assign('NumberID4',$NumberID4);
$this->display();
}
//-----------------------彩色图库结束
//↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓黑白图库
public function heibai(){
$Article=D("Home/Heibai");
$count =$Article->count();
$Page = new \Common\Page($count,30);
$show = $Page->paging();
$keywords=I('get.keywords','','strip_tags');
$search="1=1";
if ($keywords!='')$search.=" and title like '%$keywords%' ";
$list = $Article->field(array('id','title','begtime','hits','directory4','sorting'))->where($search)->order("id desc")->limit($Page->limit)->select();
#######读取第一条排序
$Start = $Article->field(array('sorting'))->where($search)->order("id desc,begtime desc")->limit(1)->select();
#######读取后一条排序
$End = $Article->field(array('sorting'))->where($search)->order("id asc,begtime desc")->limit(1)->select();
$this->assign('Startid',$Start[0]['sorting']);
$this->assign('Endid',$End[0]['sorting']);
$this->assign('list',$list);
$this->assign('page',$show);// 赋值分页输出
$this->display();
}
public function heibai_info_add(){
if ($_POST['Action']==''){
$this->display();
}else{
$title=I('post.title','','strip_tags'); ######安全模式过滤获取标题
$picurl=I('post.path','','strip_tags'); ######安全模式过滤获取标题
$ClassID=I('post.ClassID','','strip_tags'); ######安全模式过滤获取标题
$directory1=substr($ClassID,0,4); ######文章一级栏目
$directory2=substr($ClassID,0,8); ######文章二级栏目
$directory3=substr($ClassID,0,12); ######文章三级栏目
$directory4=substr($ClassID,0,16); ######文章四级栏目
$content=$_POST['content']; ###内容
session(heibai_class,$ClassID);
//$Article=D("Home/article"); // 实例化Data数据对象
//$array=array(
//"title"=>$title,
//"picurl"=>$picurl,
//"content"=>$content,
//"directory1"=>$directory1,
//"directory2"=>$directory2,
//"directory3"=>$directory3,
//"directory4"=>$directory4,
//"begtime"=>$begtime
//);
//$request=$Article->add($array); // 实例化Data数据对象
//↓↓↓↓↓↓↓↓↓↓↓利用AR数据添加方法
$Article=D("Home/heibai"); // 实例化Data数据对象
$Article->title=$title;
$Article->picurl=$picurl;
$Article->content=$content;
$Article->directory1=$directory1;
$Article->directory2=$directory2;
$Article->directory3=$directory3;
$Article->directory4=$directory4;
$Article->begtime=begtime();
$request=$Article->add();
$Article->where('id='.$request)->save(array("sorting"=>$request));
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑利用AR数据添加方法
if ($request>0){
$msg="<div class='Yoerror3'>操作成功!<br>系统将在 <span id=\"mes\">3</span> 秒钟后返回!</div>";
echo json_encode(array("msg"=>$msg,"error"=>0));
}else{
$msg="<div class='Yoerror1'>操作失败!产生错误的原因:可能是您没有输入信息<br>系统将在 <span id=\"mes\">3</span> 秒钟后返回!</div>";
echo json_encode(array("msg"=>$msg,"error"=>1));
}
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑以上开始数据的更新
}
}
//↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓利用AR方法执行数据的修改
public function heibai_info_edit(){
if ($_POST['Action']==''){
$id=I('get.Id',0,'intval');######安全模式过滤获取标签
$Article=D("Home/heibai")->find($id); ###实例化Data数据对象
$this->assign('info',$Article); ######赋值Id
$this->display();
}elseif($_POST['Action']=='Edit'){
$Id=I('post.Id',0,'intval'); ######安全模式过滤获取标签
$title=I('post.title','','strip_tags'); ######安全模式过滤获取标题
$picurl=I('post.path','','strip_tags'); ######安全模式过滤获取标题
$ClassID=I('post.ClassID','','strip_tags'); ######安全模式过滤获取标题
$directory1=substr($ClassID,0,4); ######文章一级栏目
$directory2=substr($ClassID,0,8); ######文章二级栏目
$directory3=substr($ClassID,0,12); ######文章三级栏目
$directory4=substr($ClassID,0,16); ######文章四级栏目
$content=$_POST['content']; ###内容
$Article=D("Home/heibai"); ###实例化Data数据对象
$Article->title=I('post.title','','strip_tags');
$Article->picurl=$picurl;
$Article->content=$content;
$Article->directory1=$directory1;
$Article->directory2=$directory2;
$Article->directory3=$directory3;
$Article->directory4=$directory4;
$begtime->begtime=$begtime;
$request=$Article->where('id='.$Id)->save();
if ($request>0){
$msg="<div class='Yoerror3'>操作成功!<br>系统将在 <span id=\"mes\">3</span> 秒钟后返回!</div>";
echo json_encode(array("msg"=>$msg,"error"=>0));
}else{
$msg="<div class='Yoerror1'>操作失败!产生错误的原因:可能是您没有输入信息<br>系统将在 <span id=\"mes\">3</span> 秒钟后返回!</div>";
echo json_encode(array("msg"=>$msg,"error"=>1));
}
}
}
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑以上开始数据的修改
//↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓执行数据的删除
public function heibai_infodelete(){
$id=$_POST['id'];
$Article=D("Home/heibai"); ###实例化Data数据对象
if ($_POST['Action']=='del'){
$request=$Article->where('id='.$id)->delete();
}else{
$request=$Article->where(array('id'=>array('in',$id)))->delete();
}
if ($request>0){
$msg="<div class='Yoerror3'>操作成功!<br>系统将在 <span id=\"mes\">3</span> 秒钟后返回!</div>";
echo json_encode(array("msg"=>$msg,"error"=>0));
}else{
$msg="<div class='Yoerror1'>操作失败!产生错误的原因:可能该信息已经被删除<br>系统将在 <span id=\"mes\">3</span> 秒钟后返回!</div>";
echo json_encode(array("msg"=>$msg,"error"=>1));
}
}
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑以上开始数据的删除
public function heibai_directory(){
$NumberID=I('get.NumberID','','strip_tags');
$NumberID1 = substr ("$NumberID",0,4);
$NumberID2 = substr ("$NumberID",0,8);
$NumberID3 = substr ("$NumberID",0,12);
$NumberID4 = substr ("$NumberID",0,16);
$len=strlen($NumberID);
$this->assign('len',$len);
$this->assign('NumberID',$NumberID);
$this->assign('NumberID1',$NumberID1);
$this->assign('NumberID2',$NumberID2);
$this->assign('NumberID3',$NumberID3);
$this->assign('NumberID4',$NumberID4);
$this->display();
}
//-----------------------黑白图库结束
//-----------------------图库期数管理----------------------------
public function qs(){
$Article=D("Home/Qs");
$count =$Article->count();
$Page = new \Common\Page($count,30);
$show = $Page->paging();
$keywords=I('get.keywords','','strip_tags');
$search="1=1";
if ($keywords!='')$search.=" and title like '%$keywords%' ";
$list = $Article->field(array('id','title','begtime','directory4','sorting'))->where($search)->order("id desc")->limit($Page->limit)->select();
#######读取第一条排序
$Start = $Article->field(array('sorting'))->where($search)->order("id desc,begtime desc")->limit(1)->select();
#######读取后一条排序
$End = $Article->field(array('sorting'))->where($search)->order("id asc,begtime desc")->limit(1)->select();
$this->assign('Startid',$Start[0]['sorting']);
$this->assign('Endid',$End[0]['sorting']);
$this->assign('list',$list);
$this->assign('page',$show);// 赋值分页输出
$this->display();
}
public function qs_info_add(){
if ($_POST['Action']==''){
$this->display();
}else{
$title=I('post.title','','strip_tags'); ######安全模式过滤获取标题
$picurl=I('post.path','','strip_tags'); ######安全模式过滤获取标题
$ClassID=I('post.ClassID','','strip_tags'); ######安全模式过滤获取标题
$directory1=substr($ClassID,0,4); ######文章一级栏目
$directory2=substr($ClassID,0,8); ######文章二级栏目
$directory3=substr($ClassID,0,12); ######文章三级栏目
$directory4=substr($ClassID,0,16); ######文章四级栏目
$content=$_POST['content']; ###内容
session(qs_class,$ClassID);
//$Article=D("Home/article"); // 实例化Data数据对象
//$array=array(
//"title"=>$title,
//"picurl"=>$picurl,
//"content"=>$content,
//"directory1"=>$directory1,
//"directory2"=>$directory2,
//"directory3"=>$directory3,
//"directory4"=>$directory4,
//"begtime"=>$begtime
//);
//$request=$Article->add($array); // 实例化Data数据对象
//↓↓↓↓↓↓↓↓↓↓↓利用AR数据添加方法
$Article=D("Home/qs"); // 实例化Data数据对象
$Article->title=$title;
$Article->picurl=$picurl;
$Article->content=$content;
$Article->directory1=$directory1;
$Article->directory2=$directory2;
$Article->directory3=$directory3;
$Article->directory4=$directory4;
$Article->begtime=begtime();
$request=$Article->add();
$Article->where('id='.$request)->save(array("sorting"=>$request));
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑利用AR数据添加方法
if ($request>0){
$msg="<div class='Yoerror3'>操作成功!<br>系统将在 <span id=\"mes\">3</span> 秒钟后返回!</div>";
echo json_encode(array("msg"=>$msg,"error"=>0));
}else{
$msg="<div class='Yoerror1'>操作失败!产生错误的原因:可能是您没有输入信息<br>系统将在 <span id=\"mes\">3</span> 秒钟后返回!</div>";
echo json_encode(array("msg"=>$msg,"error"=>1));
}
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑以上开始数据的更新
}
}
//↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓利用AR方法执行数据的修改
public function qs_info_edit(){
if ($_POST['Action']==''){
$id=I('get.Id',0,'intval');######安全模式过滤获取标签
$Article=D("Home/qs")->find($id); ###实例化Data数据对象
$this->assign('info',$Article); ######赋值Id
$this->display();
}elseif($_POST['Action']=='Edit'){
$Id=I('post.Id',0,'intval'); ######安全模式过滤获取标签
$title=I('post.title','','strip_tags'); ######安全模式过滤获取标题
$picurl=I('post.path','','strip_tags'); ######安全模式过滤获取标题
$ClassID=I('post.ClassID','','strip_tags'); ######安全模式过滤获取标题
$directory1=substr($ClassID,0,4); ######文章一级栏目
$directory2=substr($ClassID,0,8); ######文章二级栏目
$directory3=substr($ClassID,0,12); ######文章三级栏目
$directory4=substr($ClassID,0,16); ######文章四级栏目
$content=$_POST['content']; ###内容
$Article=D("Home/qs"); ###实例化Data数据对象
$Article->title=I('post.title','','strip_tags');
$Article->picurl=$picurl;
$Article->content=$content;
$Article->directory1=$directory1;
$Article->directory2=$directory2;
$Article->directory3=$directory3;
$Article->directory4=$directory4;
$begtime->begtime=$begtime;
$request=$Article->where('id='.$Id)->save();
if ($request>0){
$msg="<div class='Yoerror3'>操作成功!<br>系统将在 <span id=\"mes\">3</span> 秒钟后返回!</div>";
echo json_encode(array("msg"=>$msg,"error"=>0));
}else{
$msg="<div class='Yoerror1'>操作失败!产生错误的原因:可能是您没有输入信息<br>系统将在 <span id=\"mes\">3</span> 秒钟后返回!</div>";
echo json_encode(array("msg"=>$msg,"error"=>1));
}
}
}
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑以上开始数据的修改
//↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓执行数据的删除
public function qs_infodelete(){
$id=$_POST['id'];
$Article=D("Home/qs"); ###实例化Data数据对象
if ($_POST['Action']=='del'){
$request=$Article->where('id='.$id)->delete();
}else{
$request=$Article->where(array('id'=>array('in',$id)))->delete();
}
if ($request>0){
$msg="<div class='Yoerror3'>操作成功!<br>系统将在 <span id=\"mes\">3</span> 秒钟后返回!</div>";
echo json_encode(array("msg"=>$msg,"error"=>0));
}else{
$msg="<div class='Yoerror1'>操作失败!产生错误的原因:可能该信息已经被删除<br>系统将在 <span id=\"mes\">3</span> 秒钟后返回!</div>";
echo json_encode(array("msg"=>$msg,"error"=>1));
}
}
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑以上开始数据的删除
public function qs_directory(){
$NumberID=I('get.NumberID','','strip_tags');
$NumberID1 = substr ("$NumberID",0,4);
$NumberID2 = substr ("$NumberID",0,8);
$NumberID3 = substr ("$NumberID",0,12);
$NumberID4 = substr ("$NumberID",0,16);
$len=strlen($NumberID);
$this->assign('len',$len);
$this->assign('NumberID',$NumberID);
$this->assign('NumberID1',$NumberID1);
$this->assign('NumberID2',$NumberID2);
$this->assign('NumberID3',$NumberID3);
$this->assign('NumberID4',$NumberID4);
$this->display();
}
//----------------------图库期数管理结束----------------------------
public function _empty(){
echo "<div style='text-align:center;width:100%;padding-top:100px;float:left'><img src='".IMG_URL."404.png'></div>";
}
}<file_sep>/ionicTestDemo/js/indexedDB/indexedDB.js
/**
* Created by a1 on 2017/7/18.
*/
/**
* 创建数据库操作对象
*/
function indexedDBF() {
var request = null;
var transaction = null;
var db = null;
};
/* =====================兼容性处理=============================*/
window.indexedDBF = indexedDBF;
/**
*
* @returns {*}
*/
indexedDBF.prototype.createIndexeDB = function () {
var indexed_DB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
if (indexed_DB) {
console.log(indexed_DB)
return indexed_DB;
} else {
console.log('此浏览器不支持indexedDB');
return 0;
}
};
/**
*
* @returns {*}
*/
indexedDBF.prototype.createIDBTransaction = function () {
var IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
if (IDBTransaction) {
console.log(IDBTransaction)
return IDBTransaction;
} else {
console.log('此浏览器不支持IDBTransaction')
return 0;
}
};
/**
*
* @returns {*}
*/
indexedDBF.prototype.createIDBKeyRange = function () {
var IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
if (IDBKeyRange) {
console.log(IDBKeyRange)
return IDBKeyRange;
} else {
return 0;
}
}
/*=========================== 获取对应的indexedDB对象=================================*/
/**
*检测浏览器是否支持indexedDB
* @returns {undefined}
* @ 成功则返回一个indexedDB对象
*/
indexedDBF.prototype.createIndexedDBObject = function () {
debugger
if (this.createIndexeDB()) {
return this.createIndexeDB();
} else if (this.createIDBKeyRange()) {
return this.createIDBKeyRange();
} else if (this.createIDBTransaction()) {
return this.createIDBTransaction();
} else {
console.log('此浏览器不支持indexedDB操作')
return undefined;
}
}
/**
* 开启数据库连接,获取IDBDatabase对象的实例。
* @param indexedDBObj
* @param databaseName
* @param versionNumber
*/
indexedDBF.prototype.openDatabase = function (indexedDBObj, databaseName, versionNumber) {
debugger
if (indexedDBObj && databaseName) {
if (versionNumber) {
this.request = indexedDBObj.open(databaseName, versionNumber);
} else {
this.request = indexedDBObj.open(databaseName);
}
} else {
console.log('打开数据库失败');
return 0;
}
}
/**
* 为request对象绑定处理事务的函数
* @param method
* @param methodName
* @returns {number}
*/
indexedDBF.prototype.addEventMethod = function (method, methodName) {
debugger
if (this.request && method && methodName) {
this.request[methodName] = method;
} else {
console.log("绑定函数失败")
return 0;
}
}
/**
* 添加数据失败后的返回值
* @param event 事件对象
* @param customerData 即将向数据库对象添加的数据
* @param customers 控制事务操作范围的array
* @param readwrite 控制事务的操作权限
* @param keyPath 数据存储的空间名称
* @param setUnique 创建索引的方法
* @param addDatabases 向数据库对象添加数据的方法
* @param addTransaction 向result对象添加事务的方法
* @returns {number} 事件处理失败后的返回值
*/
/**
* 请求数据失败后的处理函数
* @param event
* @returns {Number}
*/
indexedDBF.prototype.errorMethod = function (event) {
return this.request.errorCode;
}
/**
* 请求数据成功后的处理函数
* @param event
* @returns {Object}
*/
indexedDBF.prototype.successMethod = function (event) {
var $this = this;
//console.log(this)
};
/**
* 创建数据索引
* @param objectStore
* @param customerData
*/
indexedDBF.prototype.setUnique = function (objectStore, customerData) {
// 创建一个索引来通过 name 搜索客户。
// 可能会有重复的,因此我们不能使用 unique 索引。
//objectStore.createIndex("name", "name", { unique: false });
// 创建一个索引来通过 email 搜索客户。
// 我们希望确保不会有两个客户使用相同的 email 地址,因此我们使用一个 unique 索引。
//objectStore.createIndex("email", "email", { unique: true });
for (var i in customerData) {
if (i == 'email') {
objectStore.createIndex(i, i, {unique: true})
}
}
}
/**
* 使用add()方法先对象存储空间添加数据
* @param objectStore
* @param customerData
*/
indexedDBF.prototype.addDatabases = function (objectStore, customerData) {
// 在新创建的对象存储空间中保存值
for (var i in customerData) {
objectStore.add(customerData[i]);
}
}
/**
* 使用put方法向对象存储空间添加数据
* @param objectStore
* @param customerData
*/
indexedDBF.prototype.usePutDatabase = function (objectStore, customerData) {
for (var i in customerData) {
objectStore.put(i, customerData[i]);
}
}
/**
*添加事务
* @param db 数据库对象
* @param readwrite 设定事务操作类型限制
*/
//var transaction = db.transaction(["customers"], "readwrite");
indexedDBF.prototype.addTransaction = function (db, array, readwrite) {
if (db) {
if (readwrite) {
this.transaction = db.transaction(array, readwrite)
} else {
if (window.IDBTransaction) {
this.transaction = db.transaction(array, IDBTransaction.READ_WRITE)
}
}
} else {
return
}
}
/****************************** transaction *******************************/
/**
* 当所有的数据都被增加到数据库时执行一些操作
* @param event
*/
indexedDBF.prototype.complateMethod = function (event) {
console.log('添加数据已完毕');
}
/**
*
* @param event
*/
indexedDBF.prototype.toTranErrorMethod = function (event) {
console.log('添加数据失败');
}
/**
*
* @param key
*/
indexedDBF.prototype.deleteData = function (key) {
if (this.transaction) {
var objectStore = this.transaction.objectStore("customers");
var request = objectStore.delete(key);
}
}
/**
* 向数据库对象添加一个错误处理程序
* @param method 方法
* @param methodName 方法名
* @如上文所述,错误事件冒泡出来。错误事件都是针对产生这些错误的请求的,然后事件冒泡到事务,然后最终到达数据库对象。如果你希望避免为所有的请求都增加错误处理程序,你可以替代性的仅对数据库对象添加一个错误处理程序
*/
indexedDBF.prototype.resultAddMethods = function (method, methodName) {
debugger;
var db = this.result;
db[methodName] = method;
}
/**
* 数据库对象的错误处理程序
* @param event
*/
indexedDBF.prototype.dbErrorFuc = function (event) {
// Generic error handler for all errors targeted at this database's
// requests!
alert("Database error: " + event.target.errorCode);
};
indexedDBF.prototype.initIndexedDB = function (customerData, dbName, version, customers, readwrite, keyPath) {
debugger
var request=null;
var db=null;
if (!window.indexedDB) {
window.alert("Your browser doesn't support a stable version of IndexedDB. Such and such feature will not be available.")
}
/* $this.request=$this.openDatabase(indexedDB,dbName,version);*/
// In the following line, you should include the prefixes of implementations you want to test.
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
// DON'T use "var indexedDB = ..." if you're not in a function.
// Moreover, you may need references to some window.IDB* objects:
if(!window.indexedDB){
window.indexedDB= window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
}
if(!window.indexedDB){
window.indexedDB= window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange
}
if(window.indexedDB){
request=window.indexedDB.open("MyTestDatabase");
}
request.onerror = function(event) {
// Do something with request.errorCode!
console.log(event.errorCode)
alert(event.errorCode)
};
request.onsuccess = function(event) {
// Do something with request.result!
db=request.result;
db.onerror = function(event) {
// Generic error handler for all errors targeted at this database's
// requests!
alert("Database error: " + event.target.errorCode);
};
};
request.onupgradeneeded = function (event) {
debugger
var db = event.target.result;
// 注意: 旧版实验性的实现使用不建议使用的常量 IDBTransaction.READ_WRITE 而不是 "readwrite"。
// 如果你想支持这样的实现,你只要这样写就可以了:
// var transaction = db.transaction(["customers"], IDBTransaction.READ_WRITE);
var transaction = db.transaction(customers, readwrite);
// 当所有的数据都被增加到数据库时执行一些操作
transaction.oncomplete = function (event) {
alert("All done!");
};
transaction.onerror = function (event) {
// 不要忘记进行错误处理!
};
var objectStore = transaction.objectStore("customers");
for (var i in customerData) {
var request = objectStore.add(customerData[i]);
request.onsuccess = function (event) {
// event.target.result == customerData[i].ssn
};
}
// 创建一个索引来通过 name 搜索客户。
// 可能会有重复的,因此我们不能使用 unique 索引。
// 创建一个对象存储空间来持有有关我们客户的信息。
// 我们将使用 "ssn" 作为我们的 key path 因为它保证是唯一的。
/*
var objectStore = db.createObjectStore("customers", {keyPath: keyPath});
objectStore.createIndex("name", "name", {unique: false});
*/
// 创建一个索引来通过 email 搜索客户。
// 我们希望确保不会有两个客户使用相同的 email 地址,因此我们使用一个 unique 索引。
/*
objectStore.createIndex("email", "email", {unique: true});
*/
// 在新创建的对象存储空间中保存值
/*
for (var i in customerData) {
objectStore.add(customerData[i]);
}
*/
}
}
<file_sep>/tp5/application/admin/controller/auth.php
<?php
namespace app\admin\controller;
class Auth extends Common{
public function __construct()
{
parent::__construct();
}
public function index()
{
$list=db('auth')->limit(0,10)->select();
return view('',['list'=>$list]);
}
public function add()
{
if(IS_POST){
}else{
return view();
}
}
}
<file_sep>/ci/app/config/ww.php
<?php
/**
* Created by PhpStorm.
* User: ww
* Date: 2017/7/7
* Time: 下午9:01
*/
//相关常量配置
//define('ACTION',get_instance()->router->method);//当前方法
//define('CONTROLLER',get_instance()->router->class);//当前控制器
//define('MODULE',get_instance()->router->directory ? get_instance()->router->directory:'');//当前模块
define('REQUEST_METHOD',$_SERVER['REQUEST_METHOD']);
define('IS_GET', REQUEST_METHOD =='GET' ? true : false);
define('IS_POST', REQUEST_METHOD =='POST' ? true : false);
define('IS_AJAX', ((isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') || !empty($_POST['ajax']) || !empty($_GET['ajax'])) ? true : false);
defined('SOCKET_SERVER') OR define('SOCKET_SERVER','127.0.0.1');
defined('SOCKET_PORT') OR define('SOCKET_PORT',1883);
//redis缓存相关参数
const MUST_LOGIN_TIME_INTERVAL=30*24*3600;//规定多长时间必须登陆一次
const MAX_LIFE_TIME=10*24*3600;//token有效期
const MAX_OFF_TIME=15*60;//最大离线时间
const MAX_ERROR_TIMES=8;//密码输入最大错误次数
/*密钥*/
const TOKEN_PRIVATE_ADMIN_KEY = 123456;// 管理员token密钥
const TOKEN_PRIVATE_USER_KEY = 234567;// 会员token密钥
const TOKEN_CODE_AUTH = 'AuthToken';//后台
const TOKEN_CODE_ADMIN = 'Admin';//管理员
const TOKEN_CODE_USER = 'User';//会员
<file_sep>/ci/app/controllers/test.php
<?php
/**
* Created by PhpStorm.
* User: ww
* Date: 2017/7/10
* Time: 上午11:33
*/
class Test extends MY_Controller {
public function index(){
$rs=$this->db->get('admin')->result_array();
header("Content-Type:application/json;charset=utf-8");
echo json_encode($rs);
}
public function mqtt()
{
$this->push('ww','您的账号已在其他地方登陆');
}
}<file_sep>/README.md
# Angular4.0
这是一个学习练习使用的项目
<file_sep>/ci/app/helpers/token_helper.php
<?php
/**
* Created by PhpStorm.
* User: ww
* Date: 2017/7/9
* Time: 上午2:00
*/
if (!function_exists('token_encrypt')) {
/**
* 加密
* @param string $token 需要被加密的数据
* @param string $private_key 密钥
* @return string
*/
function token_encrypt($token='',$private_key='')
{
return base64_encode(openssl_encrypt($token, 'BF-CBC', md5($private_key), null, substr(md5($private_key), 0, 8)));
//return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($private_key), $token, MCRYPT_MODE_CBC, md5(md5($private_key))));
}
}
if (!function_exists('token_decrypt')) {
/**
* 解密
* @param string $en_token 加密数据
* @param string $private_key 密钥
* @return string
*/
function token_decrypt($en_token='',$private_key='')
{
return rtrim(openssl_decrypt(base64_decode($en_token), 'BF-CBC', md5($private_key), 0, substr(md5($private_key), 0, 8)));
//return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($private_key), base64_decode($en_token), MCRYPT_MODE_CBC, md5(md5($private_key))), "\0");
}
}<file_sep>/tp5/runtime/temp/54eb4e54ef9f057a1248487abf8559ae.php
<?php if (!defined('THINK_PATH')) exit(); /*a:1:{s:79:"/Applications/MAMP/htdocs/tp5/public/../application/admin/view/index/index.html";i:1500200750;}*/ ?>
<!DOCTYPE html>
<html>
<head>
<meta name="renderer" content="webkit|ie-comp|ie-stand" />
<meta charset="UTF-8">
<title>后台管理系统</title>
<link rel="stylesheet" href="static/css/font-icons/entypo/css/entypo.css">
<link rel="stylesheet" type="text/css" href="static/js/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="static/js/layout/themes/bootstrap/easyui.css">
<link rel="stylesheet" type="text/css" href="static/js/layout/themes/icon.css">
<link rel="stylesheet" type="text/css" href="static/css/buttons.css">
<link rel="stylesheet" type="text/css" href="static/css/animate.css">
<link rel="stylesheet" type="text/css" href="static/css/core.css">
<link rel="stylesheet" type="text/css" href="static/css/themes/red.css" id="colorIn">
<script type="text/javascript" src="static/js/jquery.min.js"></script>
<script>
var MQ_HOST = '<?php echo MQ_HOST?>';
var MQ_PORT = '<?php echo MQ_PORT?>';
</script>
<script type="text/javascript" src="static/js/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="static/js/layout/jquery.easyui.min.js"></script>
<script type="text/javascript" src="static/js/layout/locale/easyui-lang-zh_CN.js"></script>
<script type="text/javascript" src="static/js/core.js"></script>
<style>
.themes{padding:5px 10px 5px 5px;margin-left: 10px;}
.zi{background: #5823CB;}
.red{background: #F15757;}
.huang{background: #FAAC3D;}
.liu{background: #52B058;}
</style>
</head>
<body class="easyui-layout">
<div data-options="region:'north',border:false" style="height:110px;overflow: hidden;border:none;" class="animated bounceInDown">
<div style="width: 100%; min-width: 1000px;">
<div style="padding:5px;float:left; overflow: hidden;">
<span class="glyphicon glyphicon-bullhorn"></span> 公告:欢迎进入后台管理系统!
<!--<span>
<a href="tencent://message/?uin=3120491793&Site=web&Menu=yes" style="font-weight: bold;">
<img src="static/images/qq.png" width="20"> 技术支持1</a>
</span>
<span>
<a href="tencent://message/?uin=2382573731&Site=web&Menu=yes" style="font-weight: bold;">
<img src="static/images/qq.png" width="20"> 技术支持2</a>
</span>
<span>
<a href="tencent://message/?uin=2070510353&Site=web&Menu=yes" style="font-weight: bold;">
<img src="static/images/qq.png" width="20"> 技术支持3</a>
</span>
<span>
<a href="tencent://message/?uin=1219188813&Site=web&Menu=yes" style="font-weight: bold;">
<img src="static/images/qq.png" width="20"> 技术支持4</a>
</span>
<span>
<a href="tencent://message/?uin=3446239944&Site=web&Menu=yes" style="font-weight: bold;">
<img src="static/images/qq.png" width="20"> 投诉建议</a>
</span>-->
</div>
<div style="padding:5px; float: right;">
<span>
<a href="javascript:;" class="themes zi" onclick="change('zi')"></a>
<a href="javascript:;" class="themes red" onclick="change('red')"></a>
<a href="javascript:;" class="themes huang" onclick="change('huang')"></a>
<a href="javascript:;" class="themes liu" onclick="change('liu')"></a>
</span>
<span id="Clock"></span>
<span>在线人数:<b style="color:red" class="online">0</b> </span>
<span>今日注册:<b style="color:red" class="bank_name">0</b> </span>
<a href="javascript:;" title="刷新在线人数" onclick="refreshUserCount()"><span class="glyphicon glyphicon-refresh"></span></a>
<!-- <span>平台额度:<b style="color:red"></b> </span> -->
<span>登录帐号:
<a href="javascript:;" style="color:#069" onClick="Core.dialog('修改密码','',function(){},true,false);">修改密码</a>
<a href="javascript:;" style="color:#069" onClick="Core.exit();">退出</a>
</span>
</div>
</div>
<div style="clear:both"></div>
<div class="top-menu" id="menuList">
</div>
<div id="submenu"></div>
</div>
<div data-options="region:'center',title:''" class="animated rotateInDownRight">
<div id="task" class="easyui-tabs" data-options="fit:true,tools:[{iconCls:'icon-reload',handler:function(){Core.refresh();}},{iconCls:'icon-no',handler:function(){Core.exit();}}]">
<div title="开始页" data-options="href:'welcome/start',closable:false"></div>
<!--welcome/start stats/order-->
</div>
</div>
<div id="mm" class="easyui-menu">
<div onClick="Core.refresh()">刷新</div>
<div onClick="Core.closeCurrent()">关闭当前页</div>
<div onClick="Core.closeOthers()">关闭其它页</div>
<div onClick="Core.closeAll()">关闭所有页</div>
</div>
<div id="audio" style="display: none"></div>
<script type='text/javascript'>
function change(a){
var css=document.getElementById('colorIn');
css.setAttribute('href','static/css/themes/'+a+'.css');
}
function refreshUserCount() {
$.getJSON(WEB+'login/user_count',function(c){
if(c.code == 200){
$('.online').html('');
$('.bank_name').html('');
$('.online').html(c.data['online']);
$('.bank_name').html(c.data['bank_name']);
}
});
}
</script>
<SCRIPT language=JavaScript>
function tick() {
var years, months, days, hours, minutes, seconds;
var intYears, intMonths, intDays, intHours, intMinutes, intSeconds;
var today;
today = new Date(); //系统当前时间
intYears = today.getFullYear(); //得到年份,getFullYear()比getYear()更普适
intMonths = today.getMonth() + 1; //得到月份,要加1
intDays = today.getDate(); //得到日期
intHours = today.getHours(); //得到小时
intMinutes = today.getMinutes(); //得到分钟
intSeconds = today.getSeconds(); //得到秒钟
years = intYears + "-";
if (intMonths < 10) {
months = "0" + intMonths + "-";
} else {
months = intMonths + "-";
}
if (intDays < 10) {
days = "0" + intDays + " ";
} else {
days = intDays + " ";
}
if (intHours == 0) {
hours = "00:";
} else if (intHours < 10) {
hours = "0" + intHours + ":";
} else {
hours = intHours + ":";
}
if (intMinutes < 10) {
minutes = "0" + intMinutes + ":";
} else {
minutes = intMinutes + ":";
}
if (intSeconds < 10) {
seconds = "0" + intSeconds + " ";
} else {
seconds = intSeconds + " ";
}
timeString = years + months + days + hours + minutes + seconds;
Clock.innerHTML = timeString;
window.setTimeout("tick();", 1000);
}
window.onload = tick;
</SCRIPT>
</body>
</html>
<file_sep>/admin/Admin/Runtime/Cache/Home/6635c2708068778cffc11a391431271a.php
<?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta charset="utf-8" />
<title>Wmzz-Lhc网站后台系统管理</title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<!-- bootstrap & fontawesome -->
<link rel="stylesheet" href="/lh3/Public/js/assets/css/bootstrap.css" />
<link rel="stylesheet" href="/lh3/Public/js/assets/css/font-awesome.css" />
<link rel="stylesheet" href="/lh3/Public/css/font-awesome.min.css" />
<!-- ace styles -->
<link rel="stylesheet" href="/lh3/Public/js/assets/css/ace.css" class="ace-main-stylesheet" id="main-ace-style" />
<!--[if lte IE 9]>
<link rel="stylesheet" href="/lh3/Public/js/assets/css/ace-part2.css" class="ace-main-stylesheet" />
<![endif]-->
<!--[if lte IE 9]>
<link rel="stylesheet" href="/lh3/Public/js/assets/css/ace-ie.css" />
<![endif]-->
<!-- inline styles related to this page -->
<link rel="stylesheet" href="/lh3/Public/js/assets/css/slackck.css" />
<!-- ace settings handler -->
<script src="/lh3/Public/js/assets/js/ace-extra.js"></script>
<script src="/lh3/Public/js/assets/js/jquery.min.js"></script>
<script src="/lh3/Public/js/assets/js/jquery.form.js"></script>
<script src="/lh3/Public/js/assets/layer/layer.js"></script>
<!--<script src="<?php echo (JS_URL); ?>/assets/js/jquery.leanModal.min.js"></script>-->
<!--[if lte IE 8]>
<script src="/lh3/Public/js/assets/js/html5shiv.js"></script>
<script src="/lh3/Public/js/assets/js/respond.js"></script>
<![endif]-->
</head>
<body class="no-skin">
<!-- #section:basics/navbar.layout -->
<div id="navbar" class="navbar navbar-default navbar-collapse">
<script type="text/javascript">
try{ace.settings.check('navbar' , 'fixed')}catch(e){}
</script>
<div class="navbar-container" id="navbar-container">
<!-- #section:basics/sidebar.mobile.toggle -->
<button type="button" class="navbar-toggle menu-toggler pull-left" id="menu-toggler" data-target="#sidebar">
<span class="sr-only">Toggle sidebar</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<!-- /section:basics/sidebar.mobile.toggle -->
<div class="navbar-header pull-left">
<!-- #section:basics/navbar.layout.brand -->
<a href="<?php echo U('Index/index');?>" class="navbar-brand">
<small>
<i class="fa fa-leaf"></i>
Wmzz-Lhc
</small>
</a>
<!-- /section:basics/navbar.layout.brand -->
<!-- #section:basics/navbar.toggle -->
<button class="pull-right navbar-toggle navbar-toggle-img collapsed" type="button" data-toggle="collapse" data-target=".navbar-buttons">
<span class="sr-only">Toggle user menu</span>
<img src="/lh3/Public/js/assets/avatars/user.jpg" alt="Jason's Photo" />
</button>
<!-- /section:basics/navbar.toggle -->
</div>
<!-- #section:basics/navbar.dropdown -->
<div class="navbar-buttons navbar-header pull-right collapse navbar-collapse" role="navigation">
<ul class="nav ace-nav">
<li class="transparent"></li>
<li class="transparent">
<a style="cursor:pointer;" id="cache" class="dropdown-toggle">清除缓存</a>
</li>
<!-- #section:basics/navbar.user_menu -->
<li class="light-blue">
<a data-toggle="dropdown" href="#" class="dropdown-toggle">
<img class="nav-user-photo" src="/lh3/Public/js/assets/avatars/user.jpg" alt="Jason's Photo" />
<span class="user-info">
<small>管理员</small>
<?php echo ($_SESSION['admin_username']); ?>
</span>
<i class="ace-icon fa fa-caret-down"></i>
</a>
<ul class="user-menu dropdown-menu-right dropdown-menu dropdown-yellow dropdown-caret dropdown-close">
<li class="divider"></li>
<li>
<a href="javascript:;" id="logout">
<i class="ace-icon fa fa-power-off"></i>
注销
</a>
</li>
</ul>
</li>
<!-- /section:basics/navbar.user_menu -->
</ul>
</div>
<!-- /section:basics/navbar.dropdown -->
</div><!-- /.navbar-container -->
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#logout").click(function(){
layer.confirm('你确定要退出吗?', {icon: 3}, function(index){
layer.close(index);
window.location.href="<?php echo U('Administrator/logout');?>";
});
});
});
$(function(){
$('#cache').click(function(){
if(confirm("确认要清除缓存?")){
var $type=$('#type').val();
var $mess=$('#mess');
$.post('/lh3/index.php/Home/Caiji/clear',{type:$type},function(data){
alert("缓存清理成功");
});
}else{
return false;
}
});
});
</script>
<style>
table{border-collapse:collapse;border-spacing:0;}
td,th{padding:0;}
.label,.badge {
display: inline-block;
padding: 2px 4px;
font-size: 11.844px;
font-weight: bold;
line-height: 14px;
color: #fff;
text-shadow: 0 -1px 0 rgba(0,0,0,0.25);
white-space: nowrap;
vertical-align: baseline;
background-color: #999
}
.label {
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px
}
button.close {
padding: 0;
cursor: pointer;
background: transparent;
border: 0;
-webkit-appearance: none
}
.btn {
display: inline-block;
*display: inline;
padding: 4px 12px;
margin-bottom: 0;
*margin-left: .3em;
font-size: 14px;
line-height: 20px;
color: #333;
text-align: center;
text-shadow: 0 1px 1px rgba(255,255,255,0.75);
vertical-align: middle;
cursor: pointer;
background-color: #f5f5f5;
*background-color: #e6e6e6;
background-image: -moz-linear-gradient(top,#fff,#e6e6e6);
background-image: -webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));
background-image: -webkit-linear-gradient(top,#fff,#e6e6e6);
background-image: -o-linear-gradient(top,#fff,#e6e6e6);
background-image: linear-gradient(to bottom,#fff,#e6e6e6);
background-repeat: repeat-x;
border: 1px solid #ccc;
*border: 0;
border-color: #e6e6e6 #e6e6e6 #bfbfbf;
border-color: rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);
border-bottom-color: #b3b3b3;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
*zoom: 1;
-webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);
-moz-box-shadow: inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);
box-shadow: inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05)
}
.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled] {
color: #333;
background-color: #e6e6e6;
*background-color: #d9d9d9
}
.btn:active,.btn.active {
background-color: #ccc \9
}
.btn:first-child {
*margin-left: 0
}
.btn:hover,.btn:focus {
color: #333;
text-decoration: none;
background-position: 0 -15px;
-webkit-transition: background-position .1s linear;
-moz-transition: background-position .1s linear;
-o-transition: background-position .1s linear;
transition: background-position .1s linear
}
.btn:focus {
outline: thin dotted #333;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px
}
.btn.active,.btn:active {
background-image: none;
outline: 0;
-webkit-box-shadow: inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);
-moz-box-shadow: inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);
box-shadow: inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)
}
.btn.disabled,.btn[disabled] {
cursor: default;
background-image: none;
opacity: .65;
filter: alpha(opacity=65);
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none
}
.btn-large {
padding: 11px 19px;
font-size: 17.5px;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px
}
.btn-large [class^="icon-"],.btn-large [class*=" icon-"] {
margin-top: 4px
}
.btn-small {
padding: 2px 10px;
font-size: 11.9px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px
}
.btn-small [class^="icon-"],.btn-small [class*=" icon-"] {
margin-top: 0
}
.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"] {
margin-top: -1px
}
.btn-mini {
padding: 0 6px;
font-size: 10.5px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px
}
.btn-block {
display: block;
width: 100%;
padding-right: 0;
padding-left: 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box
}
.btn-block+.btn-block {
margin-top: 5px
}
input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block {
width: 100%
}
.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active {
color: rgba(255,255,255,0.75)
}
.btn-primary {
color: #fff;
text-shadow: 0 -1px 0 rgba(0,0,0,0.25);
background-color: #006dcc;
*background-color: #04c;
background-image: -moz-linear-gradient(top,#08c,#04c);
background-image: -webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));
background-image: -webkit-linear-gradient(top,#08c,#04c);
background-image: -o-linear-gradient(top,#08c,#04c);
background-image: linear-gradient(to bottom,#08c,#04c);
background-repeat: repeat-x;
border-color: #04c #04c #002a80;
border-color: rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false)
}
.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled] {
color: #fff;
background-color: #04c;
*background-color: #003bb3
}
.btn-primary:active,.btn-primary.active {
background-color: #039 \9
}
.btn-warning {
color: #fff;
text-shadow: 0 -1px 0 rgba(0,0,0,0.25);
background-color: #faa732;
*background-color: #f89406;
background-image: -moz-linear-gradient(top,#fbb450,#f89406);
background-image: -webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));
background-image: -webkit-linear-gradient(top,#fbb450,#f89406);
background-image: -o-linear-gradient(top,#fbb450,#f89406);
background-image: linear-gradient(to bottom,#fbb450,#f89406);
background-repeat: repeat-x;
border-color: #f89406 #f89406 #ad6704;
border-color: rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false)
}
.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.btn-warning.disabled,.btn-warning[disabled] {
color: #fff;
background-color: #f89406;
*background-color: #df8505
}
.btn-warning:active,.btn-warning.active {
background-color: #c67605 \9
}
.btn-danger {
color: #fff;
text-shadow: 0 -1px 0 rgba(0,0,0,0.25);
background-color: #da4f49;
*background-color: #bd362f;
background-image: -moz-linear-gradient(top,#ee5f5b,#bd362f);
background-image: -webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));
background-image: -webkit-linear-gradient(top,#ee5f5b,#bd362f);
background-image: -o-linear-gradient(top,#ee5f5b,#bd362f);
background-image: linear-gradient(to bottom,#ee5f5b,#bd362f);
background-repeat: repeat-x;
border-color: #bd362f #bd362f #802420;
border-color: rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b',endColorstr='#ffbd362f',GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false)
}
.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.btn-danger.disabled,.btn-danger[disabled] {
color: #fff;
background-color: #bd362f;
*background-color: #a9302a
}
.btn-danger:active,.btn-danger.active {
background-color: #942a25 \9
}
.btn-success {
color: #fff;
text-shadow: 0 -1px 0 rgba(0,0,0,0.25);
background-color: #5bb75b;
*background-color: #51a351;
background-image: -moz-linear-gradient(top,#62c462,#51a351);
background-image: -webkit-gradient(linear,0 0,0 100%,from(#62c462),to(#51a351));
background-image: -webkit-linear-gradient(top,#62c462,#51a351);
background-image: -o-linear-gradient(top,#62c462,#51a351);
background-image: linear-gradient(to bottom,#62c462,#51a351);
background-repeat: repeat-x;
border-color: #51a351 #51a351 #387038;
border-color: rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462',endColorstr='#ff51a351',GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false)
}
.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.btn-success.disabled,.btn-success[disabled] {
color: #fff;
background-color: #51a351;
*background-color: #499249
}
.btn-success:active,.btn-success.active {
background-color: #408140 \9
}
.btn-info {
color: #fff;
text-shadow: 0 -1px 0 rgba(0,0,0,0.25);
background-color: #49afcd;
*background-color: #2f96b4;
background-image: -moz-linear-gradient(top,#5bc0de,#2f96b4);
background-image: -webkit-gradient(linear,0 0,0 100%,from(#5bc0de),to(#2f96b4));
background-image: -webkit-linear-gradient(top,#5bc0de,#2f96b4);
background-image: -o-linear-gradient(top,#5bc0de,#2f96b4);
background-image: linear-gradient(to bottom,#5bc0de,#2f96b4);
background-repeat: repeat-x;
border-color: #2f96b4 #2f96b4 #1f6377;
border-color: rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de',endColorstr='#ff2f96b4',GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false)
}
.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.btn-info.disabled,.btn-info[disabled] {
color: #fff;
background-color: #2f96b4;
*background-color: #2a85a0
}
.btn-info:active,.btn-info.active {
background-color: #24748c \9
}
.btn-inverse {
color: #fff;
text-shadow: 0 -1px 0 rgba(0,0,0,0.25);
background-color: #363636;
*background-color: #222;
background-image: -moz-linear-gradient(top,#444,#222);
background-image: -webkit-gradient(linear,0 0,0 100%,from(#444),to(#222));
background-image: -webkit-linear-gradient(top,#444,#222);
background-image: -o-linear-gradient(top,#444,#222);
background-image: linear-gradient(to bottom,#444,#222);
background-repeat: repeat-x;
border-color: #222 #222 #000;
border-color: rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff444444',endColorstr='#ff222222',GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false)
}
.btn-inverse:hover,.btn-inverse:focus,.btn-inverse:active,.btn-inverse.active,.btn-inverse.disabled,.btn-inverse[disabled] {
color: #fff;
background-color: #222;
*background-color: #151515
}
.btn-inverse:active,.btn-inverse.active {
background-color: #080808 \9
}
button.btn,input[type="submit"].btn {
*padding-top: 3px;
*padding-bottom: 3px
}
button.btn::-moz-focus-inner,input[type="submit"].btn::-moz-focus-inner {
padding: 0;
border: 0
}
button.btn.btn-large,input[type="submit"].btn.btn-large {
*padding-top: 7px;
*padding-bottom: 7px
}
button.btn.btn-small,input[type="submit"].btn.btn-small {
*padding-top: 3px;
*padding-bottom: 3px
}
button.btn.btn-mini,input[type="submit"].btn.btn-mini {
*padding-top: 1px;
*padding-bottom: 1px
}
.btn-link,.btn-link:active,.btn-link[disabled] {
background-color: transparent;
background-image: none;
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none
}
.btn-link {
color: #08c;
cursor: pointer;
border-color: transparent;
-webkit-border-radius: 0;
-moz-border-radius: 0;
border-radius: 0
}
.btn-link:hover,.btn-link:focus {
color: #005580;
text-decoration: underline;
background-color: transparent
}
.btn-link[disabled]:hover,.btn-link[disabled]:focus {
color: #333;
text-decoration: none
}
.btn-group {
position: relative;
display: inline-block;
*display: inline;
*margin-left: .3em;
font-size: 0;
white-space: nowrap;
vertical-align: middle;
*zoom: 1
}
.btn-group:first-child {
*margin-left: 0
}
.btn-group+.btn-group {
margin-left: 5px
}
.btn-toolbar {
margin-top: 10px;
margin-bottom: 10px;
font-size: 0
}
.btn-toolbar>.btn+.btn,.btn-toolbar>.btn-group+.btn,.btn-toolbar>.btn+.btn-group {
margin-left: 5px
}
.btn-group>.btn {
position: relative;
-webkit-border-radius: 0;
-moz-border-radius: 0;
border-radius: 0
}
.btn-group>.btn+.btn {
margin-left: -1px
}
.btn-group>.btn,.btn-group>.dropdown-menu,.btn-group>.popover {
font-size: 14px
}
.btn-group>.btn-mini {
font-size: 10.5px
}
.btn-group>.btn-small {
font-size: 11.9px
}
.btn-group>.btn-large {
font-size: 17.5px
}
.btn-group>.btn:first-child {
margin-left: 0;
-webkit-border-bottom-left-radius: 4px;
border-bottom-left-radius: 4px;
-webkit-border-top-left-radius: 4px;
border-top-left-radius: 4px;
-moz-border-radius-bottomleft: 4px;
-moz-border-radius-topleft: 4px
}
.btn-group>.btn:last-child,.btn-group>.dropdown-toggle {
-webkit-border-top-right-radius: 4px;
border-top-right-radius: 4px;
-webkit-border-bottom-right-radius: 4px;
border-bottom-right-radius: 4px;
-moz-border-radius-topright: 4px;
-moz-border-radius-bottomright: 4px
}
.btn-group>.btn.large:first-child {
margin-left: 0;
-webkit-border-bottom-left-radius: 6px;
border-bottom-left-radius: 6px;
-webkit-border-top-left-radius: 6px;
border-top-left-radius: 6px;
-moz-border-radius-bottomleft: 6px;
-moz-border-radius-topleft: 6px
}
.btn-group>.btn.large:last-child,.btn-group>.large.dropdown-toggle {
-webkit-border-top-right-radius: 6px;
border-top-right-radius: 6px;
-webkit-border-bottom-right-radius: 6px;
border-bottom-right-radius: 6px;
-moz-border-radius-topright: 6px;
-moz-border-radius-bottomright: 6px
}
.btn-group>.btn:hover,.btn-group>.btn:focus,.btn-group>.btn:active,.btn-group>.btn.active {
z-index: 2
}
.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle {
outline: 0
}
.btn-group>.btn+.dropdown-toggle {
*padding-top: 5px;
padding-right: 8px;
*padding-bottom: 5px;
padding-left: 8px;
-webkit-box-shadow: inset 1px 0 0 rgba(255,255,255,0.125),inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);
-moz-box-shadow: inset 1px 0 0 rgba(255,255,255,0.125),inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);
box-shadow: inset 1px 0 0 rgba(255,255,255,0.125),inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05)
}
.btn-group>.btn-mini+.dropdown-toggle {
*padding-top: 2px;
padding-right: 5px;
*padding-bottom: 2px;
padding-left: 5px
}
.btn-group>.btn-small+.dropdown-toggle {
*padding-top: 5px;
*padding-bottom: 4px
}
.btn-group>.btn-large+.dropdown-toggle {
*padding-top: 7px;
padding-right: 12px;
*padding-bottom: 7px;
padding-left: 12px
}
.btn-group.open .dropdown-toggle {
background-image: none;
-webkit-box-shadow: inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);
-moz-box-shadow: inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);
box-shadow: inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)
}
.btn-group.open .btn.dropdown-toggle {
background-color: #e6e6e6
}
.btn-group.open .btn-primary.dropdown-toggle {
background-color: #04c
}
.btn-group.open .btn-warning.dropdown-toggle {
background-color: #f89406
}
.btn-group.open .btn-danger.dropdown-toggle {
background-color: #bd362f
}
.btn-group.open .btn-success.dropdown-toggle {
background-color: #51a351
}
.btn-group.open .btn-info.dropdown-toggle {
background-color: #2f96b4
}
.btn-group.open .btn-inverse.dropdown-toggle {
background-color: #222
}
.btn .caret {
margin-top: 8px;
margin-left: 0
}
.btn-large .caret {
margin-top: 6px
}
.btn-large .caret {
border-top-width: 5px;
border-right-width: 5px;
border-left-width: 5px
}
.btn-mini .caret,.btn-small .caret {
margin-top: 8px
}
.dropup .btn-large .caret {
border-bottom-width: 5px
}
.btn-primary .caret,.btn-warning .caret,.btn-danger .caret,.btn-info .caret,.btn-success .caret,.btn-inverse .caret {
border-top-color: #fff;
border-bottom-color: #fff
}
.btn-group-vertical {
display: inline-block;
*display: inline;
*zoom: 1
}
.btn-group-vertical>.btn {
display: block;
float: none;
max-width: 100%;
-webkit-border-radius: 0;
-moz-border-radius: 0;
border-radius: 0
}
.btn-group-vertical>.btn+.btn {
margin-top: -1px;
margin-left: 0
}
.btn-group-vertical>.btn:first-child {
-webkit-border-radius: 4px 4px 0 0;
-moz-border-radius: 4px 4px 0 0;
border-radius: 4px 4px 0 0
}
.btn-group-vertical>.btn:last-child {
-webkit-border-radius: 0 0 4px 4px;
-moz-border-radius: 0 0 4px 4px;
border-radius: 0 0 4px 4px
}
.btn-group-vertical>.btn-large:first-child {
-webkit-border-radius: 6px 6px 0 0;
-moz-border-radius: 6px 6px 0 0;
border-radius: 6px 6px 0 0
}
.btn-group-vertical>.btn-large:last-child {
-webkit-border-radius: 0 0 6px 6px;
-moz-border-radius: 0 0 6px 6px;
border-radius: 0 0 6px 6px
}
</style>
<script language="JavaScript">
function openwin(strID)
{
window.open ("/lh3/index.php/Home/Caiji/cjcs/id/"+strID+"", "newwindow", "height=490, width=500, top=170, left=400, toolbar =no, menubar=no, scrollbars=no, resizable=no, location=no, status=no");
}
function openwin1(strID)
{
window.open ("/lh3/index.php/Home/Caiji/cj/id/"+strID+"", "newwindow", "height=490, width=500, top=170, left=400, toolbar =no, menubar=no, scrollbars=no, resizable=no, location=no, status=no");
}
</script>
<link href="<?php echo (CSS_URL); ?>common.css" rel="stylesheet" type="text/css"/>
<div class="main-container" id="main-container">
<div id="sidebar" class="sidebar responsive">
<div class="sidebar-shortcuts" id="sidebar-shortcuts">
<!--左侧顶端按钮-->
<div class="sidebar-shortcuts-large" id="sidebar-shortcuts-large">
<a class="btn btn-success" href="<?php echo U('Article/index');?>" role="button" title="文章列表"><i class="ace-icon fa fa-signal"></i></a>
<a class="btn btn-info" href="<?php echo U('Article/info_add');?>" role="button" title="添加文章"><i class="ace-icon fa fa-pencil"></i></a>
<a class="btn btn-warning" href="<?php echo U('Kaijiang/index');?>" role="button" title="开奖管理"><i class="ace-icon fa fa-users"></i></a>
<a class="btn btn-danger" href="<?php echo U('Sys/sys');?>" role="button" title="站点设置"><i class="ace-icon fa fa-cogs"></i></a>
</div>
<!--左侧顶端按钮(手机)-->
<div class="sidebar-shortcuts-mini" id="sidebar-shortcuts-mini">
<a class="btn btn-success" href="<?php echo U('Article/index');?>" role="button" title="文章列表"></a>
<a class="btn btn-info" href="<?php echo U('Article/info_add');?>" role="button" title="添加文章"></a>
<a class="btn btn-warning" href="<?php echo U('Kaijiang/index');?>" role="button" title="开奖管理"></a>
<a class="btn btn-danger" href="<?php echo U('Sys/sys');?>" role="button" title="站点设置"></a>
</div>
</div>
<ul class="nav nav-list">
<?php use Common\Controller\AuthController; use Think\Auth; $m = M('auth_rule'); $field = 'id,name,title,css'; $data = $m->field($field)->where('pid=0 AND status=1')->order('sort')->select(); $auth = new Auth(); foreach ($data as $k=>$v){ if(!$auth->check($v['name'], $_SESSION['aid']) && $_SESSION['aid'] != 1){ unset($data[$k]); } } ?>
<?php if(is_array($data)): foreach($data as $key=>$v): ?><li class="<?php if(CONTROLLER_NAME == $v['name']): ?>active open<?php endif; ?>"><!--open代表打开状态-->
<a href="#" class="dropdown-toggle">
<i class="menu-icon fa <?php echo ($v["css"]); ?>"></i>
<span class="menu-text">
<?php echo ($v["title"]); ?>
</span>
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<?php $m = M('auth_rule'); $dataa = $m->where(array('pid'=>$v['id'],'menustatus'=>1))->order('sort')->select(); foreach ($dataa as $kk=>$vv){ if(!$auth->check($vv['name'], $_SESSION['aid']) && $_SESSION['aid'] != 1){ unset($dataa[$kk]); } } $id_4=$m->where(array('name'=>CONTROLLER_NAME.'/'.ACTION_NAME,'level'=>4))->field('pid')->find(); if($id_4){ $id_3=$m->where(array('id'=>$id_4['pid'],'level'=>3))->field('pid')->find(); }else{ $id_3=$m->where(array('name'=>CONTROLLER_NAME.'/'.ACTION_NAME,'level'=>3))->field('pid')->find(); if(!$id_3){ $id_2=$m->where(array('name'=>CONTROLLER_NAME.'/'.ACTION_NAME,'level'=>2))->field('id')->find(); $id_3['pid']=$id_2['id']; } } ?>
<?php if(is_array($dataa)): foreach($dataa as $key=>$j): $m = M('auth_rule'); $dataaa = $m->where(array('pid'=>$j['id'],'status'=>1))->order('sort')->select(); foreach ($dataaa as $kkk=>$vvv){ if(!$auth->check($vvv['name'], $_SESSION['aid']) && $_SESSION['aid'] != 1){ unset($dataaa[$kkk]); } } ?>
<li class="<?php if(($_SESSION['se'] == $j['id'])): ?>active<?php endif; ?>">
<a href="<?php echo U($j['name'],array('se'=>$j['id']));?>">
<i class="menu-icon fa fa-caret-right"></i>
<?php echo ($j["title"]); ?>
</a>
<b class="arrow"></b>
</li><?php endforeach; endif; ?>
</ul>
</li><?php endforeach; endif; ?>
</ul><!-- /.nav-list -->
<!-- #section:basics/sidebar.layout.minimize -->
<div class="sidebar-toggle sidebar-collapse" id="sidebar-collapse">
<i class="ace-icon fa fa-angle-double-left" data-icon1="ace-icon fa fa-angle-double-left" data-icon2="ace-icon fa fa-angle-double-right"></i>
</div>
<!-- /section:basics/sidebar.layout.minimize -->
<script type="text/javascript">
try{ace.settings.check('sidebar' , 'collapsed')}catch(e){}
</script>
</div>
<div class="main-content">
<div class="main-content-inner">
<div class="page-content">
<div class="row">
<div class="col-xs-12">
<div>
<div class="formbody">
<table cellspacing="1" cellpadding="0" class="page_table" >
<tr>
<td class="left" style="padding:10px;">
<input type="button" value="采集添加" onclick="location.href='/lh3/index.php/Home/Caiji/info_add.html'" class="btn btn-success" />
</td>
</tr>
</table>
<div id="msg">
<form name="form1" method="post" action="">
<input id="Token" type="hidden" value="">
<table class="table table-striped table-hover">
<thead>
<tr>
<th><input type="checkbox"></th>
<th>项目编号</th>
<th>网站路径</th>
<th>采集项目名称</th>
<th>下载图片</th>
<th>页面编码</th>
<th>入库类型</th>
<th>创建时间</th>
<th>操作</th>
<th>功能</th>
</tr>
</thead>
<tbody>
<?php if(is_array($list)): foreach($list as $key=>$vo): ?><tr>
<td><input type="checkbox" id="id" value="<?php echo ($vo["id"]); ?>" style="margin:3px 0px"></td>
<td><?php echo ($vo["id"]); ?></td>
<td><?php echo ($vo["biaoti"]); ?></td>
<td><?php echo ($vo["url"]); ?></td>
<td><span class="label label-success">不下载</span></td>
<td><span class="label label-warning"><?php echo ($vo["bianma"]); ?></span></td>
<td><?php echo (czdirectory('article','0',$vo["directory4"])); ?></td>
<td><?php echo (datetime($vo["begtime"])); ?></td>
<td>
<div class="btn-group">
<a href="/lh3/index.php/Home/Caiji/info_edit/Id/<?php echo ($vo["id"]); ?>" class="btn btn-primary btn-small" data-original-title="" title="">编辑</a>
<a href="#" class="btn btn-warning btn-small" data-original-title="" onClick="Get_Ation_Save('infodelete','<?php echo ($vo["id"]); ?>')">删除</a>
</div>
</td>
<td>
<div class="btn-group">
<a href="#" onClick="openwin1('<?php echo ($vo["id"]); ?>')" class="btn btn-primary btn-small" data-original-title="" title="">采</a>
<a href="#" onClick="openwin('<?php echo ($vo["id"]); ?>')" class="btn btn-primary btn-small" data-original-title="" title="">测</a>
</div>
</td>
</tr><?php endforeach; endif; ?>
</tbody>
<tfoot>
</tfoot>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0" style="margin-top:10px;">
<tr>
<td width="17%" align="left">
<input type="button" value="全选" onClick="CheckAll()" class="btn btn-success" />
<input type="button" value="删除" onClick="Get_Del_Save()" class="btn btn-info" >
</td>
<td width="83%" style="text-align:center;"><div class="pager"><?php echo ($page); ?></div></td>
</tr>
</table>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="breadcrumbs breadcrumbs-fixed" id="breadcrumbs">
<div class="row">
<div class="col-xs-12">
<div class="">
<div id="sidebar2" class="sidebar h-sidebar navbar-collapse collapse collapse_btn">
<ul class="nav nav-list header-nav" id="header-nav">
<?php $m = M('auth_rule'); $dataaa = $m->where(array('pid'=>$_SESSION['se'],'menustatus'=>1))->order('sort')->select(); foreach ($dataaa as $kkk=>$vvv){ if(!$auth->check($vvv['name'], $_SESSION['aid']) && $_SESSION['aid']!= 1){ unset($dataaa[$kkk]); } } ?>
<?php if(is_array($dataaa)): foreach($dataaa as $key=>$k): ?><li>
<a href="<?php echo U(''.$k['name'].'');?>">
<o class="font12 <?php if((CONTROLLER_NAME.'/'.ACTION_NAME == $k['name'])): ?>rigbg<?php endif; ?>"><?php echo ($k["title"]); ?></o>
</a>
<b class="arrow"></b>
</li><?php endforeach; endif; ?>
</ul><!-- /.nav-list -->
</div><!-- .sidebar -->
</div>
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
</div>
<div class="footer">
<div class="footer-inner">
<!-- #section:basics/footer -->
<div class="footer-content">
<span class="bigger-120">
<span class="blue bolder">Wmzz.Cn</span>
Lhc系统 © 2015-2016
</span>
</div>
<!-- /section:basics/footer -->
</div>
</div>
<!-- basic scripts -->
<!--[if IE]>
<script type="text/javascript">
window.jQuery || document.write("<script src='/lh3/Public/js/assets/js/jquery1x.js'>"+"<"+"/script>");
</script>
<![endif]-->
<script src="/lh3/Public/js/assets/js/bootstrap.js"></script>
<script src="/lh3/Public/js/assets/js/maxlength.js"></script>
<script src="/lh3/Public/js/assets/js/ace/ace.js"></script>
<script src="/lh3/Public/js/assets/js/ace/ace.sidebar.js"></script>
<!-- inline scripts related to this page -->
<script type="text/javascript">
jQuery(function($) {
$('#sidebar2').insertBefore('.page-content');
$('.navbar-toggle[data-target="#sidebar2"]').insertAfter('#menu-toggler');
$(document).on('settings.ace.two_menu', function(e, event_name, event_val) {
if(event_name == 'sidebar_fixed') {
if( $('#sidebar').hasClass('sidebar-fixed') ) {
$('#sidebar2').addClass('sidebar-fixed');
$('#navbar').addClass('h-navbar');
}
else {
$('#sidebar2').removeClass('sidebar-fixed')
$('#navbar').removeClass('h-navbar');
}
}
}).triggerHandler('settings.ace.two_menu', ['sidebar_fixed' ,$('#sidebar').hasClass('sidebar-fixed')]);
})
</script>
</div>
<script src="<?php echo (JS_URL); ?>jquery.min.js"></script>
<script>
function CheckAll(value,obj) {
var form=document.getElementsByTagName("form")
for(var i=0;i<form.length;i++){
for (var j=0;j<form[i].elements.length;j++){
if(form[i].elements[j].type=="checkbox"){
var e = form[i].elements[j];
if (value=="selectAll"){e.checked=obj.checked}
else{e.checked=!e.checked;}
}
}
}
}
</script>
<script>
//==========设置几秒跳转
var i = 2;
var intervalid;
function TiaoSecond(Yoyo){
if (i ==0) {
window.location.href =Yoyo;
clearInterval(intervalid);
}
document.getElementById("mes").innerHTML = i;
i--;
}
//==========设置几秒结束
//=======================获取数据
function Get_add_Save(){
var site_name =$("#site_name").attr("value");
var site_title =$("#site_title").attr("value");
var site_url =$("#site_url").attr("value");
var site_describe=$("#site_describe").attr("value");
var site_keywords=$("#site_keywords").attr("value");
var Token =$("#Token").attr("value");
jQuery.ajax({
url: "/lh3/index.php/Home/Caiji/RightSave.html",
dataType:"json",
type:"POST",
data:{Action:"Config_Add",site_name:site_name,site_title:site_title,site_url:site_url,site_describe:site_describe,site_keywords:site_keywords},
beforeSend: function(XHR){
$('#msg').html('<center><br><br><img alt="正在加载中..." src="<?php echo (IMG_URL); ?>Loading/load1.gif" ></center>');
},
success:function(data) {
$("#msg").html(data.msg)
intervalid =setInterval("TiaoSecond('/lh3/index.php/Home/Caiji/index.html')",1000);//==========执行几秒跳转
}
});
}
//=======================获取删除数据
function Get_Del_Save(){
var $check_boxes = $('input[type=checkbox][checked=checked][id!=check_all_box]');
if($check_boxes.length<=0){ alert('您未勾选任何数据,请先勾选!');return;}
if(confirm('您确定要删除此数据?')){
var dropIds = new Array();
$check_boxes.each(function(){
dropIds.push($(this).val());
});
jQuery.ajax({
url: "/lh3/index.php/Home/Caiji/infodelete.html",
dataType:"json",
type:"POST",
data:{Action:"Alldel",id:dropIds},
beforeSend: function(){
$('#msg').html('<center><br><br><img alt="正在加载中..." src="<?php echo (IMG_URL); ?>Loading/load1.gif" ></center>');
},
success:function(data){
$("#msg").html(data.msg)
intervalid =setInterval("TiaoSecond('/lh3/index.php/Home/Caiji/index.html')",1000);//==========执行几秒跳转
}
});
}
}
//=======================获取其他操作
function Get_Ation_Save(oo1,oo2){
if(confirm('您确定要执行此操作?')){
jQuery.ajax({
url: "/lh3/index.php/Home/Caiji/infodelete.html",
dataType:"json",
type:"POST",
data:{Action:"del",id:oo2},
beforeSend: function(){
$('#msg').html('<center><br><br><img alt="正在加载中..." src="<?php echo (IMG_URL); ?>Loading/load1.gif" ></center>');
},
success:function(data){
$("#msg").html(data.msg)
intervalid =setInterval("TiaoSecond('/lh3/index.php/Home/Caiji/index.html')",1000);//==========执行几秒跳转
}
});
}
}
</script>
</body>
</html><file_sep>/index.php
<?php
/**
* Created by PhpStorm.
* User: a1
* Date: 2017/7/19
* Time: 上午12:02
*/
echo phpinfo();<file_sep>/tp5/application/admin/common.php
<?php
//2017,3,15.王维.
/**
* 定义网站公共地址
*/
function base_url(){
return 'http://'.$_SERVER['HTTP_HOST'];
}
/**
* 定义返回上一页
* @param
* @return
*/
function back(){
return $_SERVER['HTTP_REFERER'];
}
function return_json($msg,$data=[],$code=0){
$result['msg']=$msg;
$result['data']=$data;
$result['code']=$code;
$callback = isset($_GET['callback']) ? trim($_GET['callback']) : '';
if(!empty($callback)){
exit($callback.'('.json_encode($result).')');
}
else{
header("Content-Type:application/json;charset=utf-8");
exit(json_encode($result,JSON_UNESCAPED_UNICODE));
}
}
/**
* 把数组(必须是二级数组)变成(a,b,c)的形式
* @param $array $id 变量
* @return string
*/
function to_sql($array,$id){
if(is_array($array)){
$string="(";
foreach ($array as $arr){
$string.=$arr[$id].',';
}
$sql=substr($string, 0,strlen($string)-1).')';
return $sql;
}
}
/**
* 把数组变成xml形式
* @param $result 变量
* @return xml
*/
function ToXml($result){
$xml = "<xml>";
foreach ($result as $key=>$val){
if (is_numeric($val)){
$xml.="<".$key.">".$val."</".$key.">";
}else{
$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
}
}
$xml.="</xml>";
return $xml;
}
/**
* 将XML转为array
* @param $xml 变量
* @return json
*/
function FromXml($xml){
//将XML转为array
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
$values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $values;
}
/**
* php post请求数据
* @param $url 地址
* @param $header=0 请求头部默认为0
* @param $timeout=60 请求超过时间
* @return string
*/
function curl_get($url,$header=0,$timeout=60){
$ch = curl_init();
// 2. 设置选项,包括URL
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_HEADER,$header);
curl_setopt($ch, CURLOPT_TIMEOUT,(int)$timeout);
// 3. 执行并获取HTML文档内容
$output=curl_exec($ch);
curl_close($ch);
return $output;
//return json_decode($output,true);
}
/**
* php post请求数据
* @param $url 地址
* @param $data post数据
* @param $timeout=60 请求超过时间
* @return string
*/
function curl_post($url,$data,$timeout=60){
$ch = curl_init();
// 2. 设置选项,包括URL
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT,(int)$timeout);
// post数据
curl_setopt($ch, CURLOPT_POST, TRUE);
// post的变量
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// 3. 执行并获取HTML文档内容
$output=curl_exec($ch);
curl_close($ch);
return $output;
//return json_decode($output,true);
}
/**
* php xml请求数据
* @param $url 地址
* @param $xml xml数据
* @param $timeout=60 请求超过时间
* @return string
*/
function curl_post_xml($url,$xml,$timeout=60){
// 1. 初始化
$ch = curl_init();
// 2. 设置选项,包括URL
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);//严格校验
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_TIMEOUT, (int)$timeout);
// 3. 执行并获取HTML文档内容
$output = curl_exec($ch);
if($output === FALSE ){
echo "CURL Error:".curl_error($ch);
}
// 4. 释放curl句柄
curl_close($ch);
return $output;
}
/**
* 处理textarea
* @param $string 变量
* @return string
*/
function clear_string($string){
$string=str_replace("\n","<br>",$string);
$string=str_replace("\r", "",$string);
$string=str_replace("\t", "",$string);
$string=str_replace(" ", "",$string);
return $string;
}
/**
* 对数组通过关联id进行分类
* @param $arr array 要分类的数组
* @param $parent_id=0 string 父id
* @return array 返回多维数组
*/
function list_to_tree($arr,$parent_id=0){
$treeArray = array();
foreach ($arr as $v){
if ($v['parent_id'] == $parent_id){
$v['child']=list_to_tree($arr,$v['id']);
$treeArray[] = $v;
}
}
return $treeArray;
}
/**
* 对数据的无限极分类,查找家谱树
* @param $arr array 要分类的数组
* @param $parent_id string 父id
* @return array 返回多维数组
*/
function getFamilyTree($arr,$parent_id){
static $list = array();
foreach ($arr as $v){
if ($v['id'] == $parent_id){
$list[] = $v;
getFamilyTree($arr,$v['parent_id']);
}
}
return $list;
}
<file_sep>/demo/template.js
/**
* Created by a1 on 2017/7/19.
*/
// 这就是我们客户数据的结构.
const customerData = [
{ ssn: "444-44-4444", name: "Bill", age: 35, email: "<EMAIL>" },
{ ssn: "555-55-5555", name: "Donna", age: 32, email: "<EMAIL>" }
];
const dbName = "the_name";
/**********************************************************************************/
function IndexedDBObj() {
var indexedDB = null;
var request = null;
var db = null;
var transaction=null;
}
IndexedDBObj.prototype.LinkDatabese = function (dbName, version) {
var $this = this;
$this.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
$this.request = indexedDB.open(dbName, version);
if ($this.request) {
$this.request.onerror = function (event) {
// 对request.errorCode做一些需要的处理!
};
$this.request.onsuccess = function (event) {
$this.db=$this.request.result;
$this.transaction=$this.db.transaction(['customers'],'readwrite');
};
// 截止2012-02-22为止,WebKit内核的浏览器还没有对onupgradeneeded进行实现.
$this.request.onupgradeneeded = function (event) {
// 更新存储的对象(译者,此处不懂翻译,原文为Update object stores and indices)
// 对request.result进行一些需要的处理!
var db = event.target.result;
// 创建一个名为“objectStore”的对象来存储我们的客户数据。
// 我们选择使用“ssn”作为我们的key path,因为它能保证唯一
var objectStore = db.createObjectStore("customers", { keyPath: "ssn" });
// 创建一个通过name属性去查找客户数据的索引。因为可能出现
// 出现重复,所以我们不能使用唯一索引.
objectStore.createIndex("name", "name", { unique: false });
// 我们想确保任意两个客户的email是不同的,
// 所以我们用了唯一索引
objectStore.createIndex("email", "email", { unique: true });
// 用我们刚新建的objectStore来存储客户数据.
for (i in customerData) {
objectStore.add(customerData[i]);
}
db.onerror = function (event) {
// 针对这个数据库的所有请求的异常都统一在这个异常事件处理程序中完成。(译者:这样做有效减少监听的数量,在事件冒泡过程的最顶层实现一次监听就可以了,这也是提高JS运行效率的一种技巧。)
alert("Database error: " + event.target.errorCode);
}
}
}
}
/*****************************************************************************************/
<file_sep>/admin/Admin/Home/Controller/NoticeController.class.php
<?php
namespace Home\Controller;
class NoticeController extends \Common\Controller\AuthController {
public $table_name='notice';
public function __construct() {
parent::__construct();
}
public function index()
{
$map=[];
if(!empty($_GET['keyword'])){
$map['title']=['like',"%".$_GET['keyword']."%"];
$this->assign('keyword',I('get.keyword'));
}
$count =M($this->table_name)->count();
$Page = new \Common\Page($count,30);
$show = $Page->paging();
$list = M($this->table_name)->where($map)->order("id desc")->limit($Page->limit)->select();
$this->assign('list',$list);
$this->assign('page',$show);
$this->display();
}
function add()
{
if (IS_POST) {
if(!$_POST['title']){
$this->error('标题为空');
}
$id=M('notice')->add(I('post.'));
if($id) {
$this->success('保存成功');
}else{
$this->error('保存失败');
}
}else {
$this->display();
}
}
function edit()
{
if (IS_POST) {
if(!$_POST['title']){
$this->error('标题为空');
}
$id=M('notice')->save(I('post.'));
if($id) {
$this->success('保存成功');
}else{
$this->error('保存失败');
}
}else {
$this->assign('row',M($this->table_name)->find($_GET['id']));
$this->display();
}
}
function del(){
if(!$_POST['id']) $this->error('未选择数据');
M($this->table_name)->delete($_POST['id']);
$this->success('删除成功');
}
}<file_sep>/admin/Admin/Home/Controller/EmptyController.class.php
<?php
namespace Home\Controller;
use Think\Controller;
class EmptyController extends Controller {
public function _empty(){
echo "<div style='text-align:center;width:100%;padding-top:100px;float:left'><img src='".IMG_URL."404.png'></div>";
}
}<file_sep>/ci/app/helpers/common_helper.php
<?php
//2017.7.1
function base_url(){
return 'http://'.$_SERVER['HTTP_HOST'].'/';
}
//接受get数据
function get($index=null){
return get_instance()->input->get($index);
}
//接受post数据
function post($index=null){
return get_instance()->input->post($index);
}
/**
* 加载语言包
* @param $files
* @param string $lang 默认为'english'
* @return array
*/
function lang($files,$lang=''){
get_instance()->lang->load($files, $lang);
return get_instance()->lang->language;
}
//占用内存,仅供调试用
function m(){
return (memory_get_usage()/1024/1024).'M';
}
/**
* 返回json给客户端;
* @param $msg 消息提示
* @param $data=array() 数据
* @param $code=0 状态
*/
function return_json($msg,$data=[],$code=0){
$result['msg']=$msg;
$result['data']=$data;
$result['code']=$code;
$callback = isset($_GET['callback']) ? trim($_GET['callback']) : '';
if(!empty($callback)){
exit($callback.'('.json_encode($result).')');
}
else{
header("Content-Type:application/json;charset=utf-8");
exit(json_encode($result,JSON_UNESCAPED_UNICODE));
}
}
//得到带token的请求头
function get_auth_headers($header_key = null)
{
if (function_exists('apache_request_headers')) {
/* Authorization: header */
$headers = apache_request_headers();
$out = array();
foreach ($headers AS $key => $value) {
$key = str_replace(" ", "-", ucwords(strtolower(str_replace("-", " ", $key))));
$out[$key] = $value;
}
} else {
$out = array();
if (isset($_SERVER['CONTENT_TYPE'])) {
$out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
}
if (isset($_ENV['CONTENT_TYPE'])) {
$out['Content-Type'] = $_ENV['CONTENT_TYPE'];
}
foreach ($_SERVER as $key => $value) {
if (substr($key, 0, 5) == "HTTP_") {
$key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
$out[$key] = $value;
}
}
}
if ($header_key != null) {
$header_key = ucfirst(strtolower($header_key));
if (isset($out[$header_key])) {
return $out[$header_key];
} else {
return false;
}
}
return $out;
}
/**
* 获取客户端IP
* @return string
*/
function get_ip()
{
$realip = '';
$unknown = 'unknown';
if (isset($_SERVER)){
if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)){
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
foreach($arr as $ip){
$ip = trim($ip);
if ($ip != 'unknown'){
$realip = $ip;
break;
}
}
}else if(isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP']) && strcasecmp($_SERVER['HTTP_CLIENT_IP'], $unknown)){
$realip = $_SERVER['HTTP_CLIENT_IP'];
}else if(isset($_SERVER['REMOTE_ADDR']) && !empty($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)){
$realip = $_SERVER['REMOTE_ADDR'];
}else{
$realip = $unknown;
}
}else{
if(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), $unknown)){
$realip = getenv("HTTP_X_FORWARDED_FOR");
}else if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), $unknown)){
$realip = getenv("HTTP_CLIENT_IP");
}else if(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), $unknown)){
$realip = getenv("REMOTE_ADDR");
}else{
$realip = $unknown;
}
}
if($realip=='::1'){
$realip = '127.0.0.1';
}
$realip = preg_match("/[\d\.]{7,15}/", $realip, $matches) ? $matches[0] : $unknown;
return $realip;
}
/**
* 浏览器友好的变量输出
* @param mixed $var 变量
* @param boolean $echo 是否输出 默认为True 如果为false 则返回输出字符串
* @param string $label 标签 默认为空
* @param boolean $strict 是否严谨 默认为true
* @return void|string
*/
function dump($var, $echo=true, $label=null, $strict=true) {
$label = ($label === null) ? '' : rtrim($label) . ' ';
if (!$strict) {
if (ini_get('html_errors')) {
$output = print_r($var, true);
$output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
} else {
$output = $label . print_r($var, true);
}
} else {
ob_start();
var_dump($var);
$output = ob_get_clean();
if (!extension_loaded('xdebug')) {
$output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output);
$output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
}
}
if ($echo) {
echo($output);
return null;
}else
return $output;
}<file_sep>/admin/Admin/Model/AdministratorModel.class.php
<?php
namespace Model;
use Think\Model;
//说明 默认是读取表前缀 加表名字的
//可以通过 protected $trueTableName="xxxx"; 重置表名称
//可以通过 protected $tablePrefix ="xxxx"; 重置表前缀名称
class AdministratorModel extends Model {
//↓↓↓↓↓↓↓↓↓↓↓调用网站配置模块
public function Confing(){
$site="我是测试";
echo $site;
}
//↓↓↓↓↓↓↓↓↓↓↓调用网站配置模块
function CheckUser($name,$pwd){
$info=$this->getByUsername($name);
if ($info!=null){
if ($info['password']!=$pwd){
return false;
}else{
return $info;
}
}else{
return false;
}
}
//↑↑↑↑↑↑↑↑↑↑↑↑调用网站配置模块
//↑↑↑↑↑↑↑↑↑↑↑↑调用网站配置模块
}<file_sep>/admin/Admin/Model/configModel.class.php
<?php
namespace Model;
use Think\Model;
//说明 默认是读取表前缀 加表名字的
//可以通过 protected $trueTableName="xxxx"; 重置表名称
//可以通过 protected $tablePrefix ="xxxx"; 重置表前缀名称
class configModel extends Model {
//↓↓↓↓↓↓↓↓↓↓↓调用网站配置模块
public function show(){
$info=$this->where('id=1')->select();
return $info;
}
}<file_sep>/admin/Admin/Home/Conf/config.php
<?php
return array(
'URL_MODEL' =>1,// URL访问模式,可选参数0、1、2、3
);
?><file_sep>/ci/app/core/MY_Controller.php
<?php
class MY_Controller extends CI_Controller{
public $token;
public $admin;//用户信息
public $sn;//域名
//不需要token验证的接口
public $no_check_url=[
'login'=>['index'],
'test'
];
public $url;
public function __construct()
{
parent::__construct();
//设置错误级别
error_reporting(E_ALL ^ E_NOTICE);
//设置时区
date_default_timezone_set('PRC');
//加载项目常量
require_once APPPATH.'/config/ww.php';
//加载数据库
$this->load->database();
//加载redis
$this->load->library('my_redis','','redis');
//加载应用函数
$this->load->helper('common');
//api接口初始化
$this->init();
}
//api接口初始化
function init()
{
if (!is_cli()) {
header("Access-Control-Allow-Origin:*");//允许跨域访问
}
//探测请求
if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH, OPTIONS");
header("Access-Control-Allow-Headers: Accept, Authorization, Content-Type, Pragma, Origin, Cache-Control, AuthToken, FROMWAY");
exit;
}
if(!$this->is_no_check())
{
$this->check_token();
}
}
/**
* ww:是否不需要验证token
* @return bool
*/
function is_no_check(){
$classArr=[];
foreach ($this->no_check_url as $key=>$value){
$classArr[]=is_numeric($key)?$value:$key;
}
if(!in_array($this->router->class,$classArr)) {
return false;
}
$method=$this->no_check_url[$this->router->class];
if($method&&!in_array($this->router->method,$method)){
return false;
}
return true;
}
//检查token
function check_token()
{
$auth=get_auth_headers(TOKEN_CODE_AUTH);
$this->token=$auth;
if(!$this->token)
{
return_json('token不存在');
}
$tokenKey = 'token:'.TOKEN_CODE_ADMIN.':'.$this->token;
$data=$this->redis->get($tokenKey);
if(!$data)
{
return_json('未登陆或token无效');
}
if(isset($data['be_outed_time']))
{
$this->redis->del($tokenKey);
return_json('您的账号在其他地方登陆');
}
//规定多长时间必须登陆一次
if($_SERVER['REQUEST_TIME']-$data['login_time']>MUST_LOGIN_TIME_INTERVAL)
{
$this->redis->del('token_ID:'.TOKEN_CODE_ADMIN.':'.$data['id']);
$this->redis->del($tokenKey);
return_json('token失效');
}
//检查token是否超过有效时间
if($_SERVER['REQUEST_TIME']-$data['visit_time']>MAX_LIFE_TIME)
{
$this->redis->del($tokenKey);
return_json('token失效');
}
$data['visit_time']=$_SERVER['REQUEST_TIME'];
$this->redis->set($tokenKey,$data,MAX_LIFE_TIME);//更新最后访问时间
$this->admin=$data;//记录用户信息
}
/**
* @param $code
* @param $msg
* @param null $sid
* @return bool
*/
public function push($code,$msg,$sid =null){
if(empty($code) || empty($msg)){
return false;
}
error_reporting(0);
$this->load->library('mqtt',array('address'=>SOCKET_SERVER, 'port'=>SOCKET_PORT,'clientid'=>'MQTT CLIENT'));
if ($this->mqtt->connect()) {
$this->mqtt->publish('u/demo',json_encode(array('code'=>$code,'msg'=>$msg,'sid'=>$sid)),0);
$this->mqtt->close();
}
else{
return_json('mqtt连接异常');
}
}
/**
* 跳转到登录页面或跳转提示。注:和域名重定向有所不同,如果是ajax并不会跳转页面
* @param $url
*/
public function go_to($url){
if($this->input->is_ajax_request()){
header("Content-Type:application/json;charset=utf-8");
echo json_encode(array('info'=>'登录过期,请重新登录','status'=>-1));exit;
}
header("Location:$url");
}
}<file_sep>/admin/Admin/Home/Model/LoginModel.class.php
<?php
namespace Model;
use Think\Model;
//说明 默认是读取表前缀 加表名字的
//可以通过 protected $trueTableName="xxxx"; 重置表名称
//可以通过 protected $tablePrefix ="xxxx"; 重置表前缀名称
class LoginModel extends Model {
//↓↓↓↓↓↓↓↓↓↓↓调用网站配置模块
public function CheckUser($name,$pwd){
$info=$this->getByusername($name);
var_dump($info);
}
//↑↑↑↑↑↑↑↑↑↑↑↑调用网站配置模块
}<file_sep>/tp5/application/init.php
<?php
/**
* Created by PhpStorm.
* User: ww
* Date: 2017/7/16
* Time: 下午3:35
*/
define('REQUEST_METHOD',$_SERVER['REQUEST_METHOD']);
define('IS_GET', REQUEST_METHOD =='GET' ? true : false);
define('IS_POST', REQUEST_METHOD =='POST' ? true : false);
define('IS_AJAX', ((isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') || !empty($_POST['ajax']) || !empty($_GET['ajax'])) ? true : false);
defined('SOCKET_SERVER') OR define('SOCKET_SERVER','127.0.0.1');
defined('SOCKET_PORT') OR define('SOCKET_PORT',1883);
defined('MQ_HOST') OR define('MQ_HOST','127.0.0.1');
defined('MQ_PORT') OR define('MQ_PORT','61614');
//redis缓存相关参数
const MUST_LOGIN_TIME_INTERVAL=30*24*3600;//规定多长时间必须登陆一次
const MAX_LIFE_TIME=10*24*3600;//token有效期
const MAX_OFF_TIME=15*60;//最大离线时间
const MAX_ERROR_TIMES=8;//密码输入最大错误次数
/*密钥*/
const TOKEN_PRIVATE_ADMIN_KEY = 123456;// 管理员token密钥
const TOKEN_PRIVATE_USER_KEY = 234567;// 会员token密钥
const TOKEN_CODE_AUTH = 'AuthToken';//后台
const TOKEN_CODE_ADMIN = 'Admin';//管理员
const TOKEN_CODE_USER = 'User';//会员
<file_sep>/ionicTestDemo/js/home/init.js
/**
* Created by a1 on 2017/7/18.
*/
angular.module('ionicApp', ['ionic'])
.controller('RootCtrl', function ($scope) {
$scope.onControllerChanged = function (oldController, oldIndex, newController, newIndex) {
console.log('Controller changed', oldController, oldIndex, newController, newIndex);
console.log(arguments);
};
})
.controller('HomeCtrl', function ($scope, $timeout, $ionicModal, $ionicActionSheet) {
debugger;
$scope.items = [];
$ionicModal.fromTemplateUrl('newTask.html', function (modal) {
$scope.settingsModal = modal;
});
var removeItem = function (item, button) {
$ionicActionSheet.show({
buttons: [],
destructiveText: 'Delete Task',
cancelText: 'Cancel',
cancel: function () {
return true;
},
destructiveButtonClicked: function () {
$scope.items.splice($scope.items.indexOf(item), 1);
return true;
}
});
};
var completeItem = function (item, button) {
item.isCompleted = true;
};
$scope.onReorder = function (el, start, end) {
ionic.Utils.arrayMove($scope.items, start, end);
};
$scope.onRefresh = function () {
console.log('ON REFRESH');
$timeout(function () {
$scope.$broadcast('scroll.refreshComplete');
}, 1000);
}
$scope.removeItem = function (item) {
removeItem(item);
};
$scope.newTask = function () {
$scope.settingsModal.show();
};
// Create the items
for (var i = 0; i < 25; i++) {
$scope.items.push({
title: 'Task ' + (i + 1),
buttons: [{
text: 'Done',
type: 'button-success',
onButtonClicked: completeItem,
}, {
text: 'Delete',
type: 'button-danger',
onButtonClicked: removeItem,
}]
});
}
})
.controller('cartCtrl', ['$scope', '$ionicTabsDelegate', function ($scope) {
$scope.items = [];
for (var i = 0; i < 10; i++) {
var jsonDate = {
name: 'name' + i,
title: 'title' + i,
id: 10010 + i
}
$scope.items.push(jsonDate)
}
$scope.onRefresh = function () {
for (var i = 0; i < 10; i++) {
var jsonDate = {
name: 'name' + i,
title: 'title' + i,
id: 10010 + i
}
$scope.items.push(jsonDate)
}
};
/* $scope.toCart=function (index) {
$ionicSlideBoxDelegate.select()
};*/
$scope.onselect = function (index) {
alert('我是被选中的时候触发的函数');
}
$scope.deSelect = function () {
alert('选中被取消了')
}
}])
.controller('TaskCtrl', function ($scope) {
$scope.close = function () {
$scope.modal.hide();
}
})
.controller('About', ['$scope', '$ionicTabsDelegate', function ($scope, $ionicTabsDelegate) {
$scope.toGoCart = function (index) {
$ionicTabsDelegate.select(index, true);
};
$scope.images=[];
for (var i=1;i<11;i++){
$scope.images.push(i);
}
}])
.controller('Settings',['$scope','$rootScope','$ionicScrollDelegate',function ($scope,$rootScope,$ionicScrollDelegate) {
$scope.scrollMainToTop = function() {
alert(878953894689)
$ionicScrollDelegate.$getByHandle('mainScroll').scrollTop(true);
};
$scope.scrollSmallToTop = function() {
alert(76877878)
$ionicScrollDelegate.resize()
$ionicScrollDelegate.$getByHandle('small').scrollTop(true);
};
$scope.goToBottom=function () {
alert(678989)
// $ionicScrollDelegate.$getByHandle('small').scrollBottom(true)
$ionicScrollDelegate.$getByHandle('small').scrollBy(-20,30,true)
}
$scope.shouldShowScrollView=true;
if($scope.shouldShowScrollView){
try {
var delegate = $ionicScrollDelegate.$getByHandle('myScroll');
delegate.rememberScrollPosition('my-scroll-id');
delegate.scrollToRememberedPosition();
}catch (e){
console.log(e);
$ionicScrollDelegate.$getByHandle('myScroll').scrollTop();
}
}
// 这里可以放任何唯一的ID。重点是:要在每次重新创建控制器时
// 我们要加载当前记住的滚动值。
$scope.items = [];
for (var i=0; i<100; i++) {
$scope.items.push(i);
}
}])<file_sep>/ci/app/helpers/curl_helper.php
<?php
/**
* php post请求数据
* @param $url 地址
* @param $header=0 请求头部默认为0
* @param $timeout=60 请求超过时间
* @return string
*/
function curl_get($url,$header=0,$timeout=60){
$ch = curl_init();
// 2. 设置选项,包括URL
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_HEADER,$header);
curl_setopt($ch, CURLOPT_TIMEOUT,(int)$timeout);
// 3. 执行并获取HTML文档内容
$output=curl_exec($ch);
curl_close($ch);
return $output;
//return json_decode($output,true);
}
/**
* php post请求数据
* @param $url 地址
* @param $data post数据
* @param $timeout=60 请求超过时间
* @return string
*/
function curl_post($url,$data,$timeout=60){
$ch = curl_init();
// 2. 设置选项,包括URL
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT,(int)$timeout);
// post数据
curl_setopt($ch, CURLOPT_POST, TRUE);
// post的变量
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// 3. 执行并获取HTML文档内容
$output=curl_exec($ch);
curl_close($ch);
return $output;
//return json_decode($output,true);
}
/**
* php xml请求数据
* @param $url 地址
* @param $xml xml数据
* @param $timeout=60 请求超过时间
* @return string
*/
function curl_post_xml($url,$xml,$timeout=60){
// 1. 初始化
$ch = curl_init();
// 2. 设置选项,包括URL
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);//严格校验
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_TIMEOUT, (int)$timeout);
// 3. 执行并获取HTML文档内容
$output = curl_exec($ch);
if($output === FALSE ){
echo "CURL Error:".curl_error($ch);
}
// 4. 释放curl句柄
curl_close($ch);
return $output;
}
/**
* 把数组变成xml形式
* @param $result 变量
* @return xml
*/
function ToXml($result){
$xml = "<xml>";
foreach ($result as $key=>$val){
if (is_numeric($val)){
$xml.="<".$key.">".$val."</".$key.">";
}else{
$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
}
}
$xml.="</xml>";
return $xml;
}
/**
* 将XML转为array
* @param $xml 变量
* @return json
*/
function FromXml($xml){
//将XML转为array
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
$values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $values;
}
|
0f7a2b8f02f90ebe8e63bfbb2ee400cbe7541a8c
|
[
"JavaScript",
"Markdown",
"PHP"
] | 46
|
PHP
|
liusiying65200/Angular4.0
|
c76c324fe6bd9de48c8c4735c8283992b35f6663
|
271ba95557be444da65e7584d6f1963e33a3c5a0
|
refs/heads/master
|
<repo_name>lequietriot/open-osrs-audio-mod<file_sep>/runescape-client/src/main/java/MusicPatchPcmStream.java
import net.runelite.mapping.Export;
import net.runelite.mapping.Implements;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("ij")
@Implements("MusicPatchPcmStream")
public class MusicPatchPcmStream extends PcmStream {
@ObfuscatedName("i")
@ObfuscatedSignature(
descriptor = "Lio;"
)
@Export("superStream")
MidiPcmStream superStream;
@ObfuscatedName("s")
@ObfuscatedSignature(
descriptor = "Lkn;"
)
@Export("queue")
NodeDeque queue;
@ObfuscatedName("a")
@ObfuscatedSignature(
descriptor = "Las;"
)
@Export("mixer")
PcmStreamMixer mixer;
@ObfuscatedSignature(
descriptor = "(Lio;)V"
)
MusicPatchPcmStream(MidiPcmStream var1) {
this.queue = new NodeDeque(); // L: 11
this.mixer = new PcmStreamMixer(); // L: 12
this.superStream = var1; // L: 15
} // L: 16
@ObfuscatedName("i")
@ObfuscatedSignature(
descriptor = "(Liu;[IIIII)V",
garbageValue = "-887110953"
)
void method4974(MusicPatchNode var1, int[] var2, int var3, int var4, int var5) {
if ((this.superStream.field2944[var1.field2996] & 4) != 0 && var1.field2999 < 0) { // L: 73
int var6 = this.superStream.field2946[var1.field2996] / UserComparator2.sampleRate; // L: 74
while (true) {
int var7 = (var6 + 1048575 - var1.field3003) / var6; // L: 76
if (var7 > var4) { // L: 77
var1.field3003 += var6 * var4; // L: 99
break;
}
var1.stream.fill(var2, var3, var7); // L: 78
var3 += var7; // L: 79
var4 -= var7; // L: 80
var1.field3003 += var6 * var7 - 1048576; // L: 81
int var8 = UserComparator2.sampleRate / 100; // L: 82
int var9 = 262144 / var6; // L: 83
if (var9 < var8) { // L: 84
var8 = var9;
}
RawPcmStream var10 = var1.stream; // L: 85
if (this.superStream.field2932[var1.field2996] == 0) { // L: 86
var1.stream = RawPcmStream.method817(var1.rawSound, var10.method832(), var10.method936(), var10.method824()); // L: 87
} else {
var1.stream = RawPcmStream.method817(var1.rawSound, var10.method832(), 0, var10.method824()); // L: 90
this.superStream.method4765(var1, var1.patch.pitchOffset[var1.field2990] < 0); // L: 91
var1.stream.method941(var8, var10.method936()); // L: 92
}
if (var1.patch.pitchOffset[var1.field2990] < 0) { // L: 94
var1.stream.setNumLoops(-1);
}
var10.method830(var8); // L: 95
var10.fill(var2, var3, var5 - var3); // L: 96
if (var10.method834()) { // L: 97
this.mixer.addSubStream(var10);
}
}
}
var1.stream.fill(var2, var3, var4); // L: 101
} // L: 102
@ObfuscatedName("w")
@ObfuscatedSignature(
descriptor = "(Liu;IB)V",
garbageValue = "50"
)
void method4959(MusicPatchNode var1, int var2) {
if ((this.superStream.field2944[var1.field2996] & 4) != 0 && var1.field2999 < 0) { // L: 105
int var3 = this.superStream.field2946[var1.field2996] / UserComparator2.sampleRate; // L: 106
int var4 = (var3 + 1048575 - var1.field3003) / var3; // L: 107
var1.field3003 = var3 * var2 + var1.field3003 & 1048575; // L: 108
if (var4 <= var2) { // L: 109
if (this.superStream.field2932[var1.field2996] == 0) { // L: 110
var1.stream = RawPcmStream.method817(var1.rawSound, var1.stream.method832(), var1.stream.method936(), var1.stream.method824()); // L: 111
} else {
var1.stream = RawPcmStream.method817(var1.rawSound, var1.stream.method832(), 0, var1.stream.method824()); // L: 114
this.superStream.method4765(var1, var1.patch.pitchOffset[var1.field2990] < 0); // L: 115
}
if (var1.patch.pitchOffset[var1.field2990] < 0) { // L: 117
var1.stream.setNumLoops(-1);
}
var2 = var1.field3003 / var3; // L: 118
}
}
var1.stream.skip(var2); // L: 121
} // L: 122
@ObfuscatedName("g")
@ObfuscatedSignature(
descriptor = "()Lav;"
)
@Export("firstSubStream")
protected PcmStream firstSubStream() {
MusicPatchNode var1 = (MusicPatchNode)this.queue.last(); // L: 19
if (var1 == null) {
return null; // L: 20
} else {
return (PcmStream)(var1.stream != null ? var1.stream : this.nextSubStream()); // L: 21 22
}
}
@ObfuscatedName("e")
@ObfuscatedSignature(
descriptor = "()Lav;"
)
@Export("nextSubStream")
protected PcmStream nextSubStream() {
MusicPatchNode var1;
do {
var1 = (MusicPatchNode)this.queue.previous(); // L: 27
if (var1 == null) {
return null; // L: 28
}
} while(var1.stream == null); // L: 29
return var1.stream;
}
@ObfuscatedName("p")
protected int vmethod4958() {
return 0; // L: 34
}
@ObfuscatedName("j")
@Export("fill")
protected void fill(int[] var1, int var2, int var3) {
this.mixer.fill(var1, var2, var3); // L: 40
for (MusicPatchNode var6 = (MusicPatchNode)this.queue.last(); var6 != null; var6 = (MusicPatchNode)this.queue.previous()) { // L: 41
if (!this.superStream.method4787(var6)) { // L: 42
int var4 = var2; // L: 43
int var5 = var3; // L: 44
do {
if (var5 <= var6.field2995) { // L: 45
this.method4974(var6, var1, var4, var5, var5 + var4); // L: 51
var6.field2995 -= var5; // L: 52
break;
}
this.method4974(var6, var1, var4, var6.field2995, var5 + var4); // L: 46
var4 += var6.field2995; // L: 47
var5 -= var6.field2995; // L: 48
} while(!this.superStream.method4788(var6, var1, var4, var5)); // L: 49
}
}
} // L: 54
@ObfuscatedName("x")
@Export("skip")
protected void skip(int var1) {
this.mixer.skip(var1); // L: 58
for (MusicPatchNode var3 = (MusicPatchNode)this.queue.last(); var3 != null; var3 = (MusicPatchNode)this.queue.previous()) { // L: 59
if (!this.superStream.method4787(var3)) { // L: 60
int var2 = var1; // L: 61
do {
if (var2 <= var3.field2995) { // L: 62
this.method4959(var3, var2); // L: 67
var3.field2995 -= var2; // L: 68
break;
}
this.method4959(var3, var3.field2995); // L: 63
var2 -= var3.field2995; // L: 64
} while(!this.superStream.method4788(var3, (int[])null, 0, var2)); // L: 65
}
}
} // L: 70
}
<file_sep>/runescape-client/src/main/java/class247.java
import net.runelite.mapping.Export;
import net.runelite.mapping.ObfuscatedGetter;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("ir")
public class class247 {
@ObfuscatedName("i")
@ObfuscatedSignature(
descriptor = "Lko;"
)
@Export("musicPatchesArchive")
public static AbstractArchive musicPatchesArchive;
@ObfuscatedName("w")
@ObfuscatedSignature(
descriptor = "Lko;"
)
@Export("musicSamplesArchive")
public static AbstractArchive musicSamplesArchive;
@ObfuscatedName("a")
@ObfuscatedSignature(
descriptor = "Lio;"
)
@Export("midiPcmStream")
public static MidiPcmStream midiPcmStream;
@ObfuscatedName("o")
@ObfuscatedGetter(
intValue = 1167067929
)
@Export("musicPlayerStatus")
public static int musicPlayerStatus; //0 = ready, 1 = Fanfares, 2 = Music
@ObfuscatedName("j")
@ObfuscatedGetter(
intValue = 2050223797
)
@Export("musicTrackVolume")
public static int musicTrackVolume;
@ObfuscatedName("b")
@ObfuscatedGetter(
intValue = -609469797
)
@Export("pcmSampleLength")
public static int pcmSampleLength;
@ObfuscatedName("k")
@ObfuscatedSignature(
descriptor = "Lad;"
)
@Export("soundCache")
public static SoundCache soundCache;
@ObfuscatedName("kh")
@ObfuscatedSignature(
descriptor = "Ljf;"
)
@Export("dragInventoryWidget")
static Widget dragInventoryWidget;
static {
musicPlayerStatus = 0; // L: 11
}
@ObfuscatedName("w")
@ObfuscatedSignature(
descriptor = "(IIIII)V",
garbageValue = "-1859511667"
)
static final void method4751(int var0, int var1, int var2, int var3) {
for (int var4 = var1; var4 <= var3 + var1; ++var4) { // L: 63
for (int var5 = var0; var5 <= var0 + var2; ++var5) { // L: 64
if (var5 >= 0 && var5 < 104 && var4 >= 0 && var4 < 104) { // L: 65
class54.field419[0][var5][var4] = 127; // L: 66
if (var0 == var5 && var5 > 0) { // L: 67
Tiles.Tiles_heights[0][var5][var4] = Tiles.Tiles_heights[0][var5 - 1][var4];
}
if (var0 + var2 == var5 && var5 < 103) { // L: 68
Tiles.Tiles_heights[0][var5][var4] = Tiles.Tiles_heights[0][var5 + 1][var4];
}
if (var4 == var1 && var4 > 0) { // L: 69
Tiles.Tiles_heights[0][var5][var4] = Tiles.Tiles_heights[0][var5][var4 - 1];
}
if (var3 + var1 == var4 && var4 < 103) { // L: 70
Tiles.Tiles_heights[0][var5][var4] = Tiles.Tiles_heights[0][var5][var4 + 1];
}
}
}
}
} // L: 74
}
<file_sep>/runescape-client/src/main/java/SoundTone.java
/*
* SFX - Sound Tone class
* @author <NAME> (https://github.com/lequietriot)
*
* Refactored using source(s):
* https://www.rune-server.ee/runescape-development/rs2-client/snippets/421977-sound-effects.html
* https://github.com/Jameskmonger/317refactor/blob/master/src/com/jagex/runescape/audio/Instrument.java
*/
import java.util.Random;
public class SoundTone {
static int[] toneSamples;
static int[] toneNoise;
static int[] toneSine;
static int[] tonePhases;
static int[] toneDelays;
static int[] toneVolumeSteps;
static int[] tonePitchSteps;
static int[] tonePitchBaseSteps;
SoundEnvelope pitch;
SoundEnvelope volume;
SoundEnvelope pitchModifier;
SoundEnvelope pitchModifierAmplitude;
SoundEnvelope volumeMultiplier;
SoundEnvelope volumeMultiplierAmplitude;
SoundEnvelope release;
SoundEnvelope attack;
int[] oscillatorVolume;
int[] oscillatorPitch;
int[] oscillatorDelays;
int delayTime;
int delayDecay;
SoundFilter filter;
SoundEnvelope filterEnvelope;
int duration;
int offset;
static {
toneNoise = new int[32768];
Random randomID = new Random(0L);
int toneID;
for (toneID = 0; toneID < 32768; ++toneID) {
toneNoise[toneID] = (randomID.nextInt() & 2) - 1;
}
toneSine = new int[32768];
for (toneID = 0; toneID < 32768; ++toneID) {
toneSine[toneID] = (int)(Math.sin((double) toneID / 5215.1903D) * 16384.0D);
}
toneSamples = new int[220500];
tonePhases = new int[5];
toneDelays = new int[5];
toneVolumeSteps = new int[5];
tonePitchSteps = new int[5];
tonePitchBaseSteps = new int[5];
}
SoundTone() {
this.oscillatorVolume = new int[]{0, 0, 0, 0, 0};
this.oscillatorPitch = new int[]{0, 0, 0, 0, 0};
this.oscillatorDelays = new int[]{0, 0, 0, 0, 0};
this.delayTime = 0;
this.delayDecay = 100;
this.duration = 500;
this.offset = 0;
}
final int[] synthesize(int steps, int tones) {
class321.clearIntArray(toneSamples, 0, steps);
if (tones >= 10) {
double duration = (double) steps / ((double) tones + 0.0D);
this.pitch.reset();
this.volume.reset();
int pitchModulationStep = 0;
int pitchModulationBaseStep = 0;
int pitchModulationPhase = 0;
if (this.pitchModifier != null) {
this.pitchModifier.reset();
this.pitchModifierAmplitude.reset();
pitchModulationStep = (int) ((double) (this.pitchModifier.end - this.pitchModifier.start) * 32.768D / duration);
pitchModulationBaseStep = (int) ((double) this.pitchModifier.start * 32.768D / duration);
}
int volumeModulationStep = 0;
int volumeModulationBaseStep = 0;
int volumeModulationPhase = 0;
if (this.volumeMultiplier != null) {
this.volumeMultiplier.reset();
this.volumeMultiplierAmplitude.reset();
volumeModulationStep = (int) ((double) (this.volumeMultiplier.end - this.volumeMultiplier.start) * 32.768D / duration);
volumeModulationBaseStep = (int) ((double) this.volumeMultiplier.start * 32.768D / duration);
}
int step;
for (step = 0; step < 5; ++step) {
if (this.oscillatorVolume[step] != 0) {
tonePhases[step] = 0;
toneDelays[step] = (int) ((double) this.oscillatorDelays[step] * duration);
toneVolumeSteps[step] = (this.oscillatorVolume[step] << 14) / 100;
tonePitchSteps[step] = (int) ((double) (this.pitch.end - this.pitch.start) * 32.768D * Math.pow(1.0057929410678534D, this.oscillatorPitch[step]) / duration);
tonePitchBaseSteps[step] = (int) ((double) this.pitch.start * 32.768D / duration);
}
}
int pitchChange;
int volumeChange;
int volumeMultiplierChange;
int volumeMultiplierAmplitudeChange;
int[] samples;
for (step = 0; step < steps; ++step) {
pitchChange = this.pitch.doStep(steps);
volumeChange = this.volume.doStep(steps);
if (this.pitchModifier != null) {
volumeMultiplierChange = this.pitchModifier.doStep(steps);
volumeMultiplierAmplitudeChange = this.pitchModifierAmplitude.doStep(steps);
pitchChange += this.evaluateWave(pitchModulationPhase, volumeMultiplierAmplitudeChange, this.pitchModifier.form) >> 1;
pitchModulationPhase = pitchModulationPhase + pitchModulationBaseStep + (volumeMultiplierChange * pitchModulationStep >> 16);
}
if (this.volumeMultiplier != null) {
volumeMultiplierChange = this.volumeMultiplier.doStep(steps);
volumeMultiplierAmplitudeChange = this.volumeMultiplierAmplitude.doStep(steps);
volumeChange = volumeChange * ((this.evaluateWave(volumeModulationPhase, volumeMultiplierAmplitudeChange, this.volumeMultiplier.form) >> 1) + 32768) >> 15;
volumeModulationPhase = volumeModulationPhase + volumeModulationBaseStep + (volumeMultiplierChange * volumeModulationStep >> 16);
}
for (volumeMultiplierChange = 0; volumeMultiplierChange < 5; ++volumeMultiplierChange) {
if (this.oscillatorVolume[volumeMultiplierChange] != 0) {
volumeMultiplierAmplitudeChange = toneDelays[volumeMultiplierChange] + step;
if (volumeMultiplierAmplitudeChange < steps) {
samples = toneSamples;
samples[volumeMultiplierAmplitudeChange] += this.evaluateWave(tonePhases[volumeMultiplierChange], volumeChange * toneVolumeSteps[volumeMultiplierChange] >> 15, this.pitch.form);
samples = tonePhases;
samples[volumeMultiplierChange] += (pitchChange * tonePitchSteps[volumeMultiplierChange] >> 16) + tonePitchBaseSteps[volumeMultiplierChange];
}
}
}
}
int volumeAttackAmplitudeChange;
if (this.release != null) {
this.release.reset();
this.attack.reset();
step = 0;
boolean muted = true;
for (volumeMultiplierChange = 0; volumeMultiplierChange < steps; ++volumeMultiplierChange) {
volumeMultiplierAmplitudeChange = this.release.doStep(steps);
volumeAttackAmplitudeChange = this.attack.doStep(steps);
if (muted) {
pitchChange = (volumeMultiplierAmplitudeChange * (this.release.end - this.release.start) >> 8) + this.release.start;
} else {
pitchChange = (volumeAttackAmplitudeChange * (this.release.end - this.release.start) >> 8) + this.release.start;
}
step += 256;
if (step >= pitchChange) {
step = 0;
muted = !muted;
}
if (muted) {
toneSamples[volumeMultiplierChange] = 0;
}
}
}
if (this.delayTime > 0 && this.delayDecay > 0) {
step = (int) ((double) this.delayTime * duration);
for (pitchChange = step; pitchChange < steps; ++pitchChange) {
samples = toneSamples;
samples[pitchChange] += toneSamples[pitchChange - step] * this.delayDecay / 100;
}
}
if (this.filter.pairs[0] > 0 || this.filter.pairs[1] > 0) {
this.filterEnvelope.reset();
step = this.filterEnvelope.doStep(steps + 1);
pitchChange = this.filter.compute(0, (float) step / 65536.0F);
volumeChange = this.filter.compute(1, (float) step / 65536.0F);
if (steps >= pitchChange + volumeChange) {
volumeMultiplierChange = 0;
volumeMultiplierAmplitudeChange = Math.min(volumeChange, steps - pitchChange);
//TODO: Finish refactoring
int var17;
while (volumeMultiplierChange < volumeMultiplierAmplitudeChange) {
volumeAttackAmplitudeChange = (int) ((long) toneSamples[volumeMultiplierChange + pitchChange] * (long) SoundFilter.forwardMultiplier >> 16);
for (var17 = 0; var17 < pitchChange; ++var17) {
volumeAttackAmplitudeChange += (int) ((long) toneSamples[volumeMultiplierChange + pitchChange - 1 - var17] * (long) SoundFilter.coefficients[0][var17] >> 16);
}
for (var17 = 0; var17 < volumeMultiplierChange; ++var17) {
volumeAttackAmplitudeChange -= (int) ((long) toneSamples[volumeMultiplierChange - 1 - var17] * (long) SoundFilter.coefficients[1][var17] >> 16);
}
toneSamples[volumeMultiplierChange] = volumeAttackAmplitudeChange;
step = this.filterEnvelope.doStep(steps + 1);
++volumeMultiplierChange;
}
volumeMultiplierAmplitudeChange = 128;
while (true) {
if (volumeMultiplierAmplitudeChange > steps - pitchChange) {
volumeMultiplierAmplitudeChange = steps - pitchChange;
}
int var18;
while (volumeMultiplierChange < volumeMultiplierAmplitudeChange) {
var17 = (int) ((long) toneSamples[volumeMultiplierChange + pitchChange] * (long) SoundFilter.forwardMultiplier >> 16);
for (var18 = 0; var18 < pitchChange; ++var18) {
var17 += (int) ((long) toneSamples[volumeMultiplierChange + pitchChange - 1 - var18] * (long) SoundFilter.coefficients[0][var18] >> 16);
}
for (var18 = 0; var18 < volumeChange; ++var18) {
var17 -= (int) ((long) toneSamples[volumeMultiplierChange - 1 - var18] * (long) SoundFilter.coefficients[1][var18] >> 16);
}
toneSamples[volumeMultiplierChange] = var17;
step = this.filterEnvelope.doStep(steps + 1);
++volumeMultiplierChange;
}
if (volumeMultiplierChange >= steps - pitchChange) {
while (volumeMultiplierChange < steps) {
var17 = 0;
for (var18 = volumeMultiplierChange + pitchChange - steps; var18 < pitchChange; ++var18) {
var17 += (int) ((long) toneSamples[volumeMultiplierChange + pitchChange - 1 - var18] * (long) SoundFilter.coefficients[0][var18] >> 16);
}
for (var18 = 0; var18 < volumeChange; ++var18) {
var17 -= (int) ((long) toneSamples[volumeMultiplierChange - 1 - var18] * (long) SoundFilter.coefficients[1][var18] >> 16);
}
toneSamples[volumeMultiplierChange] = var17;
this.filterEnvelope.doStep(steps + 1);
++volumeMultiplierChange;
}
break;
}
pitchChange = this.filter.compute(0, (float) step / 65536.0F);
volumeChange = this.filter.compute(1, (float) step / 65536.0F);
volumeMultiplierAmplitudeChange += 128;
}
}
}
for (step = 0; step < steps; ++step) {
if (toneSamples[step] < -32768) {
toneSamples[step] = -32768;
}
if (toneSamples[step] > 32767) {
toneSamples[step] = 32767;
}
}
}
return toneSamples;
}
final int evaluateWave(int var1, int var2, int var3) {
if (var3 == 1) {
return (var1 & 32767) < 16384 ? var2 : -var2;
} else if (var3 == 2) {
return toneSine[var1 & 32767] * var2 >> 14;
} else if (var3 == 3) {
return (var2 * (var1 & 32767) >> 14) - var2;
} else {
return var3 == 4 ? var2 * toneNoise[var1 / 2607 & 32767] : 0;
}
}
final void decode(Buffer var1) {
this.pitch = new SoundEnvelope();
this.pitch.decode(var1);
this.volume = new SoundEnvelope();
this.volume.decode(var1);
int var2 = var1.readUnsignedByte();
if (var2 != 0) {
--var1.offset;
this.pitchModifier = new SoundEnvelope();
this.pitchModifier.decode(var1);
this.pitchModifierAmplitude = new SoundEnvelope();
this.pitchModifierAmplitude.decode(var1);
}
var2 = var1.readUnsignedByte();
if (var2 != 0) {
--var1.offset;
this.volumeMultiplier = new SoundEnvelope();
this.volumeMultiplier.decode(var1);
this.volumeMultiplierAmplitude = new SoundEnvelope();
this.volumeMultiplierAmplitude.decode(var1);
}
var2 = var1.readUnsignedByte();
if (var2 != 0) {
--var1.offset;
this.release = new SoundEnvelope();
this.release.decode(var1);
this.attack = new SoundEnvelope();
this.attack.decode(var1);
}
for (int var3 = 0; var3 < 10; ++var3) {
int var4 = var1.readUShortSmart();
if (var4 == 0) {
break;
}
this.oscillatorVolume[var3] = var4;
this.oscillatorPitch[var3] = var1.readShortSmart();
this.oscillatorDelays[var3] = var1.readUShortSmart();
}
this.delayTime = var1.readUShortSmart();
this.delayDecay = var1.readUShortSmart();
this.duration = var1.readUnsignedShort();
this.offset = var1.readUnsignedShort();
this.filter = new SoundFilter();
this.filterEnvelope = new SoundEnvelope();
this.filter.decode(var1, this.filterEnvelope);
}
}
<file_sep>/runescape-client/src/main/java/AudioPreferences.java
/*
* Audio Preferences class
* Custom settings class that allows for custom resources and modifications
* @author <NAME> (https://github.com/lequietriot)
*/
import java.io.File;
public class AudioPreferences {
public static int sampleRate = 44100;
public static boolean stereoSound = true;
public static boolean useCustomResources = true;
public static boolean writeMusicToFile = false;
public static String customResourceFolder;
public static String musicSaveFile;
public static String SAMPLE_INDEX = "Index = ";
public static String SAMPLE_NAME = "Sample = ";
public static String LOOP_MODE = "Loop Mode = ";
public static String SAMPLE_ROOT_KEY = "Root Key = ";
public static String SAMPLE_KEY_INDEX = "Sample Key = ";
public static String MASTER_VOLUME = "Patch Volume = ";
public static String SAMPLE_VOLUME = "Sample Volume = ";
public static String SAMPLE_PAN = "Sample Pan = ";
public static String PARAMETER_1 = "Parameter 1 = ";
public static String PARAMETER_2 = "Parameter 2 = ";
public static String PARAMETER_3 = "Parameter 3 = ";
public static String PARAMETER_4 = "Parameter 4 = ";
public static String PARAMETER_5 = "Parameter 5 = ";
public static String PARAMETER_6 = "Parameter 6 = ";
public static String PARAMETER_7 = "Parameter 7 = ";
public static String ARRAY_1 = "Array 1 = ";
public static String ARRAY_2 = "Array 2 = ";
static {
customResourceFolder = new File("runescape-client/src/test/resources/audio").getAbsolutePath();
/**
if (new File("runescape-client/src/test/resources/audio/output").mkdirs()) {
}
**/
musicSaveFile = new File("runescape-client/src/test/resources/audio/output").getAbsolutePath();
}
}
<file_sep>/runescape-client/src/main/java/NetSocket.java
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import net.runelite.mapping.Export;
import net.runelite.mapping.Implements;
import net.runelite.mapping.ObfuscatedGetter;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("eb")
@Implements("NetSocket")
public final class NetSocket extends AbstractSocket implements Runnable {
@ObfuscatedName("k")
@ObfuscatedSignature(
descriptor = "Loe;"
)
@Export("options_buttons_0Sprite")
static IndexedSprite options_buttons_0Sprite;
@ObfuscatedName("i")
@Export("outputStream")
OutputStream outputStream;
@ObfuscatedName("w")
@Export("inputStream")
InputStream inputStream;
@ObfuscatedName("s")
@Export("socket")
Socket socket;
@ObfuscatedName("a")
@Export("isClosed")
boolean isClosed;
@ObfuscatedName("o")
@ObfuscatedSignature(
descriptor = "Lew;"
)
@Export("taskHandler")
TaskHandler taskHandler;
@ObfuscatedName("g")
@ObfuscatedSignature(
descriptor = "Lev;"
)
@Export("task")
Task task;
@ObfuscatedName("e")
@Export("outBuffer")
byte[] outBuffer;
@ObfuscatedName("p")
@ObfuscatedGetter(
intValue = 23689551
)
@Export("outLength")
int outLength;
@ObfuscatedName("j")
@ObfuscatedGetter(
intValue = -1817332035
)
@Export("outOffset")
int outOffset;
@ObfuscatedName("b")
@Export("exceptionWriting")
boolean exceptionWriting;
@ObfuscatedName("x")
@ObfuscatedGetter(
intValue = 401992191
)
@Export("bufferLength")
final int bufferLength;
@ObfuscatedName("y")
@ObfuscatedGetter(
intValue = -955072145
)
@Export("maxPacketLength")
final int maxPacketLength;
@ObfuscatedSignature(
descriptor = "(Ljava/net/Socket;Lew;I)V"
)
public NetSocket(Socket var1, TaskHandler var2, int var3) throws IOException {
this.isClosed = false; // L: 16
this.outLength = 0; // L: 20
this.outOffset = 0; // L: 21
this.exceptionWriting = false; // L: 22
this.taskHandler = var2; // L: 28
this.socket = var1; // L: 29
this.bufferLength = var3; // L: 30
this.maxPacketLength = var3 - 100; // L: 31
this.socket.setSoTimeout(30000); // L: 32
this.socket.setTcpNoDelay(true); // L: 33
this.socket.setReceiveBufferSize(65536); // L: 34
this.socket.setSendBufferSize(65536); // L: 35
this.inputStream = this.socket.getInputStream(); // L: 36
this.outputStream = this.socket.getOutputStream(); // L: 37
}
@ObfuscatedName("i")
@ObfuscatedSignature(
descriptor = "(B)V",
garbageValue = "1"
)
@Export("close")
public void close() {
if (!this.isClosed) { // L: 41
synchronized(this) { // L: 42
this.isClosed = true; // L: 43
this.notifyAll(); // L: 44
} // L: 45
if (this.task != null) { // L: 46
while (this.task.status == 0) { // L: 47
FloorUnderlayDefinition.method3190(1L); // L: 48
}
if (this.task.status == 1) { // L: 50
try {
((Thread)this.task.result).join(); // L: 52
} catch (InterruptedException var3) { // L: 54
}
}
}
this.task = null; // L: 57
}
} // L: 58
@ObfuscatedName("w")
@ObfuscatedSignature(
descriptor = "(I)I",
garbageValue = "1953698452"
)
@Export("readUnsignedByte")
public int readUnsignedByte() throws IOException {
return this.isClosed ? 0 : this.inputStream.read(); // L: 65 66
}
@ObfuscatedName("s")
@ObfuscatedSignature(
descriptor = "(I)I",
garbageValue = "-1632705310"
)
@Export("available")
public int available() throws IOException {
return this.isClosed ? 0 : this.inputStream.available(); // L: 70 71
}
@ObfuscatedName("a")
@ObfuscatedSignature(
descriptor = "(II)Z",
garbageValue = "-1771919747"
)
@Export("isAvailable")
public boolean isAvailable(int var1) throws IOException {
if (this.isClosed) { // L: 75
return false;
} else {
return this.inputStream.available() >= var1; // L: 76
}
}
@ObfuscatedName("o")
@ObfuscatedSignature(
descriptor = "([BIII)I",
garbageValue = "-1246528305"
)
@Export("read")
public int read(byte[] var1, int var2, int var3) throws IOException {
if (this.isClosed) { // L: 80
return 0;
} else {
int var4;
int var5;
for (var4 = var3; var3 > 0; var3 -= var5) { // L: 81 82 86
var5 = this.inputStream.read(var1, var2, var3); // L: 83
if (var5 <= 0) { // L: 84
throw new EOFException();
}
var2 += var5; // L: 85
}
return var4; // L: 88
}
}
@ObfuscatedName("g")
@ObfuscatedSignature(
descriptor = "([BIIB)V",
garbageValue = "0"
)
@Export("write0")
void write0(byte[] var1, int var2, int var3) throws IOException {
if (!this.isClosed) { // L: 92
if (this.exceptionWriting) { // L: 93
this.exceptionWriting = false; // L: 94
throw new IOException(); // L: 95
} else {
if (this.outBuffer == null) { // L: 97
this.outBuffer = new byte[this.bufferLength];
}
synchronized(this) { // L: 98
for (int var5 = 0; var5 < var3; ++var5) { // L: 99
this.outBuffer[this.outOffset] = var1[var5 + var2]; // L: 100
this.outOffset = (this.outOffset + 1) % this.bufferLength; // L: 101
if ((this.outLength + this.maxPacketLength) % this.bufferLength == this.outOffset) { // L: 102
throw new IOException(); // L: 103
}
}
if (this.task == null) { // L: 106
this.task = this.taskHandler.newThreadTask(this, 3); // L: 107
}
this.notifyAll(); // L: 109
}
}
}
} // L: 111
@ObfuscatedName("e")
@ObfuscatedSignature(
descriptor = "([BIII)V",
garbageValue = "-748791607"
)
@Export("write")
public void write(byte[] var1, int var2, int var3) throws IOException {
this.write0(var1, var2, var3); // L: 160
} // L: 161
protected void finalize() {
this.close(); // L: 61
} // L: 62
public void run() {
try {
while (true) {
label84: {
int var1;
int var2;
synchronized(this) { // L: 118
if (this.outOffset == this.outLength) { // L: 119
if (this.isClosed) { // L: 120
break label84;
}
try {
this.wait(); // L: 122
} catch (InterruptedException var10) { // L: 124
}
}
var2 = this.outLength; // L: 126
if (this.outOffset >= this.outLength) { // L: 127
var1 = this.outOffset - this.outLength;
} else {
var1 = this.bufferLength - this.outLength; // L: 128
}
}
if (var1 <= 0) { // L: 130
continue;
}
try {
this.outputStream.write(this.outBuffer, var2, var1); // L: 132
} catch (IOException var9) { // L: 134
this.exceptionWriting = true; // L: 135
}
this.outLength = (var1 + this.outLength) % this.bufferLength; // L: 137
try {
if (this.outLength == this.outOffset) { // L: 139
this.outputStream.flush();
}
} catch (IOException var8) { // L: 141
this.exceptionWriting = true; // L: 142
}
continue;
}
try {
if (this.inputStream != null) { // L: 147
this.inputStream.close();
}
if (this.outputStream != null) { // L: 148
this.outputStream.close();
}
if (this.socket != null) { // L: 149
this.socket.close();
}
} catch (IOException var7) { // L: 151
}
this.outBuffer = null; // L: 152
break;
}
} catch (Exception var12) { // L: 154
MilliClock.RunException_sendStackTrace((String)null, var12); // L: 155
}
} // L: 157
@ObfuscatedName("i")
@ObfuscatedSignature(
descriptor = "(IIII)J",
garbageValue = "965371090"
)
static long method2923(int var0, int var1, int var2) {
return (long)(var2 << 16 | var0 << 8 | var1); // L: 38
}
@ObfuscatedName("fp")
@ObfuscatedSignature(
descriptor = "(I)V",
garbageValue = "1408375765"
)
@Export("load")
static void load() {
int var25;
if (Client.titleLoadingStage == 0) { // L: 2002
GameBuild.scene = new Scene(4, 104, 104, Tiles.Tiles_heights); // L: 2003
for (var25 = 0; var25 < 4; ++var25) { // L: 2004
Client.collisionMaps[var25] = new CollisionMap(104, 104);
}
class10.sceneMinimapSprite = new SpritePixels(512, 512); // L: 2005
Login.Login_loadingText = "Starting game engine..."; // L: 2006
Login.Login_loadingPercent = 5; // L: 2007
Client.titleLoadingStage = 20; // L: 2008
} else if (Client.titleLoadingStage == 20) { // L: 2011
Login.Login_loadingText = "Prepared visibility map"; // L: 2012
Login.Login_loadingPercent = 10; // L: 2013
Client.titleLoadingStage = 30; // L: 2014
} else if (Client.titleLoadingStage == 30) { // L: 2017
InvDefinition.archive0 = UrlRequest.newArchive(0, false, true, true); // L: 2018
ApproximateRouteStrategy.archive1 = UrlRequest.newArchive(1, false, true, true); // L: 2019
class1.archive2 = UrlRequest.newArchive(2, true, false, true); // L: 2020
ParamComposition.archive3 = UrlRequest.newArchive(3, false, true, true); // L: 2021
class12.archive4 = UrlRequest.newArchive(4, false, true, true); // L: 2022
class11.archive5 = UrlRequest.newArchive(5, true, true, true); // L: 2023
Messages.archive6 = UrlRequest.newArchive(6, true, true, true); // L: 2024
HorizontalAlignment.archive7 = UrlRequest.newArchive(7, false, true, true); // L: 2025
GrandExchangeOfferOwnWorldComparator.archive8 = UrlRequest.newArchive(8, false, true, true); // L: 2026
SecureRandomFuture.archive9 = UrlRequest.newArchive(9, false, true, true); // L: 2027
ChatChannel.archive10 = UrlRequest.newArchive(10, false, true, true); // L: 2028
AbstractWorldMapIcon.archive11 = UrlRequest.newArchive(11, false, true, true); // L: 2029
class14.archive12 = UrlRequest.newArchive(12, false, true, true); // L: 2030
LoginScreenAnimation.archive13 = UrlRequest.newArchive(13, true, false, true); // L: 2031
SecureRandomCallable.archive14 = UrlRequest.newArchive(14, false, true, true); // L: 2032
Archive.archive15 = UrlRequest.newArchive(15, false, true, true); // L: 2033
Message.archive17 = UrlRequest.newArchive(17, true, true, true); // L: 2034
Messages.archive18 = UrlRequest.newArchive(18, false, true, true); // L: 2035
class111.archive19 = UrlRequest.newArchive(19, false, true, true); // L: 2036
GrandExchangeOfferOwnWorldComparator.archive20 = UrlRequest.newArchive(20, false, true, true); // L: 2037
Login.Login_loadingText = "Connecting to update server"; // L: 2038
Login.Login_loadingPercent = 20; // L: 2039
Client.titleLoadingStage = 40; // L: 2040
} else if (Client.titleLoadingStage == 40) { // L: 2043
byte var39 = 0; // L: 2044
var25 = var39 + InvDefinition.archive0.percentage() * 4 / 100; // L: 2045
var25 += ApproximateRouteStrategy.archive1.percentage() * 4 / 100; // L: 2046
var25 += class1.archive2.percentage() * 2 / 100; // L: 2047
var25 += ParamComposition.archive3.percentage() * 2 / 100; // L: 2048
var25 += class12.archive4.percentage() * 6 / 100; // L: 2049
var25 += class11.archive5.percentage() * 4 / 100; // L: 2050
var25 += Messages.archive6.percentage() * 2 / 100; // L: 2051
var25 += HorizontalAlignment.archive7.percentage() * 56 / 100; // L: 2052
var25 += GrandExchangeOfferOwnWorldComparator.archive8.percentage() * 2 / 100; // L: 2053
var25 += SecureRandomFuture.archive9.percentage() * 2 / 100; // L: 2054
var25 += ChatChannel.archive10.percentage() * 2 / 100; // L: 2055
var25 += AbstractWorldMapIcon.archive11.percentage() * 2 / 100; // L: 2056
var25 += class14.archive12.percentage() * 2 / 100; // L: 2057
var25 += LoginScreenAnimation.archive13.percentage() * 2 / 100; // L: 2058
var25 += SecureRandomCallable.archive14.percentage() * 2 / 100; // L: 2059
var25 += Archive.archive15.percentage() * 2 / 100; // L: 2060
var25 += class111.archive19.percentage() / 100; // L: 2061
var25 += Messages.archive18.percentage() / 100; // L: 2062
var25 += GrandExchangeOfferOwnWorldComparator.archive20.percentage() / 100; // L: 2063
var25 += Message.archive17.method5260() && Message.archive17.isFullyLoaded() ? 1 : 0; // L: 2064
if (var25 != 100) { // L: 2065
if (var25 != 0) { // L: 2066
Login.Login_loadingText = "Checking for updates - " + var25 + "%";
}
Login.Login_loadingPercent = 30; // L: 2067
} else {
UserComparator8.method2460(InvDefinition.archive0, "Animations"); // L: 2070
UserComparator8.method2460(ApproximateRouteStrategy.archive1, "Skeletons"); // L: 2071
UserComparator8.method2460(class12.archive4, "Sound FX"); // L: 2072
UserComparator8.method2460(class11.archive5, "Maps"); // L: 2073
UserComparator8.method2460(Messages.archive6, "Music Tracks"); // L: 2074
UserComparator8.method2460(HorizontalAlignment.archive7, "Models"); // L: 2075
UserComparator8.method2460(GrandExchangeOfferOwnWorldComparator.archive8, "Sprites"); // L: 2076
UserComparator8.method2460(AbstractWorldMapIcon.archive11, "Music Jingles"); // L: 2077
UserComparator8.method2460(SecureRandomCallable.archive14, "Music Samples"); // L: 2078
UserComparator8.method2460(Archive.archive15, "Music Patches"); // L: 2079
UserComparator8.method2460(class111.archive19, "World Map"); // L: 2080
UserComparator8.method2460(Messages.archive18, "World Map Geography"); // L: 2081
UserComparator8.method2460(GrandExchangeOfferOwnWorldComparator.archive20, "World Map Ground"); // L: 2082
class111.spriteIds = new GraphicsDefaults(); // L: 2083
class111.spriteIds.decode(Message.archive17); // L: 2084
Login.Login_loadingText = "Loaded update list"; // L: 2085
Login.Login_loadingPercent = 30; // L: 2086
Client.titleLoadingStage = 45; // L: 2087
}
} else {
Archive var27;
Archive var28;
Archive var29;
if (Client.titleLoadingStage == 45) { // L: 2090
boolean var38 = !Client.isLowDetail; // L: 2091
UserComparator2.sampleRate = AudioPreferences.sampleRate; // L: 2094 - Original: 22050
PcmPlayer.PcmPlayer_stereo = AudioPreferences.stereoSound; // L: 2095 - Original - var38
PcmPlayer.field272 = 2; // L: 2096
MidiPcmStream var34 = new MidiPcmStream(); // L: 2098
var34.method4761(9, 128); // L: 2099
HealthBar.pcmPlayer0 = class112.method2522(GameEngine.taskHandler, 0, AudioPreferences.sampleRate); // L: 2100 - Original: 22050
HealthBar.pcmPlayer0.setStream(var34); // L: 2101
var27 = Archive.archive15; // L: 2102
var28 = SecureRandomCallable.archive14; // L: 2103
var29 = class12.archive4; // L: 2104
class247.musicPatchesArchive = var27; // L: 2106
class247.musicSamplesArchive = var28; // L: 2107
class408.soundEffectsArchive = var29; // L: 2108
class247.midiPcmStream = var34; // L: 2109
ScriptEvent.pcmPlayer1 = class112.method2522(GameEngine.taskHandler, 1, 2048); // L: 2111
BuddyRankComparator.pcmStreamMixer = new PcmStreamMixer(); // L: 2112
ScriptEvent.pcmPlayer1.setStream(BuddyRankComparator.pcmStreamMixer); // L: 2113
FontName.decimator = new Decimator(AudioPreferences.sampleRate, UserComparator2.sampleRate); // L: 2114 - Original: 22050
Login.Login_loadingText = "Prepared sound engine"; // L: 2115
Login.Login_loadingPercent = 35; // L: 2116
Client.titleLoadingStage = 50; // L: 2117
MenuAction.WorldMapElement_fonts = new Fonts(GrandExchangeOfferOwnWorldComparator.archive8, LoginScreenAnimation.archive13); // L: 2118
} else {
int var1;
if (Client.titleLoadingStage == 50) { // L: 2121
FontName[] var33 = new FontName[]{FontName.FontName_verdana11, FontName.FontName_verdana15, FontName.FontName_plain12, FontName.FontName_bold12, FontName.FontName_plain11, FontName.FontName_verdana13}; // L: 2124
var1 = var33.length; // L: 2126
Fonts var35 = MenuAction.WorldMapElement_fonts; // L: 2127
FontName[] var36 = new FontName[]{FontName.FontName_verdana11, FontName.FontName_verdana15, FontName.FontName_plain12, FontName.FontName_bold12, FontName.FontName_plain11, FontName.FontName_verdana13}; // L: 2130
Client.fontsMap = var35.createMap(var36); // L: 2132
if (Client.fontsMap.size() < var1) { // L: 2133
Login.Login_loadingText = "Loading fonts - " + Client.fontsMap.size() * 100 / var1 + "%"; // L: 2134
Login.Login_loadingPercent = 40; // L: 2135
} else {
FriendLoginUpdate.fontPlain11 = (Font)Client.fontsMap.get(FontName.FontName_plain11); // L: 2138
class6.fontPlain12 = (Font)Client.fontsMap.get(FontName.FontName_plain12); // L: 2139
Login.fontBold12 = (Font)Client.fontsMap.get(FontName.FontName_bold12); // L: 2140
class54.platformInfo = Client.platformInfoProvider.get(); // L: 2141
Login.Login_loadingText = "Loaded fonts"; // L: 2142
Login.Login_loadingPercent = 40; // L: 2143
Client.titleLoadingStage = 60; // L: 2144
}
} else {
int var3;
int var4;
Archive var26;
if (Client.titleLoadingStage == 60) { // L: 2147
var26 = ChatChannel.archive10; // L: 2149
var27 = GrandExchangeOfferOwnWorldComparator.archive8; // L: 2150
var3 = 0; // L: 2152
String[] var37 = Login.field885; // L: 2154
int var30;
String var31;
for (var30 = 0; var30 < var37.length; ++var30) { // L: 2155
var31 = var37[var30]; // L: 2156
if (var26.tryLoadFileByNames(var31, "")) { // L: 2158
++var3;
}
}
var37 = Login.field871; // L: 2163
for (var30 = 0; var30 < var37.length; ++var30) { // L: 2164
var31 = var37[var30]; // L: 2165
if (var27.tryLoadFileByNames(var31, "")) { // L: 2167
++var3;
}
}
var4 = ReflectionCheck.method1115(); // L: 2174
if (var3 < var4) { // L: 2175
Login.Login_loadingText = "Loading title screen - " + var3 * 100 / var4 + "%"; // L: 2176
Login.Login_loadingPercent = 50; // L: 2177
} else {
Login.Login_loadingText = "Loaded title screen"; // L: 2180
Login.Login_loadingPercent = 50; // L: 2181
WorldMapData_1.updateGameState(5); // L: 2182
Client.titleLoadingStage = 70; // L: 2183
}
} else if (Client.titleLoadingStage == 70) { // L: 2186
if (!class1.archive2.isFullyLoaded()) { // L: 2187
Login.Login_loadingText = "Loading config - " + class1.archive2.loadPercent() + "%"; // L: 2188
Login.Login_loadingPercent = 60; // L: 2189
} else {
Archive var32 = class1.archive2; // L: 2192
FloorOverlayDefinition.FloorOverlayDefinition_archive = var32; // L: 2194
var26 = class1.archive2; // L: 2196
FloorUnderlayDefinition.FloorUnderlayDefinition_archive = var26; // L: 2198
var27 = class1.archive2; // L: 2200
var28 = HorizontalAlignment.archive7; // L: 2201
KitDefinition.KitDefinition_archive = var27; // L: 2203
KitDefinition.KitDefinition_modelsArchive = var28; // L: 2204
class67.KitDefinition_fileCount = KitDefinition.KitDefinition_archive.getGroupFileCount(3); // L: 2205
var29 = class1.archive2; // L: 2207
Archive var5 = HorizontalAlignment.archive7; // L: 2208
boolean var6 = Client.isLowDetail; // L: 2209
ObjectComposition.ObjectDefinition_archive = var29; // L: 2211
ObjectComposition.ObjectDefinition_modelsArchive = var5; // L: 2212
ObjectComposition.ObjectDefinition_isLowDetail = var6; // L: 2213
Archive var7 = class1.archive2; // L: 2215
Archive var8 = HorizontalAlignment.archive7; // L: 2216
NPCComposition.NpcDefinition_archive = var7; // L: 2218
NPCComposition.NpcDefinition_modelArchive = var8; // L: 2219
class28.method405(class1.archive2); // L: 2221
Archive var9 = class1.archive2; // L: 2222
Archive var10 = HorizontalAlignment.archive7; // L: 2223
boolean var11 = Client.isMembersWorld; // L: 2224
Font var12 = FriendLoginUpdate.fontPlain11; // L: 2225
DirectByteArrayCopier.ItemDefinition_archive = var9; // L: 2227
HealthBarDefinition.ItemDefinition_modelArchive = var10; // L: 2228
BuddyRankComparator.ItemDefinition_inMembersWorld = var11; // L: 2229
class129.ItemDefinition_fileCount = DirectByteArrayCopier.ItemDefinition_archive.getGroupFileCount(10); // L: 2230
SoundSystem.ItemDefinition_fontPlain11 = var12; // L: 2231
Archive var13 = class1.archive2; // L: 2233
Archive var14 = InvDefinition.archive0; // L: 2234
Archive var15 = ApproximateRouteStrategy.archive1; // L: 2235
SequenceDefinition.SequenceDefinition_archive = var13; // L: 2237
SequenceDefinition.SequenceDefinition_animationsArchive = var14; // L: 2238
SequenceDefinition.SequenceDefinition_skeletonsArchive = var15; // L: 2239
Archive var16 = class1.archive2; // L: 2241
Archive var17 = HorizontalAlignment.archive7; // L: 2242
SpotAnimationDefinition.SpotAnimationDefinition_archive = var16; // L: 2244
class389.SpotAnimationDefinition_modelArchive = var17; // L: 2245
HealthBarUpdate.method2183(class1.archive2); // L: 2247
Players.method2327(class1.archive2); // L: 2248
class128.method2720(ParamComposition.archive3, HorizontalAlignment.archive7, GrandExchangeOfferOwnWorldComparator.archive8, LoginScreenAnimation.archive13); // L: 2249
Archive var18 = class1.archive2; // L: 2250
InvDefinition.InvDefinition_archive = var18; // L: 2252
UserComparator7.method2463(class1.archive2); // L: 2254
MouseRecorder.method2093(class1.archive2); // L: 2255
class28.method400(class1.archive2); // L: 2256
FileSystem.field1564 = new class387(RouteStrategy.field1986, 54, MouseHandler.clientLanguage, class1.archive2); // L: 2257
class240.HitSplatDefinition_cachedSprites = new class387(RouteStrategy.field1986, 47, MouseHandler.clientLanguage, class1.archive2); // L: 2258
Message.varcs = new Varcs(); // L: 2259
class20.method295(class1.archive2, GrandExchangeOfferOwnWorldComparator.archive8, LoginScreenAnimation.archive13); // L: 2260
Archive var19 = class1.archive2; // L: 2261
Archive var20 = GrandExchangeOfferOwnWorldComparator.archive8; // L: 2262
HealthBarDefinition.HealthBarDefinition_archive = var19; // L: 2264
HealthBarDefinition.field1658 = var20; // L: 2265
Archive var21 = class1.archive2; // L: 2267
Archive var22 = GrandExchangeOfferOwnWorldComparator.archive8; // L: 2268
WorldMapElement.WorldMapElement_archive = var22; // L: 2270
if (var21.isFullyLoaded()) { // L: 2271
WorldMapElement.WorldMapElement_count = var21.getGroupFileCount(35); // L: 2274
WorldMapElement.WorldMapElement_cached = new WorldMapElement[WorldMapElement.WorldMapElement_count]; // L: 2275
for (int var23 = 0; var23 < WorldMapElement.WorldMapElement_count; ++var23) { // L: 2276
byte[] var24 = var21.takeFile(35, var23); // L: 2277
WorldMapElement.WorldMapElement_cached[var23] = new WorldMapElement(var23); // L: 2278
if (var24 != null) { // L: 2279
WorldMapElement.WorldMapElement_cached[var23].decode(new Buffer(var24)); // L: 2280
WorldMapElement.WorldMapElement_cached[var23].method3008(); // L: 2281
}
}
}
Login.Login_loadingText = "Loaded config"; // L: 2285
Login.Login_loadingPercent = 60; // L: 2286
Client.titleLoadingStage = 80; // L: 2287
}
} else if (Client.titleLoadingStage == 80) { // L: 2290
var25 = 0; // L: 2291
if (class114.compass == null) { // L: 2292
class114.compass = WorldMapSection0.SpriteBuffer_getSprite(GrandExchangeOfferOwnWorldComparator.archive8, class111.spriteIds.compass, 0);
} else {
++var25; // L: 2293
}
if (BoundaryObject.redHintArrowSprite == null) { // L: 2294
BoundaryObject.redHintArrowSprite = WorldMapSection0.SpriteBuffer_getSprite(GrandExchangeOfferOwnWorldComparator.archive8, class111.spriteIds.field4008, 0);
} else {
++var25; // L: 2295
}
if (TriBool.mapSceneSprites == null) { // L: 2296
TriBool.mapSceneSprites = UserComparator5.method2478(GrandExchangeOfferOwnWorldComparator.archive8, class111.spriteIds.mapScenes, 0);
} else {
++var25; // L: 2297
}
if (Client.headIconPkSprites == null) { // L: 2298
Client.headIconPkSprites = class21.method312(GrandExchangeOfferOwnWorldComparator.archive8, class111.spriteIds.headIconsPk, 0);
} else {
++var25; // L: 2299
}
if (ServerPacket.headIconPrayerSprites == null) { // L: 2300
ServerPacket.headIconPrayerSprites = class21.method312(GrandExchangeOfferOwnWorldComparator.archive8, class111.spriteIds.field4011, 0);
} else {
++var25; // L: 2301
}
if (DevicePcmPlayerProvider.headIconHintSprites == null) { // L: 2302
DevicePcmPlayerProvider.headIconHintSprites = class21.method312(GrandExchangeOfferOwnWorldComparator.archive8, class111.spriteIds.field4012, 0);
} else {
++var25; // L: 2303
}
if (WorldMapIcon_0.mapMarkerSprites == null) { // L: 2304
WorldMapIcon_0.mapMarkerSprites = class21.method312(GrandExchangeOfferOwnWorldComparator.archive8, class111.spriteIds.field4013, 0);
} else {
++var25; // L: 2305
}
if (UserComparator10.crossSprites == null) { // L: 2306
UserComparator10.crossSprites = class21.method312(GrandExchangeOfferOwnWorldComparator.archive8, class111.spriteIds.field4014, 0);
} else {
++var25; // L: 2307
}
if (class115.mapDotSprites == null) { // L: 2308
class115.mapDotSprites = class21.method312(GrandExchangeOfferOwnWorldComparator.archive8, class111.spriteIds.field4010, 0);
} else {
++var25; // L: 2309
}
if (GameEngine.scrollBarSprites == null) { // L: 2310
GameEngine.scrollBarSprites = UserComparator5.method2478(GrandExchangeOfferOwnWorldComparator.archive8, class111.spriteIds.field4018, 0);
} else {
++var25; // L: 2311
}
if (class7.modIconSprites == null) { // L: 2312
class7.modIconSprites = UserComparator5.method2478(GrandExchangeOfferOwnWorldComparator.archive8, class111.spriteIds.field4016, 0);
} else {
++var25; // L: 2313
}
if (var25 < 11) { // L: 2314
Login.Login_loadingText = "Loading sprites - " + var25 * 100 / 12 + "%"; // L: 2315
Login.Login_loadingPercent = 70; // L: 2316
} else {
AbstractFont.AbstractFont_modIconSprites = class7.modIconSprites; // L: 2319
BoundaryObject.redHintArrowSprite.normalize(); // L: 2320
var1 = (int)(Math.random() * 21.0D) - 10; // L: 2321
int var2 = (int)(Math.random() * 21.0D) - 10; // L: 2322
var3 = (int)(Math.random() * 21.0D) - 10; // L: 2323
var4 = (int)(Math.random() * 41.0D) - 20; // L: 2324
TriBool.mapSceneSprites[0].shiftColors(var1 + var4, var2 + var4, var4 + var3); // L: 2325
Login.Login_loadingText = "Loaded sprites"; // L: 2326
Login.Login_loadingPercent = 70; // L: 2327
Client.titleLoadingStage = 90; // L: 2328
}
} else if (Client.titleLoadingStage == 90) { // L: 2331
if (!SecureRandomFuture.archive9.isFullyLoaded()) { // L: 2332
Login.Login_loadingText = "Loading textures - " + "0%"; // L: 2333
Login.Login_loadingPercent = 90; // L: 2334
} else {
Varcs.textureProvider = new TextureProvider(SecureRandomFuture.archive9, GrandExchangeOfferOwnWorldComparator.archive8, 20, class408.clientPreferences.brightness, Client.isLowDetail ? 64 : 128); // L: 2337
Rasterizer3D.Rasterizer3D_setTextureLoader(Varcs.textureProvider); // L: 2338
Rasterizer3D.Rasterizer3D_setBrightness(class408.clientPreferences.brightness); // L: 2339
Client.titleLoadingStage = 100; // L: 2340
}
} else if (Client.titleLoadingStage == 100) { // L: 2343
var25 = Varcs.textureProvider.getLoadedPercentage(); // L: 2344
if (var25 < 100) { // L: 2345
Login.Login_loadingText = "Loading textures - " + var25 + "%"; // L: 2346
Login.Login_loadingPercent = 90; // L: 2347
} else {
Login.Login_loadingText = "Loaded textures"; // L: 2350
Login.Login_loadingPercent = 90; // L: 2351
Client.titleLoadingStage = 110; // L: 2352
}
} else if (Client.titleLoadingStage == 110) { // L: 2355
Interpreter.mouseRecorder = new MouseRecorder(); // L: 2356
GameEngine.taskHandler.newThreadTask(Interpreter.mouseRecorder, 10); // L: 2357
Login.Login_loadingText = "Loaded input handler"; // L: 2358
Login.Login_loadingPercent = 92; // L: 2359
Client.titleLoadingStage = 120; // L: 2360
} else if (Client.titleLoadingStage == 120) { // L: 2363
if (!ChatChannel.archive10.tryLoadFileByNames("huffman", "")) { // L: 2364
Login.Login_loadingText = "Loading wordpack - " + 0 + "%"; // L: 2365
Login.Login_loadingPercent = 94; // L: 2366
} else {
Huffman var0 = new Huffman(ChatChannel.archive10.takeFileByNames("huffman", "")); // L: 2369
ItemLayer.method4108(var0); // L: 2370
Login.Login_loadingText = "Loaded wordpack"; // L: 2371
Login.Login_loadingPercent = 94; // L: 2372
Client.titleLoadingStage = 130; // L: 2373
}
} else if (Client.titleLoadingStage == 130) { // L: 2376
if (!ParamComposition.archive3.isFullyLoaded()) { // L: 2377
Login.Login_loadingText = "Loading interfaces - " + ParamComposition.archive3.loadPercent() * 4 / 5 + "%"; // L: 2378
Login.Login_loadingPercent = 96; // L: 2379
} else if (!class14.archive12.isFullyLoaded()) { // L: 2382
Login.Login_loadingText = "Loading interfaces - " + (80 + class14.archive12.loadPercent() / 6) + "%"; // L: 2383
Login.Login_loadingPercent = 96; // L: 2384
} else if (!LoginScreenAnimation.archive13.isFullyLoaded()) { // L: 2387
Login.Login_loadingText = "Loading interfaces - " + (96 + LoginScreenAnimation.archive13.loadPercent() / 50) + "%"; // L: 2388
Login.Login_loadingPercent = 96; // L: 2389
} else {
Login.Login_loadingText = "Loaded interfaces"; // L: 2392
Login.Login_loadingPercent = 98; // L: 2393
Client.titleLoadingStage = 140; // L: 2394
}
} else if (Client.titleLoadingStage == 140) { // L: 2397
Login.Login_loadingPercent = 100; // L: 2398
if (!class111.archive19.tryLoadGroupByName(WorldMapCacheName.field2210.name)) { // L: 2399
Login.Login_loadingText = "Loading world map - " + class111.archive19.groupLoadPercentByName(WorldMapCacheName.field2210.name) / 10 + "%"; // L: 2400
} else {
if (class133.worldMap == null) { // L: 2403
class133.worldMap = new WorldMap(); // L: 2404
class133.worldMap.init(class111.archive19, Messages.archive18, GrandExchangeOfferOwnWorldComparator.archive20, Login.fontBold12, Client.fontsMap, TriBool.mapSceneSprites); // L: 2405
}
Login.Login_loadingText = "Loaded world map"; // L: 2407
Client.titleLoadingStage = 150; // L: 2408
}
} else if (Client.titleLoadingStage == 150) { // L: 2411
WorldMapData_1.updateGameState(10); // L: 2412
}
}
}
}
} // L: 2009 2015 2041 2068 2088 2119 2136 2145 2178 2184 2190 2288 2317 2329 2335 2341 2348 2353 2361 2367 2374 2380 2385 2390 2395 2401 2409 2413 2415
}
<file_sep>/runescape-client/src/main/java/SoundEnvelope.java
/*
* SFX - Sound Envelope class
* @author <NAME> (https://github.com/lequietriot)
*
* Fully refactored using source(s):
* https://www.rune-server.ee/runescape-development/rs2-client/snippets/421977-sound-effects.html
* https://github.com/Jameskmonger/317refactor/blob/master/src/com/jagex/runescape/audio/Envelope.java
*
* TODO: Maybe use ByteBuffer for decoding methods?
*/
public class SoundEnvelope {
int segments;
int[] durations;
int[] phases;
int start;
int end;
int form;
int ticks;
int phaseIndex;
int step;
int amplitude;
int max;
SoundEnvelope() {
this.segments = 2;
this.durations = new int[2];
this.phases = new int[2];
this.durations[1] = 65535;
this.phases[1] = 65535;
}
final void decode(Buffer buffer) {
this.form = buffer.readUnsignedByte();
this.start = buffer.readInt();
this.end = buffer.readInt();
this.decodeSegments(buffer);
}
final void decodeSegments(Buffer buffer) {
this.segments = buffer.readUnsignedByte();
this.durations = new int[this.segments];
this.phases = new int[this.segments];
for (int segment = 0; segment < this.segments; ++segment) {
this.durations[segment] = buffer.readUnsignedShort();
this.phases[segment] = buffer.readUnsignedShort();
}
}
final void reset() {
this.ticks = 0;
this.phaseIndex = 0;
this.step = 0;
this.amplitude = 0;
this.max = 0;
}
final int doStep(int period) {
if (this.max >= this.ticks) {
this.amplitude = this.phases[this.phaseIndex++] << 15;
if (this.phaseIndex >= this.segments) {
this.phaseIndex = this.segments - 1;
}
this.ticks = (int)((double)this.durations[this.phaseIndex] / 65536.0D * (double) period);
if (this.ticks > this.max) {
this.step = ((this.phases[this.phaseIndex] << 15) - this.amplitude) / (this.ticks - this.max);
}
}
this.amplitude += this.step;
++this.max;
return this.amplitude - this.step >> 15;
}
}
|
ab3edb66bf70b929daf153b065184a48a3229436
|
[
"Java"
] | 6
|
Java
|
lequietriot/open-osrs-audio-mod
|
05ad00b5dccfed2e6e3745ffcfcbd7b2a4ea40d9
|
ee16942c2c214fc108222d35a303461410c517a1
|
refs/heads/main
|
<repo_name>simmaco99/Tesi<file_sep>/codici/pattern_matching.sh
#!/bin/bash
file="3nodi.txt"
for i in {1..33}
do
a=`sed -n "${i}p" pattern3nodi.txt`
sed -i -e "s|$a|y($i)|g" $file
done
sed -i -e "s|spa||g" $file
sed -i -e "s|dot{y|f|g" $file
sed -i -e "s|&||g" $file
sed -i -e "s|*+|+|g" $file
<file_sep>/codici/Triple/Condizioni_Iniziali_Triple.cpp
#include<fstream>
#include<iostream>
using namespace std;
ofstream fout("Condizioni_Iniziali_Triple.m");
void StampaVett(int v[], int N, int inv)
{ for(int i=0;i<N; i++)
{fout<<(v[i]-inv)*(v[i]-inv);
if(i<N-1) fout<<";";
}
}
int main()
{
int N,i,j;
char a;
cout<<"Inserisci la dimensione della rete: ";
cin>>N;
cout<<"Per ogni nodo inserire S per infetto o I per sano "<<endl;
int v[N];
for ( i=0;i<N;i++)
{ char_non_valido:
{
cout<<"Nodo "<<i+1<<":";
cin>>a;
if (a=='S' || a=='s') v[i]=1;
else{
if (a=='I'|| a =='i') v[i]=0;
else
goto char_non_valido;
}
}
}
fout<<"S=[";
StampaVett(v,N,0);
fout<<"];\nI=[";
StampaVett(v,N,1);
fout<<"];\n";
fout<<"coppie=[\n";
for(i=1;i<=N;i++){
for(j=1;j<=N;j++){
if(i==j) fout<<"0 ";
else fout<<"S("<<i<<")*I("<<j<<") ";
}
fout<<";";
}
fout<<"]';\n";
fout<<"SS=[\n";
for(i=1;i<=N;i++){
for(j=1;j<=N;j++){
if (i==j)fout<<"0 ";
if (i<j) fout<<"S("<<i<<")*S("<<j<<") ";
if (i>j) fout<<"S("<<j<<")*S("<<i<<") ";
}
fout<<";";
}
fout<<"];\n";
fout<<"b=(G~=0)& (G==triu(G)); \n SS=SS(b==1);\n co= zeros(2*N,1);\n co(2:2:2*N) = I ; \n co(1:2:2*N) = S ; \n co=[co;coppie(G~=0); SS ];";
fout<<"clear S I coppie b SS\n";
}
<file_sep>/README.md
# Tesi
In questo repository è caricato il materiale utilizzato per la stesura della mia tesi triennale dal titolo "Il modello epidemiologico SIR sulle reti complesse".
Nella cartella "codici" sono racchiuse tutte le funzioni/script utilizzati per le sperimentazioni e la creazione delle figure.
Nella cartella "tesi" sono raccolti i sorgenti .tex e il formato PDF della tesi.
|
c8940a5ff4bd42a888bc656219fd10ffcab8d84f
|
[
"Markdown",
"C++",
"Shell"
] | 3
|
Shell
|
simmaco99/Tesi
|
e40dba776ff572fe1b2875fd00bfab0fbad19da8
|
e67b9260bd885c69e636dfd5bb798944f37861c8
|
refs/heads/master
|
<file_sep>package cz.jandys.demo.api;
import cz.jandys.demo.db.Architype;
import cz.jandys.demo.db.DBController;
import cz.jandys.demo.json.JSONProducer;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import java.util.Base64;
import java.util.Random;
@RestController
public class MainController {
private long timechecker = System.currentTimeMillis();
private DBController vinlandDBControler = null;
char[] chars = {'a','b'};
@CrossOrigin(origins = {"http://localhost", "http://10.0.0.1"})
@RequestMapping(value = "/login2", method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
public String Login2(@RequestBody String body){
JSONProducer input = new JSONProducer().fromBody(body);
System.out.println(input.toString());
return "3";
}
@CrossOrigin(origins = "http://localhost:3000")
@RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json")
public String Login(@RequestParam(value = "name") String name, @RequestParam(value = "pass") String pass){
checkTiming();
JSONProducer output = new JSONProducer();
DBController dbController = getDBControler();
if(dbController.loginAttempt(name,pass)){
output.add("status","ok");
output.add("session", dbController.createSession(name));
output.add("name",encode(name));
return output.toString();
}
output.add("status","error");
output.add("error","1057");
output.add("message","The account name is invalid or does not exist or the password is invalid for the account name specified.");
output.add("name",name);
for (int i = 0; i < 6; i++) {
char g =chars[new Random().nextInt(chars.length)];
}
return output.toString();
}
private String encode(String name) {
return Base64.getEncoder().encodeToString(name.getBytes());
}
private String decode(String toDecode){
return new String(Base64.getDecoder().decode(toDecode.getBytes()));
}
@CrossOrigin(origins = "http://localhost:3000")
@RequestMapping(value = "/register", method = RequestMethod.POST, produces = "application/json")
public String Register(@RequestBody String body){
//checkTiming();
JSONProducer output = new JSONProducer();
//DBController dbController = getDBControler();
/*if(dbController.registerAttempt(name,pass,email)){
output.add("status","ok");
output.add("message","register succesful");
output.add("name",name);
output.add("seesionend",String.valueOf(System.currentTimeMillis()+1800000));
output.add("sesioncheck", String.valueOf(new Random(System.currentTimeMillis()).nextInt(Integer.MAX_VALUE)));
return output.toString();
}*/
output.add("status","error");
output.add("message","register failed");
output.add("name",body);
return output.toString();
}
@CrossOrigin(origins = "http://localhost:3000")
@RequestMapping(value = "/session", method = RequestMethod.POST, produces = "application/json")
public String Session(@RequestParam(value = "id") String id, @RequestParam(value = "name") String name){
checkTiming();
DBController dbController = getDBControler();
JSONProducer output = new JSONProducer();
if(dbController.checkSession(decode(name),id)){
output.add("status","ok");
output.add("message", "Session is active and correct");
return output.toString();
}
output.add("status","error");
output.add("error","7001");
output.add("message","The specified session name is invalid.");
return output.toString();
}
private void checkTiming(){
if(System.currentTimeMillis() - timechecker > 1000){
DBController dbController = getDBControler();
dbController.deleteOldSessions();
}
}
private DBController getDBControler(){
if(this.vinlandDBControler == null){
this.vinlandDBControler = new DBController(Architype.MYSQL,"vinlandkings","test","test");
}
return this.vinlandDBControler;
}
}
<file_sep>import CryptoJS from 'crypto-js';
import React from 'react';
import cookie from 'react-cookies';
export class Login extends React.Component{
render() {
return (
<div className="Vinland" id="vLog">
<h2>Vinland Kings</h2>
<div class="login">
<form>
<label><b>Username</b></label>
<input class="uname" type="text" placeholder="Enter Username" required id="nam"></input>
<br/>
<label><b>Password</b></label>
<input class="pass" type="password" placeholder="Enter Password" required id="pwd"></input>
<br/>
<button type="button" onClick={submitHandle} >Login</button>
</form>
</div>
<div class="container">
<span class="errors" id="errorM"></span>
</div>
<div class="container">
<span class="psw">Forgot a <a href="/forgotPassword" class="pswHref">password?</a></span>
</div>
<div class="container">
<span class="reg">Or <a href="/register" class="regHref">register</a> and try Vinland Kings for free.</span>
</div>
</div>
)
}
componentDidMount(){
if(checkSession() === true){
toGame()
}
else{
console.log("IAM UNDEFINED COOKIE")
}
}
}
const datalog = {};
function submitHandle(e) {
var pwdObj = document.getElementById('pwd').value;
var hashPW = CryptoJS.SHA512(pwdObj);
var hashPass = hashPW.toString(CryptoJS.enc.Base64);
var name = document.getElementById('nam').value.toString();
if(name===""||pwdObj===""){
}
else{
let url = `http://localhost:8080/login?name=${name}&pass=${<PASSWORD>}`
doFetch(url).then((data) => {
console.log(data)
datalog.status = data["status"]
datalog.user = data["name"]
if(datalog.status === "ok"){
datalog.session = data["session"]
logUser()
toGame()
}
else{
if(data["error"] === "1057")
{
const nam = document.getElementById('nam')
const pas = document.getElementById('pwd')
nam.style = "border-style: solid;border-color: red;border-width: medium;"
pas.style = "border-style: solid;border-color: red;border-width: medium;"
const erM = document.getElementById('errorM')
erM.innerText = data["message"]
erM.style = ""
//TODO add function that fades error borders after error after some time
}
}
}).catch(function (ex){
console.log('Response parsing failed. Error: ', ex);
});
}
};
function doFetch(url){
return fetch(url,{
method: 'post',
headers:{
'Accept' : 'application/json, text/plain, */*',
'Content-Type': 'application/json',
},
'credentials': 'same-origin'
})
.then(res=>res.json());
}
function logUser(){
let timerino = 60 * 20;
const expiresSet = new Date()
expiresSet.setDate(Date.now() + 1000 * timerino)
cookie.remove('VINLANDSESSION')
cookie.remove('VINLANDUSER')
cookie.save(
'VINLANDSESSION',
datalog.session,
{path: '/',expires:expiresSet,maxAge:timerino,secure:true}
)
cookie.save(
'VINLANDUSER',
datalog.user,
{path: '/',expires:expiresSet,maxAge:timerino,secure:true}
)
console.log(cookie.load('VINLANDSESSION'))
console.log(cookie.load('VINLANDUSER'))
}
function toGame() {
window.location.href = "http://localhost:3000/game"
}
async function checkSession(){
const session = cookie.load('VINLANDSESSION')
const vinusr = cookie.load('VINLANDUSER')
if(session === undefined || vinusr === undefined){
return false;
}
else{
let url = `http://localhost:8080/session?id=${session}&name=${vinusr}`
await doFetch(url).then((data) => {
console.log(data)
if(data["status" === "ok"]){
return true;
}
}).catch(function (ex){
console.log('Response parsing failed. Error: ', ex);
});
}
}
export default Login;<file_sep>const game = () => {
return(
<div>
<h1>This is game</h1>
<h2>Play play play</h2>
<div>
<a href="/character"> Go to an character</a>
</div>
</div>
);
}
export default game;<file_sep>import React, { Component } from 'react';
export class ItemContainer extends React.Component{
constructor(props){
super(props)
this.data = {
"name":"<NAME>",
"dmg":"12",
"slot":"weapon0"
}
}
render() {
return (
<img src={this.getSrc()} draggable={this.props.drag} onDragStart={e=>this.handleDragStart(e,this.data)}></img>
)
}
handeClick(){
}
handleDragStart(e,data){
console.log(e,data);
}
getSrc(){
if(this.props.img === undefined){
return this.getPrefix("items") + 'hPXWfu.png'
}else if(this.props.prefix === undefined){
return this.getPrefix("items")+this.props.img
}
else{
return this.getPrefix(this.props.prefix)+this.props.img
}
}
getPrefix(prefix){
switch(prefix){
case "items":
case "item":
return 'http://localhost/vinland/items/';
default:
return "";
}
}
}
export default ItemContainer;<file_sep>import CryptoJS from 'crypto-js';
const vinland_register = () => {
return(
<div className="Vinland">
<h2>Vinland Kings Register</h2>
<div class="register">
<form>
<label><b>Username</b></label>
<input class="uname" type="text" placeholder="Enter Username" required id="namR"></input>
<br/>
<label><b>Email</b></label>
<input class="email" type="text" placeholder="Enter Email" required id="emailR"></input>
<br/>
<label><b>Password</b></label>
<input class="pass" type="password" placeholder="Enter Password" required id="pwdR"></input>
<br/>
<label><b>Password Again</b></label>
<input class="pass" type="password" placeholder="Enter Password Again" required id="pwd2R"></input>
<br/>
<button type="button" onClick={submitHandle}>Register</button>
</form>
</div>
<div class="container">
<span class="reg">Do you have an account? <a href="/" class="regHref">Login here</a> and play!</span>
</div>
</div>
);
};
function submitHandle(e) {
var namR = document.getElementById('namR').value;
var emailR = document.getElementById('emailR').value;
var pwdR = document.getElementById('pwdR').value;
var pwd2R = document.getElementById('pwd2R').value;
if(namR === "" || emailR === "" || pwdR ==="" || pwd2R ===""){
}
else{
if(pwdR !== pwd2R){
alert("Passwords must match");
}
else{
var hashPW = CryptoJS.SHA512(pwdR);
var hashPass = hashPW.toString(CryptoJS.enc.Base64);
let url = `http://localhost:8080/register?name=${namR}&pass=${hashPass}&email=${emailR}`
doFetch(url).then((data) => {
console.log(data)
}).catch(function (ex){
console.log('Response parsing failed. Error: ', ex);
});
}
}
}
function doFetch(url){
return fetch(url,{
method: 'post',
headers:{
'Accept' : 'application/json, text/plain, */*',
'Content-Type': 'application/json',
},
'credentials': 'same-origin'
})
.then(res=>res.json());
}
export default vinland_register;
|
298ef2229eea12d8b956c9969741a551b0a5df9a
|
[
"JavaScript",
"Java"
] | 5
|
Java
|
Jandys/vinlandkings
|
b694fe38193109a75da535dd28ba25504116fd8e
|
6f5eeb1cc06138494556d390db2b21b10e6c650a
|
refs/heads/master
|
<file_sep># Genkan Device
This is genkan on Raspberry Pi zero wh.
# Struture
WIP: Write the role of golang files `daemon/updateManager`, `deployment/pushNewVersion` and `main.go`
# Installation
1. Move `updater.sh` to `/home/pi`
2. Add `.genkan.env` to `/home/pi`
3. Put `genkan_device` and `updateManager` to `/home/pi`
4. Move `*.service` files to `/etc/systemd/system/`
5. Enable daemons by `sudo systemctl enable genkan # or genkan-updater` and start it by `sudo systemctl start genkan # or genkan-updater`
# Release
TravisCI releases every job automatically only if the commit has tag.
```
$ git add .
$ git commit -m "commit message"
$ git tag v_1.0.0
$ git push origin v_1.0.0
```
# systemd
`genkan.service` and `genkan-updater.service` is files for systemd. They register the 2 jobs as daemons.
They use `.genkan.env` as an environment file. Don't forget to put it properly because it's very hard to debug what happens if it's forgotten...
## Detailed
Cross-compile is realized by `goxc` and the compiled binary is uploaded to GitHub Releases.
After upload, a MQTT message will be published to `genkan/update` with version number as a payload by `pushNewVersion`.
<file_sep>package main
import (
"log"
"os"
"reflect"
"time"
"gobot.io/x/gobot"
"gobot.io/x/gobot/drivers/gpio"
"gobot.io/x/gobot/platforms/mqtt"
"gobot.io/x/gobot/platforms/raspi"
"github.com/JustinTulloss/firebase"
)
type History struct {
Action string `json:",omitempty"`
RanAt string `json:",omitempty"`
}
func PushOpenToFirebase(c firebase.Client) {
PushHistory(&History{Action: "open", RanAt: time.Now().UTC().Format(time.RFC3339)}, c)
}
func PushCloseToFirebase(c firebase.Client) {
PushHistory(&History{Action: "close", RanAt: time.Now().UTC().Format(time.RFC3339)}, c)
}
func PushHistory(h *History, c firebase.Client) {
_, err := c.Push(h, nil)
if err != nil {
log.Fatal(err)
}
}
func main() {
deviceID := os.Getenv("GENKAN_DEVICE_ID")
endpoint := os.Getenv("GENKAN_FIREBASE_ENDPOINT")
auth := os.Getenv("GENKAN_FIREBASE_AUTH")
c := firebase.NewClient(endpoint+"/devices/"+deviceID+"/history", auth, nil)
// mqtt.DEBUG = log.New(os.Stdout, "", 0)
// mqtt.ERROR = log.New(os.Stdout, "", 0)
uri := "tcp://" + os.Getenv("GENKAN_URI")
id := "device"
userName := os.Getenv("GENKAN_USERNAME")
password := os.Getenv("<PASSWORD>")
mqttAdaptor := mqtt.NewAdaptorWithAuth(uri, id, userName, password)
adaptor := raspi.NewAdaptor()
servo := gpio.NewServoDriver(adaptor, "12")
work := func() {
mqttAdaptor.On("genkan/devices/"+deviceID, func(msg mqtt.Message) {
if reflect.DeepEqual(msg.Payload(), []byte("open")) {
servo.Move(uint8(31))
PushOpenToFirebase(c)
} else if reflect.DeepEqual(msg.Payload(), []byte("close")) {
servo.Move(uint8(13))
PushCloseToFirebase(c)
}
})
}
robot := gobot.NewRobot("mqttBot",
[]gobot.Connection{mqttAdaptor},
work,
)
robot.Start()
}
<file_sep>#! /bin/bash
# Download the specific releace
cd /home/pi
curl -sJLO https://github.com/asmsuechan/genkan_device/releases/download/v_$1/genkan_device_$1_linux_arm.tar.gz
tar -zxvf genkan_device_$1_linux_arm.tar.gz
mv genkan_device_$1_linux_arm/genkan_device /home/pi
# Run the downloaded program and pi-blaster
sudo systemctl restart genkan
rm -rf genkan_device_$1_linux_arm/ genkan_device_$1_linux_arm.tar.gz
<file_sep>package main
import (
"flag"
"fmt"
"log"
"net/url"
"os"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
)
func connect(clientId string, uri *url.URL) mqtt.Client {
opts := createClientOptions(clientId, uri)
client := mqtt.NewClient(opts)
token := client.Connect()
for !token.WaitTimeout(3 * time.Second) {
}
if err := token.Error(); err != nil {
log.Fatal(err)
}
return client
}
func createClientOptions(clientId string, uri *url.URL) *mqtt.ClientOptions {
opts := mqtt.NewClientOptions()
opts.AddBroker(fmt.Sprintf("tcp://%s", uri.Host))
opts.SetUsername(uri.User.Username())
password, _ := uri.User.Password()
opts.SetPassword(password)
opts.SetClientID(clientId)
return opts
}
// Usage:
// ./updateManager [version]
// example
// $ ./updateManager 1.0.0
func main() {
uri := os.Getenv("GENKAN_URI")
userName := os.Getenv("GENKAN_USERNAME")
password := os.Getenv("GENKAN_PASSWORD")
cloudmqtturl := "mqtt://" + userName + ":" + password + "@" + uri
parseduri, err := url.Parse(cloudmqtturl)
if err != nil {
// TODO: Send error log to a service (not decided)
log.Fatal(err)
}
client := connect("pub", parseduri)
flag.Parse()
args := flag.Args()
topic := "genkan/update"
token := client.Publish(topic, 0, false, args[0])
token.Wait()
}
|
b1715f05b8bbdeb1c71e25a4f97df5242258a75b
|
[
"Markdown",
"Go",
"Shell"
] | 4
|
Markdown
|
asmsuechan/genkan_device
|
10cc494d84f37037e237da0cece256eb4389db8e
|
cf86fc4915106065105075a43e0cdad478cda8cf
|
refs/heads/master
|
<repo_name>msgpo/youtube-export-helper-for-kodi<file_sep>/yt-export.py
#!/usr/bin/python3
from pyquery import PyQuery
import readline
import requests
from urllib.parse import urlparse
from urllib.parse import parse_qs
from os.path import join as pjoin
def main():
export_path = '/mnt/nfsserver/internal/kodi-data/yt-music-videos/'
while True:
url = rlinput("url: ")
parsed = urlparse(url)
video_id = parse_qs(parsed.query)['v'][0]
r = requests.get(url)
pq = PyQuery(r.text)
title = pq('title').text()
if title.endswith(' - YouTube'):
title = title[:-10]
title = rlinput("title: ", title)
path = "%s%s.strm" % (export_path, title)
with open(path, "w") as f:
content = 'plugin://plugin.video.youtube/play/?video_id=%s' % video_id
f.write(content)
def rlinput(prompt, prefill=''):
readline.set_startup_hook(lambda: readline.insert_text(prefill))
try:
return input(prompt)
finally:
readline.set_startup_hook()
if __name__ == "__main__":
main()
|
60c03ac7c44b1ee9c6d5fc1322a33893aa1fa6f3
|
[
"Python"
] | 1
|
Python
|
msgpo/youtube-export-helper-for-kodi
|
7923343969fb783712c76b95f3b82f4ba5230402
|
0bbc88cb4f33546c3b5e13ad0f759611c6d1bf62
|
refs/heads/master
|
<repo_name>ellil4/Lithopone_sharp<file_sep>/Lithopone/UIComponents/CompSelectionGroup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Media;
namespace Lithopone.UIComponents
{
public class CompSelectionGroup
{
public List<UserControl> mSelections;
public delegate void MouseEnter();
public delegate void MouseLeave();
public delegate void MouseClick();
MouseEnter mEnterFunc;
MouseLeave mLeaveFunc;
MouseClick mClickFunc;
private int mSelIdx = -1;
public void Set(List<UserControl> selections, int selected = -1,
MouseEnter enterFunc = null, MouseLeave leaveFunc = null, MouseClick clickFunc = null)
{
mSelections = selections;
mEnterFunc = enterFunc;
mLeaveFunc = leaveFunc;
mClickFunc = clickFunc;
for (int i = 0; i < mSelections.Count; i++)
{
mSelections[i].MouseEnter +=
new System.Windows.Input.MouseEventHandler(CompSelectionGroup_MouseEnter);
mSelections[i].MouseLeave +=
new System.Windows.Input.MouseEventHandler(CompSelectionGroup_MouseLeave);
mSelections[i].MouseDown +=
new System.Windows.Input.MouseButtonEventHandler(CompSelectionGroup_MouseDown);
}
mSelIdx = selected;
if (mSelIdx > -1)
{
SetUISelected(mSelIdx);
}
}
public void SetUISelected(int index)
{
for (int i = 0; i < mSelections.Count; i++)
{
if (index == i)
{
mSelections[i].BorderBrush = new SolidColorBrush(Color.FromRgb(0, 0, 0));
mSelIdx = i;
}
else
{
mSelections[i].BorderBrush = new SolidColorBrush(Color.FromRgb(255, 255, 255));
}
}
}
void CompSelectionGroup_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (mClickFunc == null)
{
for (int i = 0; i < mSelections.Count; i++)
{
if (sender.Equals(mSelections[i]))
{
mSelections[i].BorderBrush = new SolidColorBrush(Color.FromRgb(0, 0, 0));
mSelIdx = i;
}
else
{
mSelections[i].BorderBrush = new SolidColorBrush(Color.FromRgb(255, 255, 255));
}
}
}
else
{
mClickFunc();
}
}
void CompSelectionGroup_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
if (mLeaveFunc == null)
{
if (getObjectIdx(sender) != mSelIdx)
{
((UserControl)sender).BorderBrush = new SolidColorBrush(Color.FromRgb(255, 255, 255));
}
}
else
{
mLeaveFunc();
}
}
void CompSelectionGroup_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
if (mEnterFunc == null)
{
((UserControl)sender).BorderBrush = new SolidColorBrush(Color.FromRgb(0, 0, 0));
}
else
{
mEnterFunc();
}
}
private int getObjectIdx(object obj)
{
int retval = -1;
int upper = mSelections.Count;
for (int i = 0; i < upper; i++)
{
if (obj.Equals(mSelections[i]))
{
retval = i;
break;
}
}
return retval;
}
public int GetSelectedIndex()
{
return mSelIdx;
}
}
}
<file_sep>/LithoponeReportDLL/ReportUI.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Arora
{
public partial class ReportUI : Form
{
public AroraReport mArora;
public ReportUI(AroraReport arora)
{
InitializeComponent();
mArora = arora;
}
private void button1_Click(object sender, EventArgs e)
{
mArora.PrevPage();
}
private void button2_Click(object sender, EventArgs e)
{
mArora.NextPage();
}
private void button3_Click(object sender, EventArgs e)
{
Close();
}
}
}
<file_sep>/Lithopone/UIComponents/TitlePage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Lithopone.UIComponents
{
/// <summary>
/// TitlePage.xaml 的互動邏輯
/// </summary>
public partial class TitlePage : UserControl
{
public MainWindow mMainWindow;
public TitlePage(MainWindow mw, int sizeX, int sizeY)
{
InitializeComponent();
mMainWindow = mw;
amTitleBlock.Width = sizeX;
amRichTxt.Width = sizeX;
amRichTxt.Height = sizeY - 12 - 56 - 45 - 15;
Canvas.SetTop(button1, sizeY - 56);
Canvas.SetLeft(button1, (sizeX - 116) / 2);
}
private void button1_Click(object sender, RoutedEventArgs e)
{
mMainWindow.OnTitleClose();
}
}
}
<file_sep>/Lithopone/UIComponents/DemogWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Lithopone.UIComponents
{
/// <summary>
/// DemogWindow.xaml 的互動邏輯
/// </summary>
public partial class DemogWindow : Window
{
public MainWindow mMW;
public DemogWindow(MainWindow mw)
{
InitializeComponent();
mMW = mw;
this.WindowStyle = System.Windows.WindowStyle.None;
}
public void OnDemogClose()
{
mMW.mDemogInfo = mMW.mDemogRunner.GetResult();
if (mMW.mDemogInfo != null)
{
mMW.OnDemogClose();
this.Close();
}
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (mMW.mDemogInfo == null)
{
System.Environment.Exit(0);
}
}
}
}
<file_sep>/LithoponeReportDLL/AroraCore.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lithopone.Memory;
using System.IO;
using LibTabCharter;
using NormDistributionLib;
namespace Arora
{
//calculating and saving the scores
public class AroraCore
{
public static String OUT_PATH =
AppDomain.CurrentDomain.BaseDirectory + "AroraAppendableGeneral";
protected Dictionary<int, StItem> mItems;
protected List<StAnswer> mAnswers;
protected Dictionary<String, String> mDemogInfo;
protected StNormAuto mNorm;
protected List<float> mDimzScores;
protected List<double> mDimzPercentile;
protected List<double> mDimzStdScore;
//must override
//abstract public void DoReport();
//abstract protected void ReadResultForm();
public AroraCore()
{
mDimzPercentile = new List<double>();
mDimzScores = new List<float>();
mDimzStdScore = new List<double>();
}
public void SetData(Dictionary<int, StItem> items, List<StAnswer> answers,
Dictionary<String, String> demogInfo, StNormAuto norm)
{
mItems = items;
mAnswers = answers;
mDemogInfo = demogInfo;
mNorm = norm;
}
private List<String> genHeader()
{
List<String> header = new List<string>();
for (int i = 0; i < mDemogInfo.Count; i++)
header.Add(mDemogInfo.ElementAt(i).Key);
header.Add("TimeStamp");
for (int i = 0; i < mAnswers.Count; i++)
{
header.Add( i + "selected");
//header.Add(i + "RT");
header.Add(i + "value");
}
for (int i = 0; i < mNorm.Dims.Count; i++)
{
header.Add(mNorm.Dims[i].Name + "_Socre");
header.Add(mNorm.Dims[i].Name + "_Percentile");
header.Add(mNorm.Dims[i].Name + "_StdScore");
}
header.Add("Validity");
return header;
}
protected bool TestValid()
{
int TotalDiff = 0;
//validity with principal
for (int i = 0; i < mNorm.Validity.ItemIndex.Count / 2; i += 2)
{
if (mNorm.Validity.Principal == ValidityPrincipal.IndexEqual)
{
if (mAnswers[mNorm.Validity.ItemIndex[i]] !=
mAnswers[mNorm.Validity.ItemIndex[i + 1]])
{
TotalDiff++;
}
}
else if (mNorm.Validity.Principal == ValidityPrincipal.ValueEqual)
{
if (GetSingleItemScore(mItems, mAnswers, mNorm.Validity.ItemIndex[i]) !=
GetSingleItemScore(mItems, mAnswers, mNorm.Validity.ItemIndex[i + 1]))
{
TotalDiff++;
}
}
}
if (TotalDiff >= mNorm.Validity.Tolerance)
return false;
else
return true;
}
virtual protected void WriteFile(String path)
{
TabCharter ltc = new TabCharter(path);
if (!File.Exists(path))
{
ltc.Create(genHeader());
}
//demog info
List<String> line = new List<string>();
for (int i = 0; i < mDemogInfo.Count; i++)
{
line.Add(mDemogInfo.ElementAt(i).Value);
}
DateTime dt = DateTime.Now;
line.Add(dt.Year + "-" + dt.Month + "-" + dt.Day + " " +
dt.Hour + ":" + dt.Minute + ":" + dt.Second);
//items` info
for (int i = 0; i < mAnswers.Count; i++)
{
line.Add(mAnswers[i].Selected.ToString());
//line.Add(mAnswers[i].RT.ToString());
line.Add(GetSingleItemScore(mItems, mAnswers, i).ToString());
}
//norm info
for (int i = 0; i < mNorm.Dims.Count; i++ )
{
line.Add(mDimzScores[i].ToString());
line.Add(mDimzPercentile[i].ToString());
line.Add(mDimzStdScore[i].ToString());
}
line.Add(TestValid().ToString());
ltc.Append(line);
}
protected void calculateStdScore()
{
for (int index = 0; index < mDimzScores.Count; index++)
{
double retval = mDimzScores[index];
for (int i = 0; i < mNorm.Dims[index].Method.Method.Count; i++)
{
if (mNorm.Dims[index].Method.Method[i] == '+')
{
retval += mNorm.Dims[index].Method.Values[i];
}
else if (mNorm.Dims[index].Method.Method[i] == '-')
{
retval -= mNorm.Dims[index].Method.Values[i];
}
else if (mNorm.Dims[index].Method.Method[i] == '*')
{
retval *= mNorm.Dims[index].Method.Values[i];
}
else if (mNorm.Dims[index].Method.Method[i] == '/')
{
retval /= mNorm.Dims[index].Method.Values[i];
}
}
mDimzStdScore.Add(retval);
}
}
//raw score and percentile
protected void calcNormRelatedResult()
{
float singleNormScore = 0;
for (int i = 0; i < mNorm.Dims.Count; i++)
{
singleNormScore = GetSingleDimensionzScore(mItems, mAnswers, mNorm.Dims[i].ItemIndexList);
mDimzScores.Add(singleNormScore);
mDimzPercentile.Add(DifferenceIntegrate.GetSpecificAreaSize(
1000000, mNorm.Dims[i].Mean, mNorm.Dims[i].SD, mNorm.Dims[i].Mean - 4 * mNorm.Dims[i].SD,
singleNormScore));
}
}
virtual public void Sta_Save()
{
calcNormRelatedResult();
calculateStdScore();
WriteFile(OUT_PATH);
}
public float GetSingleDimensionzScore(
Dictionary<int, StItem> item, List<StAnswer> answer, List<int> itemIndexList)
{
float retval = 0;
int itemNumBuf = 0;
for (int i = 0; i < itemIndexList.Count; i++)
{
//get index in norm
itemNumBuf = itemIndexList[i];
//get certain index`s selection value added to return value
retval += item[itemNumBuf].Selections[answer[itemNumBuf].Selected].Value;
}
return retval;
}
public float GetSingleItemScore(
Dictionary<int, StItem> item, List<StAnswer> answer, int index)
{
if (answer[index].Selected != -1)
{
return item[index].Selections[answer[index].Selected].Value;
}
else
{
return 0;
}
}
}
}
<file_sep>/Memory/Memory/StDocManageBriefInfo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lithopone.Memory
{
public class StDocManageBriefInfo
{
public String Number { get; set; }
public String Name { get; set; }
public String Stamp { get; set; }
}
}
<file_sep>/LithoponeReportDLL/NormDistriBarviewGen.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms.DataVisualization.Charting;
using System.Drawing;
using NormDistributionLib;
namespace Arora
{
public class NormDistriBarviewGen
{
static public void SetChart(Chart chart, int percentage, Color overcolor, Color belowcolor)
{
chart.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
chart.ChartAreas["ChartArea1"].Area3DStyle.LightStyle = LightStyle.None;
chart.ChartAreas["ChartArea1"].Area3DStyle.Inclination = 0;
chart.ChartAreas["ChartArea1"].Area3DStyle.Perspective = 10;
chart.ChartAreas["ChartArea1"].BackColor = Color.FromArgb(255, 255, 255);
chart.ChartAreas["ChartArea1"].AxisX.Enabled = AxisEnabled.False;
chart.ChartAreas["ChartArea1"].AxisY.Enabled = AxisEnabled.False;
chart.ChartAreas["ChartArea1"].Area3DStyle.WallWidth = 0;
chart.ChartAreas["ChartArea1"].Area3DStyle.PointDepth = 1000;
Series serbelow = new Series("below");
serbelow.IsVisibleInLegend = false;
serbelow.ChartType = SeriesChartType.Area;
serbelow.BorderWidth = 0;
serbelow.ShadowOffset = 3;
serbelow.Color = belowcolor;
Series serover = new Series("over");
serover.IsVisibleInLegend = false;
serover.ChartType = SeriesChartType.Area;
serover.BorderWidth = 0;
serover.ShadowOffset = 3;
serover.Color = overcolor;
int stepCount = 100;
float sdRange = (float)2.58 * 2;
float step = sdRange / stepCount;
float startPoint = (float)-2.58;
for (int i = 0; i < stepCount; i++)
{
float x = startPoint + i * step;
if (i < percentage)
{
serover.Points.AddXY(x, (float)ValueY.GetValue(0, 1, x));
}
else
{
serbelow.Points.AddXY(x, (float)ValueY.GetValue(0, 1, x));
}
}
chart.Series.Clear();
chart.Series.Add(serbelow);
chart.Series.Add(serover);
}
}
}<file_sep>/Lithopone/UIComponents/CompText.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Lithopone.UIComponents
{
/// <summary>
/// CompTextCasual.xaml 的互動邏輯
/// </summary>
public partial class CompText : UserControl
{
public static int HEIGHT = 53;
public int mWidth;
public MainWindow mMW;
public CompText()
{
InitializeComponent();
}
public CompText(MainWindow mw, int width)
{
InitializeComponent();
BorderBrush = new SolidColorBrush(Color.FromRgb(255, 255, 255));
mMW = mw;
mWidth = width;
}
public void SetText(String text)
{
amLabel.Text = text;
amLabel.Width = mWidth;
this.Width = mWidth;
}
}
}
<file_sep>/Memory/Memory/StAnswer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lithopone.Memory
{
public class StAnswer
{
public long RT = -1;
public int Selected = -1;
public StAnswer()
{ }
public StAnswer(long rt, int selected)
{
RT = rt;
Selected = selected;
}
}
}
<file_sep>/Lithopone/UIComponents/CompGraph.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Drawing;
using System.IO;
using Lithopone.FileReader;
using Lithopone.Memory;
namespace Lithopone.UIComponents
{
/// <summary>
/// CompGraph.xaml 的互動邏輯
/// </summary>
public partial class CompGraph : UserControl
{
public static int TEXTFIELD_HEIGHT = 38;
public static int SIZE_SMALL = 150;
public static int SIZE_MEDIUM = 300;
public static int SIZE_LARGE = 600;
public static int EDGE = 4;
ResExtractor mExtractor;
public static int GetVarSize(GRAPH_SIZE size)
{
int VAR_SIZE = 0;
switch (size)
{
case GRAPH_SIZE.SMALL:
VAR_SIZE = SIZE_SMALL;
break;
case GRAPH_SIZE.MEDIUM:
VAR_SIZE = SIZE_MEDIUM;
break;
case GRAPH_SIZE.LARGE:
VAR_SIZE = SIZE_LARGE;
break;
}
return VAR_SIZE;
}
public CompGraph(GRAPH_SIZE size, ref ResExtractor extractor)
{
InitializeComponent();
mExtractor = extractor;
int VAR_SIZE = GetVarSize(size);
amImage.Width = VAR_SIZE;
amImage.Height = VAR_SIZE;
amLabel.Width = VAR_SIZE;
amLabel.Height = TEXTFIELD_HEIGHT;
this.Height = VAR_SIZE + TEXTFIELD_HEIGHT + EDGE;
this.Width = VAR_SIZE + EDGE;
Canvas.SetLeft(amImage, 0);
Canvas.SetTop(amImage, 0);
Canvas.SetLeft(amLabel, 0);
Canvas.SetTop(amLabel, VAR_SIZE);
BorderBrush = new SolidColorBrush(System.Windows.Media.Color.FromRgb(255, 255, 255));
}
public void SetText(String text)
{
amLabel.Content = text;
}
public void SetGraph(int index)
{
//BinaryReader br = new BinaryReader(File.Open(path, FileMode.Open));
//FileInfo fi = new FileInfo(path);
byte[] data = mExtractor.ExtractRes2Mem(index);//br.ReadBytes((int)fi.Length);
//br.Close();
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = new MemoryStream(data);
bi.EndInit();
amImage.Source = bi;
}
}
}
<file_sep>/Memory/Memory/StNorm.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lithopone.Memory
{
public class StNorm
{
public String KEY;
public double Mean;
public double SD;
public int[] ItemIDs;
public StNorm(String key, double mean, double sd, int[] itemIDs)
{
KEY = key;
Mean = mean;
SD = sd;
ItemIDs = itemIDs;
}
}
}
<file_sep>/Lithopone/FileReader/ResExtractor.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lithopone.Memory;
using System.IO;
namespace Lithopone.FileReader
{
public class ResExtractor : BinaryReaderBase
{
public static int BUFFERLEN = 1024;
public StBlockDscription mBlockDscp;
public int mResCount = 0;
override public void Begin2()
{
mBlockDscp = GetBlockInfo(BLOCKTYPE.RESOURCE);
mFs.Position = mBlockDscp.Begin;
mResCount = ReadInt();
}
public long GetIndexBeg(int index)
{
long retval = -1;
retval = index * 24 + mBlockDscp.Begin + 4;
return retval;
}
public StResourceDscp GetResourceDscp(int index)
{
StResourceDscp retval = new StResourceDscp();
mFs.Position = GetIndexBeg(index);
retval.beg = ReadLong();
retval.len = ReadLong();
retval.type = ReadLong();
return retval;
}
public static String GetExtendName(StResourceDscp resDscp)
{
String ret = "";
if (resDscp.type == 0)
{
ret = ".jpg";
}
else if (resDscp.type == 1)
{
ret = ".png";
}
return ret;
}
public int GetResourceCount()
{
mFs.Position = mBlockDscp.Begin;
int retval = ReadInt();
return retval;
}
//extract a whole file into memory
public byte[] ExtractRes2Mem(int index)
{
byte[] retval = null;
StResourceDscp dscp = GetResourceDscp(index);
mFs.Position = getResourceDataBegpos(index);
retval = mBr.ReadBytes((int)dscp.len);
return retval;
}
//get resource data begin pos of a whole picture file (not just its data part)
private long getResourceDataBegpos(int index)
{
return GetResourceDscp(index).beg + mBlockDscp.Begin + 4 + 24 * mResCount;
}
//extract file to hard disk (currently not in use)
public void ExtractRes(String destFolder, int rangeStart, int count)
{
String path = destFolder;
if (rangeStart >= 0 && count > 0 && count <= mResCount)
{
int rangeEnd = rangeStart + count;
StResourceDscp resDscp = null;
byte[] buffer = new byte[BUFFERLEN];
for (int i = rangeStart; i < rangeEnd; i++)
{
resDscp = GetResourceDscp(i);
FileStream fso =
new FileStream(path + i.ToString() + GetExtendName(resDscp),
FileMode.Create, FileAccess.Write);
mFs.Position = getResourceDataBegpos(i);
if (resDscp.len < BUFFERLEN)
{
mBr.Read(buffer, (int)resDscp.beg, (int)resDscp.len);
fso.Write(buffer, 0, (int)resDscp.len);
}
else
{
int time = (int)(resDscp.len / BUFFERLEN + 1);
int lastLen = (int)(resDscp.len % BUFFERLEN);
int red = 0;
for (int j = 0; j < time; j++)
{
if (j != time - 1)
{
red = mBr.Read(buffer, 0, BUFFERLEN);
fso.Write(buffer, 0, BUFFERLEN);
}
else
{
red = mBr.Read(buffer, 0, lastLen);
fso.Write(buffer, 0, lastLen);
}
}
}
fso.Close();
}
}
}
}
}
<file_sep>/Memory/Memory/StBlockDscription.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lithopone.Memory
{
public class StBlockDscription
{
public int Begin;
public int Length;
}
}
<file_sep>/Memory/Memory/StPFileInfo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lithopone.Memory
{
public class StPFileInfo
{
public int Version;
public byte Mode;
public byte ResourceStatus;
}
}
<file_sep>/Memory/Memory/StNormLevel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lithopone.Memory
{
//class to define the relationship of the value and description
public class StNormLevel
{
public int ID;//level ID
public double FloorWith;//start value (included)
public double CeilingWithout;//end value (not included)
public string Description;//description
}
}
<file_sep>/Memory/Memory/StDemogLine.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lithopone.Memory
{
public class StDemogLine
{
public String PreText;
public String PostText;
public LINETYPE Type;
public Dictionary<int, String> SubItems;//only for comboBoxes and radio buttons
public String VarName;
public int Width = 0;
public bool ForcedChoice = false;
public StDemogLine()
{
SubItems = new Dictionary<int, String>();
}
}
}
<file_sep>/Memory/Memory/StSelection.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lithopone.Memory
{
public class StSelection
{
public int ResID;
public float Value;
public string Casual;
public StSelection(int resId, float value, string casual)
{
ResID = resId;
Value = value;
Casual = casual;
}
}
}
<file_sep>/Memory/Memory/StRankSpan.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lithopone.Memory
{
public class StRankSpan
{
public int Key;
public float Percentage;
public float Floor;
}
}
<file_sep>/Lithopone/FileReader/TestXmlReader.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Lithopone.Memory;
using System.IO;
namespace Lithopone.FileReader
{
public class TestXmlReader
{
private XmlDocument mDoc;
private FileStream mFs;
public void Begin(String path)
{
mDoc = new XmlDocument();
mFs = new FileStream(path, FileMode.Open, FileAccess.Read);
mDoc.Load(mFs);
}
public void Finish()
{
mFs.Close();
}
private Dictionary<int, StSelection> GetSelections(XmlNode itemNode)
{
Dictionary<int, StSelection> retval = new Dictionary<int, StSelection>();
XmlNodeList nl = itemNode.ChildNodes;
string casual;
int id = Int32.MaxValue, resId = Int32.MaxValue, value = Int32.MaxValue;
//selections
for (int i = 1; i < nl.Count; i++)
{
casual = nl[i].FirstChild.InnerText;
XmlAttributeCollection ac = nl[i].Attributes;
//attributes in one selection
for (int j = 0; j < ac.Count; j++)
{
if(ac[j].Name.Equals("id"))
{
id = Int32.Parse(ac[j].Value);
}
else if(ac[j].Name.Equals("res_id"))
{
resId = Int32.Parse(ac[j].Value);
}
else if(ac[j].Name.Equals("value"))
{
value = Int32.Parse(ac[j].Value);
}
}
retval.Add(id, new StSelection(resId, value, casual));
}
return retval;
}
public Dictionary<int, StItem> GetItems()
{
Dictionary<int, StItem> ret = new Dictionary<int, StItem>();
XmlNodeList itemsNl = mDoc.SelectNodes("/test/item");
XmlAttributeCollection ac;
int id = Int32.MaxValue;
int resId = Int32.MaxValue;
string casual = "";
//items
for (int i = 0; i < itemsNl.Count; i++)
{
ac = itemsNl[i].Attributes;
//attributes
for (int j = 0; j < ac.Count; j++)
{
if (ac[j].Name.Equals("id"))
{
id = Int32.Parse(ac[j].Value);
}
else if (ac[j].Name.Equals("res_id"))
{
resId = Int32.Parse(ac[j].Value);
}
}
//casual
casual = itemsNl[i].FirstChild.InnerText;
//get selections
Dictionary<int, StSelection> sel = GetSelections(itemsNl[i]);
ret.Add(id, new StItem(resId, casual, ref sel));
}
return ret;
}
public StTestXmlHeader GetHeader()
{
StTestXmlHeader ret = new StTestXmlHeader();
XmlNode node = mDoc.SelectSingleNode("/test");
XmlAttributeCollection ac = node.Attributes;
string nameBuf, valueBuf;
for (int i = 0; i < ac.Count; i++)
{
nameBuf = ac[i].Name;
valueBuf = ac[i].Value;
if (nameBuf.Equals("version"))
{
ret.Version = Int32.Parse(valueBuf);
}
else if (nameBuf.Equals("text_selection"))
{
ret.TextSelection = Boolean.Parse(valueBuf);
}
else if (nameBuf.Equals("text_casual"))
{
ret.TextCausal = Boolean.Parse(valueBuf);
}
else if (nameBuf.Equals("selection_size"))
{
ret.SelectionSize = Lib.Str2Size(valueBuf);
}
else if (nameBuf.Equals("name"))
{
ret.Name = valueBuf;
}
else if (nameBuf.Equals("item_count"))
{
ret.ItemCount = Int32.Parse(valueBuf);
}
else if (nameBuf.Equals("id"))
{
ret.ID = Int32.Parse(valueBuf);
}
else if (nameBuf.Equals("graphic_selection"))
{
ret.GraphicSelection = Boolean.Parse(valueBuf);
}
else if (nameBuf.Equals("graphic_casual"))
{
ret.GraphicCasual = Boolean.Parse(valueBuf);
}
else if (nameBuf.Equals("description"))
{
ret.Description = valueBuf;
}
else if (nameBuf.Equals("instruction"))
{
ret.Instruction = valueBuf;
}
else if (nameBuf.Equals("casual_size"))
{
ret.CasualSize = Lib.Str2Size(valueBuf);
}
}
return ret;
}
}
}
<file_sep>/Lithopone/FileReader/BinaryReaderBase.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Lithopone.Memory;
using System.Windows.Forms;
namespace Lithopone.FileReader
{
public class BinaryReaderBase
{
public enum BLOCKTYPE { TEST, CONFIG, RESOURCE };
public FileStream mFs;
public BinaryReader mBr;
public void Begin(String path)
{
try
{
mFs = new FileStream(path, FileMode.Open, FileAccess.Read);
mBr = new BinaryReader(mFs);
}
catch (Exception)
{
MessageBox.Show("源文件不存在");
System.Environment.Exit(0);
}
Begin2();
}
public virtual void Begin2()
{ }
public StBlockDscription GetBlockInfo(BLOCKTYPE type)
{
int posToSet = -1;
switch (type)
{
case BLOCKTYPE.TEST:
posToSet = 8;
break;
case BLOCKTYPE.CONFIG:
posToSet = 16;
break;
case BLOCKTYPE.RESOURCE:
posToSet = 24;
break;
}
mFs.Position = posToSet;
StBlockDscription retval = new StBlockDscription();
retval.Begin = ReadInt();
retval.Length = ReadInt();
return retval;
}
public int ReadInt()
{
int retval = Int16.MaxValue;
byte[] bArr = mBr.ReadBytes(4);
Array.Reverse(bArr);
retval = BitConverter.ToInt32(bArr, 0);
return retval;
}
public long ReadLong()
{
long retval = Int64.MaxValue;
byte[] bArr = mBr.ReadBytes(8);
Array.Reverse(bArr);
retval = BitConverter.ToInt64(bArr, 0);
return retval;
}
public byte ReadByte()
{
return mBr.ReadByte();
}
public void End()
{
if (mBr != null)
{
mBr.Close();
mBr = null;
}
if (mFs != null)
{
mFs.Close();
mFs = null;
}
}
~BinaryReaderBase()
{
End();
}
}
}
<file_sep>/Memory/Memory/StNormStdScoreMethod.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lithopone.Memory
{
//class to define the method of making standard score
public class StNormStdScoreMethod
{
//the methods are to be used to make the standard score
public List<char> Method;
//the values are to be used to make the standard score
public List<double> Values;
public StNormStdScoreMethod()
{
Method = new List<char>();
Values = new List<double>();
}
}
}
<file_sep>/Lithopone/Kernel/ItemsRunner.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using Lithopone.Memory;
using Lithopone.UIComponents;
using Lithopone.FileReader;
using System.IO;
using System.Drawing;
/*
* not in using anymore
*/
namespace Lithopone.Kernel
{
public class ItemsRunner
{
public MainWindow mMainWindow;
public int mVerTaken = 0;
static int CASUAL_ITEM_GAP = 50;
static int SEL_GAP = 10;
public CompSelectionGroup mSelGrp;
public Dictionary<int, StItem> mItems;
private TestRunner mTest;
private String mPackagePath;
private ResExtractor mExtractor;
public ItemsRunner(MainWindow _mainWindow,
Dictionary<int, StItem> items, TestRunner test, String packagePath)
{
mMainWindow = _mainWindow;
mItems = items;
mTest = test;
mSelGrp = new CompSelectionGroup();
mPackagePath = packagePath;
}
public void OpenConnection()
{
mExtractor = new ResExtractor();
mExtractor.Begin(mPackagePath);
}
public void CloseConnection()
{
mExtractor.End();
}
public void SetPage(int index, int UISlected = -1)
{
mVerTaken = 0;
mMainWindow.amCanvas.Children.Clear();
if (mItems.ContainsKey(index))
{
if (mTest.GetTestAttribute().GraphicCasual)
{
layGraphicCasual(index);
}
else
{
layTextCasual(index);
}
if (mTest.GetTestAttribute().GraphicSelection)
{
layGraphicSelection(index);
}
else
{
layTextSelection(index, UISlected);
}
layProgressText(index);
}
}
private void layProgressText(int index)
{
CompText ct = new CompText(mMainWindow, 10);
ct.SetText("第" + (index + 1).ToString() + "题,共" + mItems.Count + "题");
mMainWindow.amCanvas.Children.Add(ct);
Canvas.SetTop(ct, mMainWindow.Height - 180);
Canvas.SetLeft(ct, mMainWindow.Width / 2 - 65);
}
private void layTextCasual(int index)
{
CompTextLarge ct = new CompTextLarge();
ct.SetText(mItems[index].Casual);
mMainWindow.amCanvas.Children.Add(ct);
Canvas.SetTop(ct, 0);
Canvas.SetLeft(ct, (mMainWindow.Width - ct.amLabel.Width) / 2);
mVerTaken += CompText.HEIGHT + CASUAL_ITEM_GAP;
}
private void layTextSelection(int index, int UIselected)
{
Dictionary<int, StSelection> selection = mItems[index].Selections;
List<UserControl> list = new List<UserControl>();
for (int i = 0; i < selection.Count; i++)
{
CompText ct = new CompText(mMainWindow, 10);
ct.SetText(selection[i].Casual);
mMainWindow.amCanvas.Children.Add(ct);
Canvas.SetTop(ct, mVerTaken);
Canvas.SetLeft(ct, (mMainWindow.Width - ct.Width) / 2);
mVerTaken += CompText.HEIGHT + SEL_GAP;
list.Add(ct);
}
//mMainWindow.Height = mVerTaken + CompText.HEIGHT + 100;
mSelGrp.Set(list, UIselected);
}
private void layGraphicCasual(int index)
{
GRAPH_SIZE size = mTest.GetTestAttribute().CasualSize;
CompGraph cg = new CompGraph(size, ref mExtractor);
int resID = mItems[index].ResID;
cg.SetGraph(resID);
cg.SetText(mItems[index].Casual);
mMainWindow.amCanvas.Children.Add(cg);
Canvas.SetTop(cg, 0);
Canvas.SetLeft(cg, (mMainWindow.Width - cg.Width) / 2);
mVerTaken += (int)cg.Height + CASUAL_ITEM_GAP;
}
private void layGraphicSelection(int index)
{
Dictionary<int, StSelection> selection = mItems[index].Selections;
List<UserControl> list = new List<UserControl>();
GRAPH_SIZE size = mTest.GetTestAttribute().SelectionSize;
for (int i = 0; i < selection.Count; i++)
{
CompGraph cg = new CompGraph(size, ref mExtractor);
int resID = mItems[index].Selections[i].ResID;
cg.SetGraph(resID);
cg.SetText(mItems[index].Selections[i].Casual);
mMainWindow.amCanvas.Children.Add(cg);
list.Add(cg);
}
placeComGraphSelections(CompGraph.GetVarSize(size) + 10, list);
mMainWindow.amCanvas.Height = mVerTaken + CompGraph.GetVarSize(size) + 150;
mSelGrp.Set(list);
}
private void placeComGraphSelections(int comWidth, List<UserControl> list)
{
int tryInt = 0;
int placed = 0;
while (tryInt * comWidth < mMainWindow.amCanvas.Width)
tryInt++;
tryInt--;
int totalWidth = 0;
if (list.Count < tryInt)
{
totalWidth = list.Count * comWidth;
}
else
{
totalWidth = tryInt * comWidth;
}
int xOff = (int)(mMainWindow.amCanvas.Width - totalWidth) / 2;
int verTaken = mVerTaken;
for (int i = 0; i < list.Count; i++)
{
if (placed == tryInt)
{
verTaken += (int)list[i].Height + SEL_GAP;
placed = 0;
}
Canvas.SetLeft(list[i], xOff + placed * comWidth);
Canvas.SetTop(list[i], verTaken);
placed++;
}
mVerTaken = verTaken;
}
}
}
<file_sep>/Lithopone/FileReader/DemogXmlReader.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Lithopone.Memory;
using System.IO;
using System.Windows.Forms;
namespace Lithopone.FileReader
{
class DemogXmlReader
{
private XmlDocument mDoc;
private FileStream mFs;
public Dictionary<int, StDemogLine> GetDemogItems(String filename)
{
Dictionary<int, StDemogLine> retval = null;
try
{
mDoc = new XmlDocument();
mFs = new FileStream(System.AppDomain.CurrentDomain.BaseDirectory + filename,
FileMode.Open, FileAccess.Read);
mDoc.Load(mFs);
retval = new Dictionary<int, StDemogLine>();
XmlNodeList nodeList = mDoc.SelectNodes("/DemographicSheet/Line");
XmlAttributeCollection attrCollection = null;
//line
for (int i = 0; i < nodeList.Count; i++)
{
attrCollection = nodeList[i].Attributes;
//attributes in line
StDemogLine line = new StDemogLine();
int lineID = -1;
for (int j = 0; j < attrCollection.Count; j++)
{
String attrName = attrCollection[j].Name;
if (attrName.Equals("id"))
{
lineID = Int32.Parse(attrCollection[j].Value);
}
else if (attrName.Equals("var_name"))
{
line.VarName = attrCollection[j].Value;
}
else if (attrName.Equals("line_type"))
{
line.Type = Lib.Str2LineType(attrCollection[j].Value);
}
else if (attrName.Equals("pre_text"))
{
line.PreText = attrCollection[j].Value;
}
else if (attrName.Equals("post_text"))
{
line.PostText = attrCollection[j].Value;
}
else if (attrName.Equals("width"))
{
line.Width = Int32.Parse(attrCollection[j].Value);
}
else if (attrName.Equals("forced_choice"))
{
line.ForcedChoice = Boolean.Parse(attrCollection[j].Value);
}
}
XmlNodeList selections = nodeList[i].ChildNodes;
for (int k = 0; k < selections.Count; k++)
{
int SelectionID = -1;
String SelectionText = null;
XmlAttributeCollection attrOfSelection = selections[k].Attributes;
for (int l = 0; l < attrOfSelection.Count; l++)
{
if (attrOfSelection[l].Name.Equals("id"))
{
SelectionID = Int32.Parse(attrOfSelection[l].Value);
}
else if (attrOfSelection[l].Name.Equals("text"))
{
SelectionText = attrOfSelection[l].Value;
}
}
line.SubItems.Add(SelectionID, SelectionText);
}
retval.Add(lineID, line);
}
}
catch (Exception)
{
if (MessageBox.Show("人口学数据读取出错") == DialogResult.OK)
{
if (mFs != null)
mFs.Close();
System.Environment.Exit(0);
}
}
if(mFs != null)
mFs.Close();
return retval;
}
}
}
<file_sep>/Lithopone/Kernel/KernelLib.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Drawing;
using System.Windows.Media.Imaging;
namespace Lithopone.Kernel
{
public class KernelLib
{
public static int LINE_HEIGHT = 35;
public static int CHARA_WIDTH = 18;
public static int DEMOG_FONT_SIZE = 18;
public static int STACKPANE_WIDTH = 760;
public static int LINE_GAP = 5;
public static StackPanel GenLinePane()
{
StackPanel retval = new StackPanel();
retval.Height = LINE_HEIGHT;
retval.Width = STACKPANE_WIDTH;
retval.Orientation = Orientation.Horizontal;
return retval;
}
}
}
<file_sep>/Lithopone/UIComponents/ItemPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Lithopone.Kernel;
using Lithopone.Memory;
using Lithopone.FileReader;
namespace Lithopone.UIComponents
{
/// <summary>
/// ItemPage.xaml 的互動邏輯
/// </summary>
/// class of the whole test page(selection, buttons, pages, stem)
public partial class ItemPage : UserControl
{
public Dictionary<int, StItem> mItems;
private TestRunner mTest;
//private String mPackagePath;
//private ResExtractor mExtractor;
public CompSelection amCompSelection;
public ItemPage(Dictionary<int, StItem> items, TestRunner runner, int sizeX, int sizeY)
{
InitializeComponent();
mItems = items;
mTest = runner;
amCompSelection = new CompSelection(mTest.mMainWindow, this, sizeX);
amCanvas.Children.Add(amCompSelection);
Canvas.SetTop(amCompSelection, 100);
Canvas.SetLeft(amCompSelection, 0);
//sizing & centalize
this.Width = sizeX;
this.Height = sizeY;
amCanvas.Width = sizeX;
amCanvas.Height = sizeY;
amStem.Width = sizeX;
amCompSelection.Width = sizeX;
amCompSelection.Height = sizeY - 25 - 27 - 47 - 44 - 35 - 20;
amLabelPageNum.Width = sizeX;
Canvas.SetLeft(amLabelPageNum, 0);
Canvas.SetTop(amLabelPageNum, sizeY - 45);
Canvas.SetLeft(amBtnPrev, (sizeX - (86 * 2 + 10)) / 2);
Canvas.SetTop(amBtnPrev, sizeY - 35 - 20 - 44);
Canvas.SetLeft(amBtnNext, (sizeX - (86 * 2 + 10)) / 2 + 10 + 86);
Canvas.SetTop(amBtnNext, sizeY - 35 - 20 - 44);
}
public void SetPage(int index, int uiSelected = -1)
{
StItem item = mItems[index];
amCompSelection.Set(item.Selections);
amCompSelection.SetUISelected(uiSelected);
amStem.Text = item.Casual;
amLabelPageNum.Text = "第" + (mTest.mCurTill + 1) + "页, 共" + mItems.Count + "页";
}
public void toNextPage()
{
if (amCompSelection.GetSelectedIndex() != -1)
{
mTest.Save();
mTest.mCurTill++;
if (mTest.mCurTill < mTest.mTestAttr.ItemCount)
{
mTest.SetPage(mTest.mCurTill);
}
else
{
mTest.TestEnd();
}
}
else
{
MessageBox.Show("请做出选择");
}
}
private void amBtnNext_Click(object sender, RoutedEventArgs e)
{
toNextPage();
}
private void amBtnPrev_Click(object sender, RoutedEventArgs e)
{
if (amCompSelection.GetSelectedIndex() != -1)
{
mTest.Save();
}
if (mTest.mCurTill > 0)
mTest.mCurTill--;
if (mTest.mCurTill > -1)
{
mTest.SetPage(mTest.mCurTill);
}
}
}
}
<file_sep>/Memory/Memory/StGeneralInfo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lithopone.Memory
{
public class StGeneralInfo
{
public String Name;
public String Value;
public StGeneralInfo(String value, String name)
{
Name = name;
Value = value;
}
}
}
<file_sep>/Lithopone/UIComponents/CompSelection.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Lithopone.Memory;
namespace Lithopone.UIComponents
{
/// <summary>
/// CompSelection.xaml 的互動邏輯
/// </summary>
/// class of selections and highlights only
public partial class CompSelection : UserControl
{
private List<CompText> mSelections;
public delegate void MouseEnterDele();
public delegate void MouseLeaveDele();
public delegate void MouseClickDele();
MouseEnterDele mEnterFunc = null;
MouseLeaveDele mLeaveFunc = null;
MouseClickDele mClickFunc = null;
public MainWindow mMainWindow;
public ItemPage mItemPage;
public int mSizeX;
public CompSelection(MainWindow mw, ItemPage itemPage, int sizeX)
{
InitializeComponent();
mSelections = new List<CompText>();
mMainWindow = mw;
mItemPage = itemPage;
mSizeX = sizeX;
}
private int mSelIdx = -1;
public void Set(Dictionary<int, StSelection> selection, int selected = -1,
MouseEnterDele enterFunc = null, MouseLeaveDele leaveFunc = null, MouseClickDele clickFunc = null)
{
mSelections.Clear();
amCanvas.Children.Clear();
for (int j = 0; j < selection.Count; j++)
{
CompText line = new CompText(mMainWindow, mSizeX);
line.SetText(selection[j].Casual);
mSelections.Add(line);
}
double accumVerticalPos = 0;
for (int i = 0; i < mSelections.Count; i++)
{
mSelections[i].MouseEnter +=
new System.Windows.Input.MouseEventHandler(CompSelectionGroup_MouseEnter);
mSelections[i].MouseLeave +=
new System.Windows.Input.MouseEventHandler(CompSelectionGroup_MouseLeave);
mSelections[i].MouseDown +=
new System.Windows.Input.MouseButtonEventHandler(CompSelectionGroup_MouseDown);
amCanvas.Children.Add(mSelections[i]);
Canvas.SetTop(mSelections[i], accumVerticalPos);
Canvas.SetLeft(mSelections[i], 0);
accumVerticalPos += CompText.HEIGHT + 5;
}
mSelIdx = selected;
if (mSelIdx > -1)
{
SetUISelected(mSelIdx);
}
}
public void SetUISelected(int index)
{
for (int i = 0; i < mSelections.Count; i++)
{
if (index == i)
{
mSelections[i].BorderBrush = new SolidColorBrush(Color.FromRgb(0, 0, 0));
mSelIdx = i;
}
else
{
mSelections[i].BorderBrush = new SolidColorBrush(Color.FromRgb(255, 255, 255));
}
}
}
void CompSelectionGroup_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (mClickFunc == null)
{
for (int i = 0; i < mSelections.Count; i++)
{
if (sender.Equals(mSelections[i]))
{
//mSelections[i].BorderBrush = new SolidColorBrush(Color.FromRgb(0, 0, 0));
((CompText)sender).amLabel.Background =
new SolidColorBrush(Color.FromRgb(134, 217, 255));
mSelIdx = i;
}
else
{
//mSelections[i].BorderBrush = new SolidColorBrush(Color.FromRgb(255, 255, 255));
mSelections[i].amLabel.Background =
new SolidColorBrush(Color.FromRgb(255, 255, 255));
}
}
}
else
{
mClickFunc();
}
//test
//mItemPage.toNextPage();
}
void CompSelectionGroup_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
if (mLeaveFunc == null)
{
if (getObjectIdx(sender) != mSelIdx)
{
//((UserControl)sender).BorderBrush = new SolidColorBrush(Color.FromRgb(255, 255, 255));
((CompText)sender).amLabel.Background =
new SolidColorBrush(Color.FromRgb(255, 255, 255));
}
}
else
{
mLeaveFunc();
}
}
void CompSelectionGroup_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
if (mEnterFunc == null)
{
//((UserControl)sender).BorderBrush = new SolidColorBrush(Color.FromRgb(0, 0, 0));
((CompText)sender).amLabel.Background =
new SolidColorBrush(Color.FromRgb(134, 217, 255));
}
else
{
mEnterFunc();
}
}
private int getObjectIdx(object obj)
{
int retval = -1;
int upper = mSelections.Count;
for (int i = 0; i < upper; i++)
{
if (obj.Equals(mSelections[i]))
{
retval = i;
break;
}
}
return retval;
}
public int GetSelectedIndex()
{
return mSelIdx;
}
}
}
<file_sep>/Lithopone/MainMenu.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Lithopone.Memory;
using Lithopone.FileReader;
namespace Lithopone
{
/// <summary>
/// MainMenu.xaml 的互動邏輯
/// </summary>
public partial class MainMenu : Window
{
ConfigCollection mConfigs;
public MainMenu()
{
InitializeComponent();
mConfigs = new ConfigCollection();
}
private void amRectIntro_MouseUp(object sender, MouseButtonEventArgs e)
{
}
private void amRectTest_MouseUp(object sender, MouseButtonEventArgs e)
{
new MainWindow(mConfigs).Show();
}
private void amRectResult_MouseUp(object sender, MouseButtonEventArgs e)
{
new DocManageWnd(mConfigs).ShowDialog();
}
private void amRectIntro_MouseEnter(object sender, MouseEventArgs e)
{
amRectIntro.Stroke = new SolidColorBrush(Color.FromRgb(150, 150, 200));
}
private void amRectIntro_MouseLeave(object sender, MouseEventArgs e)
{
amRectIntro.Stroke = new SolidColorBrush(Color.FromRgb(255, 255, 255));
}
private void amRectTest_MouseEnter(object sender, MouseEventArgs e)
{
amRectTest.Stroke = new SolidColorBrush(Color.FromRgb(150, 150, 200));
}
private void amRectTest_MouseLeave(object sender, MouseEventArgs e)
{
amRectTest.Stroke = new SolidColorBrush(Color.FromRgb(255, 255, 255));
}
private void amRectResult_MouseEnter(object sender, MouseEventArgs e)
{
amRectResult.Stroke = new SolidColorBrush(Color.FromRgb(150, 150, 200));
}
private void amRectResult_MouseLeave(object sender, MouseEventArgs e)
{
amRectResult.Stroke = new SolidColorBrush(Color.FromRgb(255, 255, 255));
}
}
}
<file_sep>/Lithopone/Kernel/DemogRunner.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using Lithopone.Memory;
using Lithopone.UIComponents;
namespace Lithopone.Kernel
{
public class DemogRunner
{
DemogWindow mMW;
private List<LINETYPE> mLinetypes;
private List<String> mVarNames;
public static String DEMOG_FILENAME = "demog.xml";
public DemogRunner(DemogWindow mw)
{
mMW = mw;
mLinetypes = new List<LINETYPE>();
mVarNames = new List<String>();
}
private void addTitle()
{
AddTextField("请在下面填写个人信息", "", 0, "TITLE");
}
public void GenUI(Dictionary<int, StDemogLine> lines)
{
addTitle();
for (int i = 0; i < lines.Count; i++)
{
if(lines.ContainsKey(i))
{
switch (lines[i].Type)
{
case LINETYPE.TXTFIELD:
AddTextField(lines[i].PreText, lines[i].PostText,
lines[i].Width, lines[i].VarName);
break;
case LINETYPE.RADIO:
AddRadioButtonLine(lines[i].PreText, lines[i].PostText,
lines[i].SubItems, lines[i].VarName);
if (lines[i].ForcedChoice)
{
((RadioButton)(getLinePane(mMW.amCanvas.Children.Count - 1).Children[1])).IsChecked = true;
}
break;
case LINETYPE.COMBO:
AddComboLine(lines[i].PreText, lines[i].PostText,
lines[i].SubItems, lines[i].VarName);
if (lines[i].ForcedChoice)
{
((ComboBox)(getLinePane(mMW.amCanvas.Children.Count - 1).Children[1])).SelectedIndex = 0;
}
break;
}
}
}
CompButton btnSubmmit = new CompButton("提交");
int btnWidth = 100;
int btnHeight = 40;
int btnUpGap = 31;
int btnDownGap = 10;
btnSubmmit.amButton.Width = btnWidth;
btnSubmmit.Width = btnWidth;
btnSubmmit.Height = btnHeight;
btnSubmmit.amButton.Height = btnHeight;
btnSubmmit.amButton.FontSize = 18;
btnSubmmit.SetBehavior(Submmit);
mMW.amCanvas.Children.Add(btnSubmmit);
Canvas.SetTop(btnSubmmit,
(mMW.amCanvas.Children.Count - 1) *
(KernelLib.LINE_HEIGHT + KernelLib.LINE_GAP) + btnUpGap);
Canvas.SetRight(btnSubmmit, 25);
int neededHeight = mMW.amCanvas.Children.Count *
(KernelLib.LINE_HEIGHT + KernelLib.LINE_GAP) + btnHeight + btnUpGap + btnDownGap;
if (neededHeight > mMW.amCanvas.Height)
{
mMW.amCanvas.Height = neededHeight;
}
mMW.Height = neededHeight + btnDownGap;
}
public void Submmit()
{
mMW.OnDemogClose();
}
private StackPanel getLinePane(int index)
{
return (StackPanel)mMW.amCanvas.Children[index];
}
private void addLabel2StackPane(ref StackPanel pane, String text)
{
Label label = new Label();
label.Content = text;
label.Width = text.Length * KernelLib.CHARA_WIDTH + 20;
label.Height = KernelLib.LINE_HEIGHT;
label.FontSize = KernelLib.DEMOG_FONT_SIZE;
pane.Children.Add(label);
}
private void addCombobox2StackPane(ref StackPanel pane, Dictionary<int, String> selections)
{
int upper = selections.Count;
int longest = 0;
ComboBox cb = new ComboBox();
for (int i = 0; i < upper; i++)
{
if (selections.ContainsKey(i))
{
if (selections[i].Length > longest)
longest = selections[i].Length;
cb.Items.Add(selections[i]);
}
}
cb.Height = KernelLib.LINE_HEIGHT;
cb.Width = KernelLib.CHARA_WIDTH * longest + 10;
cb.FontSize = KernelLib.DEMOG_FONT_SIZE;
pane.Children.Add(cb);
}
private void addTextField2StackPane(ref StackPanel pane, int width)
{
TextBox tb = new TextBox();
tb.Width = width;
tb.Height = KernelLib.LINE_HEIGHT;
tb.FontSize = KernelLib.DEMOG_FONT_SIZE;
pane.Children.Add(tb);
}
private void addRadioButtonGroup2StackPane(ref StackPanel sp, Dictionary<int, String> selections)
{
int upper = selections.Count;
for (int i = 0; i < upper; i++)
{
if (selections.ContainsKey(i))
{
RadioButton rb = new RadioButton();
rb.Content = selections[i] + " ";
rb.Height = KernelLib.LINE_HEIGHT;
rb.FontSize = KernelLib.DEMOG_FONT_SIZE;
sp.Children.Add(rb);
}
}
}
private void appendLinePan2Canvas(ref Canvas cvs, ref StackPanel sp)
{
cvs.Children.Add(sp);
Canvas.SetLeft(sp, 0);
Canvas.SetTop(sp, (mMW.amCanvas.Children.Count - 1) *
(KernelLib.LINE_HEIGHT + KernelLib.LINE_GAP));
}
public void AddComboLine(String preText, String postText,
Dictionary<int, String> selections, String name)
{
StackPanel sp = KernelLib.GenLinePane();
addLabel2StackPane(ref sp, preText);
addCombobox2StackPane(ref sp, selections);
addLabel2StackPane(ref sp, postText);
int elementCount = mMW.amCanvas.Children.Count;
appendLinePan2Canvas(ref mMW.amCanvas, ref sp);
LINETYPE type = LINETYPE.COMBO;
mLinetypes.Add(type);
mVarNames.Add(name);
}
public void AddTextField(String preText, String postText, int width, String name)
{
StackPanel sp = KernelLib.GenLinePane();
addLabel2StackPane(ref sp, preText);
addTextField2StackPane(ref sp, width);
addLabel2StackPane(ref sp, postText);
appendLinePan2Canvas(ref mMW.amCanvas, ref sp);
LINETYPE type = LINETYPE.TXTFIELD;
mLinetypes.Add(type);
mVarNames.Add(name);
}
public void AddRadioButtonLine(String preText, String postText,
Dictionary<int, String> contents, String name)
{
StackPanel sp = KernelLib.GenLinePane();
addLabel2StackPane(ref sp, preText);
addRadioButtonGroup2StackPane(ref sp, contents);
addLabel2StackPane(ref sp, postText);
appendLinePan2Canvas(ref mMW.amCanvas, ref sp);
LINETYPE type = LINETYPE.RADIO;
mLinetypes.Add(type);
mVarNames.Add(name);
}
private StGeneralInfo getLineInfo(int index)
{
StGeneralInfo retval = null;
StackPanel sp = ((StackPanel)(mMW.amCanvas.Children[index]));
String value = "";
switch(mLinetypes[index])
{
case LINETYPE.COMBO:
ComboBox cb = (ComboBox)sp.Children[1];
if (cb.SelectedIndex != -1)
{
value = (String)cb.Items[cb.SelectedIndex];
}
break;
case LINETYPE.TXTFIELD:
TextBox tb = (TextBox)sp.Children[1];
value = tb.Text;
break;
case LINETYPE.RADIO:
for (int i = 1; i < sp.Children.Count - 1; i++)
{
if (((RadioButton)sp.Children[i]).IsChecked == true)
{
value = (i - 1).ToString();
break;
}
}
break;
}
if (String.IsNullOrEmpty(value) || String.IsNullOrWhiteSpace(value))
{
System.Windows.Forms.MessageBox.Show(
"请完整填写所有信息", "提示",
System.Windows.Forms.MessageBoxButtons.OK,
System.Windows.Forms.MessageBoxIcon.Information);
retval = null;
}
else
{
retval = new StGeneralInfo(value, mVarNames[index]);
}
return retval;
}
public Dictionary<String, String> GetResult()
{
Dictionary<String, String> retval = new Dictionary<String, String>();
int upper = mMW.amCanvas.Children.Count;
for (int i = 1; i < upper - 1; i++)//title and button exclueded
{
StGeneralInfo info = getLineInfo(i);
if (info != null)
{
retval.Add(info.Name, info.Value);
}
else
{
retval = null;
break;
}
}
return retval;
}
}
}
<file_sep>/Lithopone/MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Lithopone.FileReader;
using Lithopone.Kernel;
using Lithopone.Memory;
using Lithopone.UIComponents;
using Arora;
namespace Lithopone
{
/// <summary>
/// MainWindow.xaml 的互動邏輯
/// </summary>
public partial class MainWindow : Window
{
static String BASEFOLER = AppDomain.CurrentDomain.BaseDirectory;
int mCurTestIndex = 0;
public Dictionary<String, String> mDemogInfo;
public DemogRunner mDemogRunner;
public int mScreenWidth, mScreenHeight;
TestRunner mCurRunner;
public ConfigCollection mConfigCollection;
public MainWindow(ConfigCollection confColl)
{
InitializeComponent();
this.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
mConfigCollection = confColl;
}
//prameters: element: the element to centralize, sizeX & sizeY: size of the element
public void centralize(UIElement element, int sizeX, int sizeY)
{
int screenX = (int)System.Windows.SystemParameters.PrimaryScreenWidth;
int screenY = (int)System.Windows.SystemParameters.PrimaryScreenHeight;
int offx = (screenX - sizeX) / 2;
int offy = (screenY - sizeY) / 2;
Canvas.SetTop(element, (double)offy);
Canvas.SetLeft(element, (double)offx);
}
public int getXScreenTaken()
{
return (int)(System.Windows.SystemParameters.PrimaryScreenWidth / 5 * 4);
}
public int getYScreenTaken()
{
return (int)(System.Windows.SystemParameters.PrimaryScreenHeight / 5 * 4);
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
mScreenWidth = (int)System.Windows.SystemParameters.PrimaryScreenWidth;
mScreenHeight = (int)System.Windows.SystemParameters.PrimaryScreenHeight;
TitlePage page = new TitlePage(this, getXScreenTaken(), getYScreenTaken());
page.amRichTxt.Document =
new FlowDocument(new Paragraph(new Run(mConfigCollection.mTestInfo.Description)));
page.amTitleBlock.Text = mConfigCollection.mTestInfo.Name;
amCanvas.Children.Add(page);
centralize(page, getXScreenTaken(), getYScreenTaken());
//test below
/* AroraCore ac = new AroraCore(new ReportForm());
AroraNormFactory anf = new AroraNormFactory();
Dictionary<int, StItem> items = new Dictionary<int, StItem>();
List<StAnswer> answers = new List<StAnswer>();
for (int i = 0; i < 68; i++)
{
StAnswer answer = new StAnswer(0, 3);
answers.Add(answer);
Dictionary<int,StSelection> selections = new Dictionary<int,StSelection>();
for(int j = 0; j < 4; j++)
{
selections.Add(j, new StSelection(0, (float)j, "aaa"));
}
StItem item = new StItem(i, "none", ref selections);
items.Add(i, item);
}
ac.SetData(items, answers, new Dictionary<String, String>(), anf.GetNorm());
ac.Run();*/
FullScreen();
//systest
/*AroraNormFactory anf = new AroraNormFactory();
AroraReport rep = new AroraReport(mDemogLines.Count, 68,
anf.GetNorm());
rep.DoReport();*/
}
public void FullScreen()
{
this.WindowState = System.Windows.WindowState.Normal;
this.WindowStyle = System.Windows.WindowStyle.None;
this.ResizeMode = System.Windows.ResizeMode.NoResize;
//this.Topmost = true;
this.Left = 0;
this.Top = 0;
this.Width = System.Windows.SystemParameters.PrimaryScreenWidth;
this.Height = System.Windows.SystemParameters.PrimaryScreenHeight;
}
public void OnTitleClose()
{
amCanvas.Children.Clear();
//mDemogInfo = new Dictionary<string, string>();
DemogWindow dw = new DemogWindow(this);
mDemogRunner = new DemogRunner(dw);
mDemogRunner.GenUI(mConfigCollection.mDemogLines);
dw.ShowDialog();
}
//how to call report
public void OnThanksClose()
{
AroraCore ac = new AroraCore();
ac.SetData(mCurRunner.mItemPage.mItems,
mCurRunner.mAnswers, mDemogInfo, mConfigCollection.mNorms);
ac.Sta_Save();
AroraReport rep = new AroraReport(mConfigCollection.mDemogLines.Count,
mCurRunner.mItemPage.mItems.Count, mConfigCollection.mNorms);
rep.DoReport();
this.Close();
}
public void OnDemogClose()
{
if (mDemogInfo != null)
{
mCurRunner = new TestRunner(Lib.TestFileName, this);
mCurRunner.SetInstructionPage();
mCurTestIndex++;
}
}
public void OnTestClose()
{
ThanksPage page = new ThanksPage(this);
amCanvas.Children.Clear();
amCanvas.Children.Add(page);
Canvas.SetTop(page, 0);
Canvas.SetLeft(page, 0);
}
~MainWindow()
{
}
}
}
<file_sep>/Lithopone/DocManageWnd.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using Arora;
using Lithopone.FileReader;
using LibTabCharter;
using System.IO;
namespace Lithopone
{
/// <summary>
/// DocManageWnd.xaml 的互動邏輯
/// </summary>
public partial class DocManageWnd : Window
{
public ConfigCollection mConfigs;
public DocManageWnd(ConfigCollection configs)
{
InitializeComponent();
mConfigs = configs;
}
private ObservableCollection<Memory.StDocManageBriefInfo> readRecBriefList()
{
ObservableCollection<Memory.StDocManageBriefInfo> list =
new ObservableCollection<Memory.StDocManageBriefInfo>();
if (System.IO.File.Exists(Arora.AroraCore.OUT_PATH))
{
LibTabCharter.TabFetcher fetcher =
new LibTabCharter.TabFetcher(Arora.AroraCore.OUT_PATH, "\\t");
List<String> lineBuf = null;
fetcher.Open();
fetcher.GetLineBy();//skip first line
while ((lineBuf = fetcher.GetLineBy()).Count != 0)
{
Memory.StDocManageBriefInfo lineSt = new Memory.StDocManageBriefInfo();
lineSt.Name = lineBuf[0];
lineSt.Number = lineBuf[6];
lineSt.Stamp = lineBuf[7];
list.Add(lineSt);
}
fetcher.Close();
}
return list;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
amDataGrid.DataContext = readRecBriefList();
amDataGrid.Items.Refresh();
}
private void amBtnClose_Click(object sender, RoutedEventArgs e)
{
Close();
}
private void amBtnDel_Click(object sender, RoutedEventArgs e)
{
int index = amDataGrid.SelectedIndex;
if (index != -1)
{
//read
List<List<String>> table = new List<List<string>>();
TabFetcher fet = new TabFetcher(AroraCore.OUT_PATH, "\\t");
fet.Open();
List<string> lineBuf = null;
while ((lineBuf = fet.GetLineBy()).Count != 0)
{
table.Add(lineBuf);
}
fet.Close();
//remove
table.RemoveAt(index + 1);
//write
File.Delete(AroraCore.OUT_PATH);
TabCharter charter = new TabCharter(AroraCore.OUT_PATH);
charter.Create(table[0]);
for (int i = 1; i < table.Count; i++)
{
charter.Append(table[i]);
}
amDataGrid.DataContext = readRecBriefList();
}
}
private void amBtnCheck_Click(object sender, RoutedEventArgs e)
{
if (amDataGrid.SelectedIndex != -1)
{
AroraReport rep = new AroraReport(mConfigs.mDemogLines.Count, mConfigs.mTestInfo.ItemCount,
mConfigs.mNorms, amDataGrid.SelectedIndex + 1);
rep.DoReport();
}
}
}
}
<file_sep>/Lithopone/FileReader/PackageReader.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Lithopone.Memory;
namespace Lithopone.FileReader
{
public class PackageReader : BinaryReaderBase
{
public void ExtractFile(string path, BLOCKTYPE type)
{
FileStream fso = new FileStream(path, FileMode.Create, FileAccess.Write);
StBlockDscription dscp = GetBlockInfo(type);
mFs.Position = dscp.Begin;
int red = 0;
int thisRed = 0;
int buflen = 1024;
int readingPlan = 0;
int left = 0;
readingPlan = buflen < dscp.Length ? buflen : dscp.Length;
byte[] buf = new byte[1024];
bool doRead = true;
while (doRead)
{
//counting
thisRed = mFs.Read(buf, 0, readingPlan);
fso.Write(buf, 0, thisRed);
red += thisRed;
//make plan
left = dscp.Length - red;
if (left >= buflen)
{
readingPlan = buflen;
}
else
{
readingPlan = left;
}
//if stop
if (red == dscp.Length)
doRead = false;
}
fso.Close();
}
public StPFileInfo GetPFileInfo()
{
StPFileInfo retval = new StPFileInfo();
mFs.Position = 0;
retval.Version = ReadInt();
retval.Mode = ReadByte();
retval.ResourceStatus = ReadByte();
return retval;
}
}
}
<file_sep>/LithoponeReportDLL/AroraAppendableGeneralReader.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LibTabCharter;
using Lithopone.Memory;
namespace Arora
{
public class AroraAppendableGeneralReader
{
public int mDemogLen;
public int mTestCount;
public StNormAuto mNorm;
private TabFetcher mFetch;
private List<String> mLine;
public AroraAppendableGeneralReader(int DemogLen, int TestCount, StNormAuto Norm)
{
mFetch = new TabFetcher(AroraCore.OUT_PATH, "\\t");
mDemogLen = DemogLen;
mTestCount = TestCount;
mNorm = Norm;
}
public void Fetch(int index)
{
mFetch.Open();
if (index != -1)
{
mLine = mFetch.GetLineAt(index);
}
else
{
mLine = mFetch.GetLineAt(mFetch.GetLineCount() - 2);
}
mFetch.Close();
}
public int GetRatingDimCount()
{
return mNorm.Dims.Count;
}
private int getBaseOffset()
{
return mDemogLen + 1 + mTestCount * 2;
//demog + time + itemCount * 2(indexSel, value)
}
public double GetItemSelected(int Index)
{
return double.Parse(mLine[mDemogLen + 1 + Index * 2]);
}
public double GetItemSelectedValue(int Index)
{
return double.Parse(mLine[mDemogLen + 1 + Index * 2 + 1]);
}
public double GetDimScore(int Index)
{
return double.Parse(mLine[getBaseOffset() + Index * 3]);
}
public double GetDimPercentile(int Index)
{
return double.Parse(mLine[getBaseOffset() + Index * 3 + 1]);
}
public double GetDimStdScore(int Index)
{
return double.Parse(mLine[getBaseOffset() + Index * 3 + 2]);
}
public bool IsValid()
{
return bool.Parse(mLine[getBaseOffset() + mNorm.Dims.Count * 3 + 1]);
}
}
}
<file_sep>/Memory/Memory/Enums.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lithopone.Memory
{
public enum GRAPH_SIZE { UNKNOWN, SMALL, MEDIUM, LARGE };
public enum LINETYPE { UNKNOW, COMBO, RADIO, TXTFIELD };
}
<file_sep>/Memory/Memory/StRank.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lithopone.Memory
{
public class StRank
{
public int ID;
public List<StRankSpan> Spans;
}
}
<file_sep>/Lithopone/UIComponents/CompInstructionPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Lithopone.Kernel;
namespace Lithopone.UIComponents
{
/// <summary>
/// CompInstructionPage.xaml 的互動邏輯
/// </summary>
public partial class CompInstructionPage : UserControl
{
public TestRunner mTestRunner;
public CompInstructionPage(TestRunner tr, int sizeX, int sizeY)
{
InitializeComponent();
mTestRunner = tr;
this.Width = sizeX;
this.Height = sizeY;
amTitleLabel.Width = sizeX;
amInstructionText.Width = sizeX;
amInstructionText.Height = sizeY - 52 - 2 * 10;
Canvas.SetTop(amOKBtn, sizeY - 52 - 20);
Canvas.SetLeft(amOKBtn, (sizeX - 122) / 2);
}
private void amOKBtn_Click(object sender, RoutedEventArgs e)
{
mTestRunner.StartTest();
}
}
}
<file_sep>/Lithopone/Kernel/TestRunner.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lithopone.Memory;
using Lithopone.FileReader;
using System.IO;
using System.Windows.Controls;
using Lithopone.UIComponents;
using System.Windows.Forms;
namespace Lithopone.Kernel
{
public class TestRunner
{
public StTestXmlHeader mTestAttr;
private String mSrcPath;
public ItemPage mItemPage;
public List<StAnswer> mAnswers;
public MainWindow mMainWindow;
//public static String BUFFER_FOLDER = AppDomain.CurrentDomain.BaseDirectory + "LithoponeBuf\\";
//public static String XMLFILE_PATH = BUFFER_FOLDER + "test.xml";
private FEITTimer mTimer;
public int mCurTill = 0;
public TestRunner(String srcPath, MainWindow mw)
{
//folderWork();
mMainWindow = mw;
mSrcPath = srcPath;
mAnswers = new List<StAnswer>();
mTimer = new FEITTimer();
startItemFileSystem();
}
private void startItemFileSystem()
{
//test xml
TestXmlReader xmlReader = new TestXmlReader();
xmlReader.Begin(Lib.TestFileName);
mTestAttr = xmlReader.GetHeader();
Dictionary<int, StItem> items = xmlReader.GetItems();
xmlReader.Finish();
//itemsRunner
mItemPage = new ItemPage(items, this,
mMainWindow.getXScreenTaken(), mMainWindow.getYScreenTaken());
/*if(mTestAttr.GraphicCasual || mTestAttr.GraphicSelection)
mItemRunner.OpenConnection();*/
}
public void SetInstructionPage()
{
mMainWindow.amCanvas.Children.Clear();
CompInstructionPage page = new CompInstructionPage(this,
mMainWindow.getXScreenTaken(), mMainWindow.getYScreenTaken());
page.amTitleLabel.Content = mTestAttr.Name;
page.amInstructionText.Text = mTestAttr.Instruction;
mMainWindow.amCanvas.Children.Add(page);
mMainWindow.centralize(page,
mMainWindow.getXScreenTaken(), mMainWindow.getYScreenTaken());
}
public void StartTest()
{
//mMainWindow.Width = 590;
//mMainWindow.amScrollViewer.Width = 630;
//mMainWindow.Height = 430;
//mMainWindow.amScrollViewer.Height = 430;
mMainWindow.amCanvas.Children.Clear();
mMainWindow.amCanvas.Children.Add(mItemPage);
//centralize
mMainWindow.centralize(mItemPage,
mMainWindow.getXScreenTaken(), mMainWindow.getYScreenTaken());
SetPage(0);
}
public void SetPage(int index)
{
mTimer.Stop();
mTimer.Reset();
int uiSelected = -1;
//load result
if (mAnswers.Count > index)
{
uiSelected = mAnswers[index].Selected;
}
mItemPage.SetPage(index, uiSelected);
//set timer
mTimer.Start();
}
public StTestXmlHeader GetTestAttribute()
{
return mTestAttr;
}
public void Save()
{
if (mCurTill < mAnswers.Count)
{
mAnswers[mCurTill].Selected = mItemPage.amCompSelection.GetSelectedIndex();
mAnswers[mCurTill].RT = mTimer.GetElapsedTime();
}
else
{
mAnswers.Add(new StAnswer(mTimer.GetElapsedTime(),
mItemPage.amCompSelection.GetSelectedIndex()));
}
}
public void TestEnd()
{
Console.WriteLine("TestEnd()");
/*if(mTestAttr.GraphicCasual || mTestAttr.GraphicSelection)
mItemRunner.CloseConnection();*/
mMainWindow.OnTestClose();
}
}
}
<file_sep>/Memory/Memory/StNormAuto.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lithopone.Memory
{
public class StNormAuto
{
public List<StNormDim> Dims;
public StNormValidity Validity;
public StNormAuto()
{
Dims = new List<StNormDim>();
Validity = new StNormValidity();
}
}
}
<file_sep>/Memory/Memory/StResourceDscp.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lithopone.Memory
{
public class StResourceDscp
{
public long beg;
public long len;
public long type;
}
}
<file_sep>/Memory/Memory/StNormValidity.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lithopone.Memory
{
//class to check if the test users` result is legal
public class StNormValidity
{
public List<int> ItemIndex;//validity verification item list
public ValidityPrincipal Principal;//how to verify the validity
public int Tolerance;//how many times` breaking validity pricipal is allowed
public StNormValidity()//constructor
{
ItemIndex = new List<int>();
Principal = ValidityPrincipal.None;
Tolerance = -1;
}
}
public enum ValidityPrincipal
{
None, ValueEqual, IndexEqual
}
}
<file_sep>/LithoponeReportDLL/AroraReport.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Lithopone.Memory;
using System.IO;
using System.Windows.Forms.DataVisualization.Charting;
using System.Drawing;
//PTSD Double Test
namespace Arora
{
public class AroraReport
{
protected static String OUT_PATH_SPECIFIC =
AppDomain.CurrentDomain.BaseDirectory + "\\AroraAppendableSpecific";
public ReportUI mUI;
private int mCurPage = 0;
private int mTotalPages;
private AroraAppendableGeneralReader mReader;
public StNormAuto mNorm;
public AroraReport(int DemogLen, int TestCount, StNormAuto Norm, int UserIndex = -1)
{
mUI = new ReportUI(this);
mReader = new AroraAppendableGeneralReader(DemogLen, TestCount, Norm);//norm for offset count
mReader.Fetch(UserIndex);
mTotalPages = mReader.mNorm.Dims.Count;
mNorm = Norm;
}
/*public override void Run()
{
//calc
calcNormRelatedResult();
DoReport();
}*/
public void SetReportPageContent(int index)
{
//chart
Color aboveColor = Color.FromArgb(255, 100, 100);
Color belowColor = Color.FromArgb(200, 200, 255);
NormDistriBarviewGen.SetChart(mUI.chart1, (int)(Math.Round(mReader.GetDimPercentile(index) * 100.0)),
aboveColor, belowColor);
//richText
mUI.richTextBox1.Text = mReader.mNorm.Dims[index].Name + ": 高于%" +
((int)(Math.Round(mReader.GetDimPercentile(index)* 100.0))).ToString() + "的人群(红色部分)";
//label
mUI.label1.Text = (index + 1).ToString() + "/" + mTotalPages;
//comment
attachComment(index);
}
private void attachComment(int dimIndex)
{
//validity comment
if (!mReader.IsValid())
{
mUI.richTextBox1.Text += "\r\n题目前后回答不一致";
}
//level comment
if (mNorm.Dims[dimIndex].Levels.Count != 0)
{
string textShow = "";
//get target value first
double targetval = -1;
if (mNorm.Dims[dimIndex].TargetValue == NormTargetValue.Percentile)
{
targetval = mReader.GetDimPercentile(dimIndex) * 100.0;
}
else if (mNorm.Dims[dimIndex].TargetValue == NormTargetValue.RawScore)
{
targetval = mReader.GetDimScore(dimIndex);
}
else if (mNorm.Dims[dimIndex].TargetValue == NormTargetValue.StdScore)//total score only
{
targetval = mReader.GetDimStdScore(dimIndex);
}
textShow += "\r\n得分: " + targetval;
textShow += "\r\n\r\n" + mNorm.Dims[dimIndex].Name + "评价: ";
int levelAt = -1;
for (int i = 0; i < mNorm.Dims[dimIndex].Levels.Count; i++)
{
if (targetval >= mNorm.Dims[dimIndex].Levels[i].FloorWith &&
targetval < mNorm.Dims[dimIndex].Levels[i].CeilingWithout)
{
levelAt = i;
break;
}
}
textShow += "\r\n" + mNorm.Dims[dimIndex].Levels[levelAt].Description;
mUI.richTextBox1.Text += textShow;
}
}
public void DoReport()
{
//ReadResultForm();
SetReportPageContent(0);
mUI.Show();
}
public void NextPage()
{
if (mCurPage < mTotalPages - 1)
{
mCurPage++;
SetReportPageContent(mCurPage);
}
if (mCurPage == mTotalPages - 1)
{
mUI.button2.Text = "打印";
}
}
public void PrevPage()
{
if (mCurPage > 0)
{
mCurPage--;
SetReportPageContent(mCurPage);
mUI.button2.Text = "下一页";
}
}
public void Close()
{
}
}
}
<file_sep>/Lithopone/FileReader/ConfigCollection.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lithopone.Memory;
namespace Lithopone.FileReader
{
public class ConfigCollection
{
public Dictionary<int, StDemogLine> mDemogLines;
public StTestXmlHeader mTestInfo;
public StNormAuto mNorms;
public ConfigCollection()
{
//demog structure
Lithopone.FileReader.DemogXmlReader rd = new FileReader.DemogXmlReader();
mDemogLines = rd.GetDemogItems(Lib.DemogFileName);
//test structure
TestXmlReader xmlReader = new TestXmlReader();
xmlReader.Begin(Lib.TestFileName);
mTestInfo = xmlReader.GetHeader();
xmlReader.Finish();
//norm structure
mNorms = nf.GetNorm();
}
}
}
<file_sep>/Memory/Memory/StUserOption.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lithopone.Memory
{
public class StUserOption
{
public int Key;
public string VarName;
public string OptionString;
public string Note;
}
}
<file_sep>/Memory/Memory/StTestXmlHeader.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lithopone.Memory
{
public class StTestXmlHeader
{
public int Version;
public int ID;
public String Name;
public String Description;
public String Instruction;
public bool TextSelection;
public bool TextCausal;
public bool GraphicSelection;
public bool GraphicCasual;
public GRAPH_SIZE SelectionSize;
public GRAPH_SIZE CasualSize;
public int ItemCount;
}
}
<file_sep>/Memory/Memory/StNormDim.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lithopone.Memory
{
public class StNormDim
{
public string Name;//dimension name
public List<int> ItemIndexList;//dimension`s items
public double Mean;//mean score
public double SD;//standard deviation of the socre
public NormTargetValue TargetValue;//target value type
public List<StNormLevel> Levels;//levels of the dimension
public StNormStdScoreMethod Method;//method to make this dimension`s standard score
public StNormDim()
{
Name = "";
ItemIndexList = new List<int>();
Mean = -1;
SD = -1;
TargetValue = NormTargetValue.None;
Levels = new List<StNormLevel>();
Method = null;
}
public double GetStandardScore()
{
return -1;
}
}
public enum NormTargetValue
{
None, RawScore, StdScore, Percentile
}
}
<file_sep>/Memory/Memory/StDescription.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lithopone.Memory
{
public class StDescription
{
public int Key;
public string Content;
}
}
<file_sep>/Lithopone/UIComponents/CompTextLarge.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Lithopone.UIComponents
{
/// <summary>
/// CompTextCasual.xaml 的互動邏輯
/// </summary>
public partial class CompTextLarge : UserControl
{
public static int HEIGHT = 60;
public CompTextLarge()
{
InitializeComponent();
BorderBrush = new SolidColorBrush(Color.FromRgb(255, 255, 255));
}
public void SetText(String text)
{
amLabel.Content = text;
//amLabel.Width = text.Length * 15 + 22;
//this.Width = text.Length * 15 + 22;
}
}
}
<file_sep>/Lithopone/Lib.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows;
using Lithopone.Memory;
namespace Lithopone
{
public class Lib
{
public const String TestFileName = "tsource";
public const String DemogFileName = "dsource";
public static LINETYPE Str2LineType(String typeStr)
{
LINETYPE retval = LINETYPE.UNKNOW;
if (typeStr.Equals("RADIO"))
{
retval = LINETYPE.RADIO;
}
else if (typeStr.Equals("COMBO"))
{
retval = LINETYPE.COMBO;
}
else if (typeStr.Equals("TXTFIELD"))
{
retval = LINETYPE.TXTFIELD;
}
return retval;
}
public static GRAPH_SIZE Str2Size(string src)
{
GRAPH_SIZE ret = GRAPH_SIZE.UNKNOWN;
if (src.Equals("SMALL"))
ret = GRAPH_SIZE.SMALL;
else if (src.Equals("MEDIUM"))
ret = GRAPH_SIZE.MEDIUM;
else if (src.Equals("LARGE"))
ret = GRAPH_SIZE.LARGE;
return ret;
}
public static int Size2Number(GRAPH_SIZE size)
{
int retval = -1;
switch (size)
{
case GRAPH_SIZE.SMALL:
retval = 50;
break;
case GRAPH_SIZE.MEDIUM:
retval = 100;
break;
case GRAPH_SIZE.LARGE:
retval = 200;
break;
}
return retval;
}
}
}
<file_sep>/Memory/Memory/StItem.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lithopone.Memory
{
public class StItem
{
public int ResID;
public string Casual;
public Dictionary<int, StSelection> Selections;
public StItem(int ri, string cas, ref Dictionary<int, StSelection> sel)
{
ResID = ri;
Casual = cas;
Selections = sel;
}
}
}
|
4a33406eaff35065a1085ab2dfcc1b1ea2fd2f65
|
[
"C#"
] | 49
|
C#
|
ellil4/Lithopone_sharp
|
101f9b48f239bb379fdff2732bbe865b7048fa9c
|
c1cb7d3dce8c7c867f1417faad7ef35c3295d5db
|
refs/heads/master
|
<repo_name>nathan-j-brenner/playground<file_sep>/fakearray.js
// module fakearray.js
module.exports = {
length: 0,
pop: function() {
if(this.length>1){
var returnValue = this[this.length - 1]; //returnValue should be the last element the array
this[this.length-1] = undefined; //the last element of the array has a value of undefined
this.length--;
return returnValue;
}
},
push: function(input) {
if(input != undefined){
this[this.length] = input;
this.length++;
return this.length;
}
},
shift: function(){
if(this.length>1){
var returnValue = this[0];
this[this[0]] = undefined;
this.length--;
return returnValue;
}
},
unshift: function(input){
for(var i = this.length; i>this.length; i--){
this[i+1] = this[i];
}
this[0] = input;
this.length++;
return this.length;
}
};
/*
pop: removes last element of the array, returns that element
push: adds element to the end of the array, returns the length of the array
shift: removes the first element of an array, returns that element
unshift: adds an element to the beginning of an array, returns the length of the array
*/<file_sep>/README.md
# playground
directories for javascript immersion projects
<file_sep>/testing.js
// var assert = require('assert');
// var arr = [1, 2, 3];
// // var lastElem = arr.pop();
// // assert.equal(lastElem, 3, "expected " + lastElem + " to equal 3, but it didn't");
// // assert.fail(lastElem, 4, "expected " + lastElem + " to equal 3, but it didn't");
// //what is the forth argument 'operator' for .fail?
// // assert.notDeepEqual(lastElem, '2', "expected " + lastElem + " to equal 3, but it didn't");
// var addElem = arr.push(3);
// assert.equal(addElem, 4, "expected " + addElem + " to be the last element added to arr");
// console.log(arr);
var fakeArray = require('../fakearray.js');
var assert = require('assert');
describe('My fake array object', function() {
describe('The pop method', function() {
before(function() {
fakeArray[0] = 1;
fakeArray[1] = 2;
fakeArray[2] = 3;
fakeArray.length = 3;
});
it('should return the final element', function() {
assert.equal(fakeArray.pop(), 3);
});
});
});<file_sep>/promises.js
// function inASecond(cb) {
// console.log('one sec...')
// setTimeout(function() {
// console.log('doing it now:')
// cb();
// },1000);
// }
// function sayHello() {
// console.log('hello!');
// }
// // sayHello();
// function Promise(startDoingAsyncFn) {
// var pendingTask = null;
// this.then = function(afterwardFn) {
// pendingTask = afterwardFn;
// }
// function fulfilPromise() {
// if (pendingTask)
// pendingTask();
// }
// startDoingAsyncFn(fulfilPromise);
// }
// // Optional factory using that ctor:
// function makePromise(startDoingAsyncFn) {
// return new Promise(startDoingAsyncFn);
// }
// makePromise(inASecond).then(sayHello);
//exercise
function Promise(startDoingAsyncFn) {
var pendingTask = [];
this.then = function(afterwardFn) {
pendingTask.push(afterwardFn);
return this;
}
function fulfilPromise() {
var nextAction = pendingTask.shift();
if (nextAction){
nextAction(fulfilPromise);
}
}
startDoingAsyncFn(fulfilPromise);
}
// Optional factory using that ctor:
function makePromise(startDoingAsyncFn) {
return new Promise(startDoingAsyncFn);
}
function inASecond(cb) {
console.log('one sec...')
setTimeout(function() {
console.log('doing it now:')
cb();
},1000);
}
function sayHello() {
console.log('hello!');
}
makePromise(inASecond).then(inASecond).then(inASecond).then(inASecond);
//relate to databases: pg and knex have a promise interface
<file_sep>/sum_of_two_numbers.js
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("Pick a number", function(numberA){
rl.question("Pick a second number", function(numberB){
numberA = parseInt(numberA);
numberB = parseInt(numberB);
console.log(numberA + " + " + numberB + " = " + (numberA + numberB));
});
rl.close();
});
<file_sep>/message.js
#!/usr/bin/env node
var message = require('./message.json');
console.log(message.messages);<file_sep>/migrations/20150602151341_countries.js
exports.up = function(knex, Promise) {
return knex.schema.createTable('countries', function(table) {
table.increments('id').primary();
table.string('name');
});
};
exports.down = function(knex, Promise) {
return knex.schema.dropTable('countries');
};
knex('countries').insert({name: 'Nate'});
<file_sep>/scope.js
// var x = 5;
// var z;
var add = function(x, y) {
console.log(result);
var result;
result = x + y;
return result;
};
var subtract = function(x, y) {
var result;
result = x - y;
return result;
};
// console.log(x);
function hoist(){ //even though console.log comes before the variable is defined, the varible definition is created first. Best practice: write it in the order that it'll be processed
console.log(a);
var a;
}
// hoist();
// var x = 0; //without this line: error
// var foo = function(x) { //local x shadows global x
// var bar = function(x) {
// return x; //without this line, x is undefined so x exists in global scope
// };
// return bar(x); //without this line, x is undefined so x exists in global scope
// };
// console.log(foo(x)); //x=0 x is from the global variable
// var x = 0;
function sequence(){
console.log(x);
x++;
}
// function counter(){
// console.log(x);
// x++;
// }
function counter(x){ //the argument determines what number to start on
// var x = 0;
return function(){
console.log(x);
x++;
};
}
// var sequence1 = counter(3);
// var sequence2 = counter(0);
// sequence1(); //=> 0
// sequence1(); //=> 1
// sequence2(); //=> 0
// sequence1(); //=> 2
// sequence2(); //=> 1
var counter = //module pattern
function(){
var x = 0;
function count(val){
x += val;
console.log(x);
}
return {
next: function(){
count(1);
},
reset: function(){
// x = val;
// if (x===undefined){
// x="null";
// };;
console.log(x);
}
};
};
var sequence1 = counter();
var sequence2 = counter();
// sequence1.next(); //=> 0
// sequence1.next(); //=> 1
// sequence2.next(); //=> 0
// sequence1.next(); //=> 2
// sequence1.reset(); //=> void
// sequence1.next(); //=> 0
// sequence2.next(); //=> 1
// sequence1.reset(5); //=> void
// sequence1.next(); //=> 5
var foo = 1;
function bar() {
if (!foo) {
var foo = 10;
}
alert(foo);
}
bar();
<file_sep>/functions.js
// function showUserDetail(){
// checkThatUserIsLoggedIn();
// }
// function editProfile(){
// checkThatUserIsLoggedIn();
// }
// //easier
// function loggedIn(action){
// return function(){
// if (userIsLoggedIn) {
// action();
// } else{
// return "You have to log in!"
// }
// }
// }
// //fibbonacci 1 1 (1+1)=2 (1+2) = 3 5 8
// /**
// * Find the nth (zero-indexed) Fibonacci number.
// */
// var fibonacci = function(n) {
// return n > 1 ? fibonacci(n - 1) + fibonacci(n - 2) : 1;
// };
// console.log(fibonacci(Number(process.argv[2])));
// //or
// /**
// * Find the nth (zero-indexed) Fibonacci number.
// */
// var fibonacci = function(n) {
// return n > 1 ? fibonacci(n - 1) + fibonacci(n - 2) : 1;
// };
// console.log(fibonacci(Number(process.argv[2])));
// //or
// var fibonacci = function(n){
// if(n>1){
// return fibonacci(n-1) + fibonacci(n-2);
// } else {
// return 1;
// }
// }
//speed up
// var knownFibonacciNumbers = {};
// var fibonacci = function(n) {
// if (knownFibonacciNumbers[n] === undefined) {
// if ( n > 1 ) {
// knownFibonacciNumbers[n] = fibonacci(n - 1) + fibonacci(n - 2);
// } else {
// knownFibonacciNumbers[n] = 1;
// }
// knownFibonacciNumbers[n] = n > 1 ? fibonacci(n - 1) + fibonacci(n - 2) : 1;
// }
// return knownFibonacciNumbers[n];
// };
// console.log(fibonacci(Number(process.argv[2])));
// memorizing
// var dumbFibonacci = function(n){
// return n > 1? dumbFibonacci(n-1) + dumbFibonacci(n-2) : 1;
// }
// var fibonacci = function(n){
// console.log(n);
// return n > 1 ? fibonacci(n-1) + fibonacci(n-2) : 1;
// };
// function memoize(f) {
// var knownValues = {};
// return function(n) {
// if (knownValues[n] === undefined) {
// knownValues[n] = f(n);
// }
// return knownValues[n];
// }
// }
// fibonacci = memoize(fibonacci);
// console.log(fibonacci(Number(process.argv[40])));
// function once(f){
// var knownOnce = false;
// return function(){
// if(knownOnce === false){
// knownOnce = f();
// }
// return knownOnce;
// };
// }
// var findTrueLove = once(function(){
// console.log("Looking for true love...");
// });
// findTrueLove();
// findTrueLove();
// mod 5 % 2 gives 1, which is the remainder
//implement filter function
// var numbers = [1, 2, 3, 4, 5, 6];
// var numbers2 = [7, 8, 9, 10, 11, 12];
// function filter(arrayArgument, divider){ //filter function takes two arguments: an array and a number that will applied to each item in the array argument
// var filteredArray = []; //this creates an empty array that will store the values that meet the qualifications of the diviser
// return function(){
// for(var i = 0; i<arrayArgument.length; i++){ //loops through each item in the array argument
// if((arrayArgument[i]%divider)===0){ //if the items in the array argument are divisible by divider
// filteredArray.push(arrayArgument[i]); //then all those array items are put into the filered array
// }
// }
// if(filteredArray.length===0) { //if the filtered array has no items
// console.log("None of the numbers are dividable by " + divider);
// } else { //if the filtered array has items, then it prints out those items
// for(var n = 0; n<filteredArray.length; n++){ //this loop just removes the array syntax
// console.log(filteredArray[n]);
// }
// }
// };
// }
// var evenNumbers = filter(numbers, 2);
// evenNumbers();
//improved version
// function filter(array, fn){
// var filtered = [];
// array.forEach(function(element) {
// if(fn(element)){
// filtered.push(element);
// }
// })
// return filtered;
// }
// var numbers = [1-10]
// var otherNumbers
// var sharedNumbers = filter(numbers, function(num) {return otherNumbers.indexOf(num) !== -1})
// reduce
// var arrays = [[10], ['string'], [{}]];
// var result = [];
// arrays.forEach(function(a) {result = result.concat(a);});
// result; //=> [10, 'string', {}]
// var numbers = [1, 2, 3, 4, 5, 6];
// var sum = 0;
// numbers.forEach(function(n) {
// sum += n;
// });
// console.log(sum); //=> 21
// var pairs = [
// ['name', 'JSI'],
// ['location', { city: 'Portland', 'state': 'OR'}],
// ['school', 'PCS']
// ];
// var result = [];
// pairs.forEach(
// function(a, b) {
// result = result.concat('{' + a + ':' + b + '}');
// console.log(pairs);
// }, {});
// var obj = pairs.reduce(function(accumulatingValue, currentValue){
// //currentVale looks [key, value]
// var key = currentValue[0];
// var value = currentValue[1];
// accumulatingValue[key] = value;
// return accumulatingValue;
// }, {});
// console.log(obj);
// big picture structure
// learning strategies
// sequence of topics
// collaboration, comfort zone/discomfort zone
// demand quality, communicate what you need, count your blessings
//at
function filter(array, fn){
var filtered = [];
array.forEach(function(element) {
if(fn(element)){
filtered.push(element);
}
});
return filtered;
}
var numbers = [1, 2, 3, 4, 5, 6, 7];
var otherNumbers = [1, 3, 5, 7];
var sharedNumbers = filter(numbers, function(num) {return otherNumbers.indexOf(num) !== -1};);
// var array = function at(collection, property){
// atArray = [];
// collection.forEach(function(element){
// if(property(element)){
// atArray.push(element);
// }
// })
// return atArray;
// };
// array(["hello", "world", "today"], [1, 3]);
<file_sep>/pgFun.js
var pg = require('pg');
var settings = "postgres://localhost/test"; // "postgres://username:password@localhost/database";
var id = process.argv[2];
if (process.argv.length <= 2) { return console.error('please provide an id to look up'); }
var client = new pg.Client(settings);
client.connect(function(err) {
if(err)
return console.error('could not connect to postgres', err);
client.query('select * from people where name = $1::text', [id], function(err, result) { //async call
if(err)
return console.error('error running query', err);
console.log('Search results:');
console.log('%j', result.rows[0]);
client.end();
});
});
//process.argv chops off first two things in node, array of whateverwords you type here
// $1::int $1 is the first thing that is in the following array, :: make sure it's formatted as a argument, not a string
//postgres doesn't care about directories
//no promises, this uses callbacks
//this talks to sql from javascript<file_sep>/knex_demo.js
var env = process.env.NODE_ENV || 'development';
var knexConfig = require('./knexfile.js')[env];
var knex = require('knex')(knexConfig);
function log(it){
console.log(it);
}
function finish(err, result){
if (err){
console.log(err);
} else{
console.log(result);
}
};
//this creates a new row
// knex('countries').insert([{name:'Canada'}]).then(log).catch(log);
//change the values of a column on a row
// knex('countries').where('id', '=', '8').update({id: '2'}).then(log).catch(log);
// knex('countries').select('name').then(log);
//delete a row
// knex('countries').del().where('name', 'USA').then(log);
//print the whole table
// knex.select().table('countries').then(log).catch(log);
//print just the selected elements from the table
// knex.select('name').from('countries').then(log).catch(log);
function grantAccess(user) {
if (user[0] != undefined){
console.log("your user exists");
} else{
console.log("invalid access");
}
}
var userName = process.argv[2];
knex('users').where([username: username, password: <PASSWORD>]).then(grantAccess);
|
eb93b367246ec278d270a73ad52f350a628c69dc
|
[
"JavaScript",
"Markdown"
] | 11
|
JavaScript
|
nathan-j-brenner/playground
|
98753075ad5a47f1709d68f94025efa7b1615505
|
beecc8fe6570cd03b2cc72ab39ea0225f61d2f60
|
refs/heads/master
|
<file_sep>var searchData=
[
['_5f_5ffilt_5fcoef',['__FILT_COEF',['../dd/db8/struct_____f_i_l_t___c_o_e_f.html',1,'']]],
['_5f_5fq_5fformat',['__Q_FORMAT',['../de/d4e/struct_____q___f_o_r_m_a_t.html',1,'']]]
];
<file_sep>/**
* @file dspQFormatConvert.h
*
* @date 2015. 6. 12.
* @author i04055dt
*/
#ifndef DSPQFORMATCONVERT_H_
#define DSPQFORMATCONVERT_H_
#define SAMPLE_RATE 48000 ///< Audio Sampling Rate = 48000Hz
#ifndef M_LN2
#define M_LN2 0.69314718055994530942 ///<
#endif /* M_LN2 */
#ifndef M_PI
#define M_PI 3.14159265358979323846 ///< Pi Value
#endif /* M_PI */
//#include "dspFilter.h"
extern int Float2QFormatConvert( _FILT_COEF param_tFiltCoef, _Q_FORMAT *param_tFiltQForm,
unsigned int fixNum, unsigned int fracNum );
extern void PrintCoef( int mode, _FILT_COEF param_tFiltCoef, _Q_FORMAT param_tFiltQForm,
float valFreq, float valQ, float valGain );
extern int QFormatConvert( float param_filtCoef, int *param_filtQForm, unsigned int fracNum );
#endif /* DSPQFORMATCONVERT_H_ */
<file_sep>var searchData=
[
['a1',['a1',['../dd/db8/struct_____f_i_l_t___c_o_e_f.html#a0a8a4d4cc79f407d2123b75794233cd8',1,'__FILT_COEF::a1()'],['../de/d4e/struct_____q___f_o_r_m_a_t.html#a3bdaae0a32b731c7aadb02b96334e254',1,'__Q_FORMAT::a1()']]],
['a2',['a2',['../dd/db8/struct_____f_i_l_t___c_o_e_f.html#aeb8fe784561c14b524f8d8527c723b2c',1,'__FILT_COEF::a2()'],['../de/d4e/struct_____q___f_o_r_m_a_t.html#adf82b4d95ce195a01c00f0c2f4e043f5',1,'__Q_FORMAT::a2()']]]
];
<file_sep>var searchData=
[
['sample_5frate',['SAMPLE_RATE',['../d9/d5e/dsp_q_format_convert_8h.html#a4b76a0c2859cfd819a343a780070ee2b',1,'dspQFormatConvert.h']]]
];
<file_sep>var annotated =
[
[ "__FILT_COEF", "dd/db8/struct_____f_i_l_t___c_o_e_f.html", "dd/db8/struct_____f_i_l_t___c_o_e_f" ],
[ "__Q_FORMAT", "de/d4e/struct_____q___f_o_r_m_a_t.html", "de/d4e/struct_____q___f_o_r_m_a_t" ]
];<file_sep>/**
* dspFilter.h
*
* Created on: 2015. 6. 10.
* Author: i04055dt
*/
#ifndef DSPFILTER_H_
#define DSPFILTER_H_
/**
* @brief Floating point Filter Coefficient Structures
* @remarks All Member type is float(floating Point)
*/
typedef struct __FILT_COEF
{
float b0;
float b1;
float b2;
float a1;
float a2;
} _FILT_COEF;
/**
* @brief Q Formatted Filter Coefficient Sturctures
* @remarks All Member type is int(integer)
*/
typedef struct __Q_FORMAT
{
int b0;
int b1;
int b2;
int a1;
int a2;
} _Q_FORMAT;
void ShelvingFilter2ndLow( _FILT_COEF *param_FiltCoef, float param_freq,
float param_qValue, float param_gainDb );
void ShelvingFilter2ndHigh( _FILT_COEF *param_FiltCoef, float param_freq,
float param_qValue, float param_gainDb );
void PeakingFilter( _FILT_COEF *param_FiltCoef, float param_freq, float param_qValue, float param_gainDbc );
void PeqFilter( _FILT_COEF *param_FiltCoef, float param_freq, float param_qValue, float param_gainDb );
void ShelvingFilter1stLow( _FILT_COEF *param_FiltCoef, float param_freq,
float param_qValue, float param_gainDb );
#endif /* DSPFILTER_H_ */
<file_sep>var files =
[
[ "dspFilter.c", "d2/d88/dsp_filter_8c.html", "d2/d88/dsp_filter_8c" ],
[ "dspFilter.h", "de/dca/dsp_filter_8h.html", "de/dca/dsp_filter_8h" ],
[ "dspQFormatConvert.c", "d3/d27/dsp_q_format_convert_8c.html", "d3/d27/dsp_q_format_convert_8c" ],
[ "dspQFormatConvert.h", "d9/d5e/dsp_q_format_convert_8h.html", "d9/d5e/dsp_q_format_convert_8h" ],
[ "xmos_HelloWorld.xc", "df/d44/xmos___hello_world_8xc.html", null ]
];<file_sep>/**
* @file dspFilter.c
*
* Created on: 2015. 6. 10.
* Author: i04055dt
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include "dspFilter.h"
extern const float g_twoPi;
extern const float g_fs;
/**
* @brief 2nd Order Low Frequency Shelving Filter Coefficient Calculation Function
*
* @param param_FiltCoef
* @param param_freq
* @param param_qValue
* @param param_gainDb
*/
void ShelvingFilter2ndLow(
_FILT_COEF *param_FiltCoef,
float param_freq,
float param_qValue,
float param_gainDb
)
{
float w0;
float A;
float alpha;
float cosW0;
float b0, b1, b2, a0, a1, a2;
float f0;
float gainDb;
float qValue;
f0 = param_freq;
gainDb = param_gainDb;
qValue = param_qValue;
w0 = (float)g_twoPi * f0 / (float)g_fs;
A = pow(10.0, (gainDb / 40.0));
cosW0 = cos(w0);
alpha = sin(w0)/(2.0 * qValue);
// printf("alpha2 = %f\n", alpha);
b0 = A *((A + 1.0) - ((A - 1.0) * cosW0) + (2.0 * pow(A, 0.5) * alpha));
b1 = 2.0 * A * ((A - 1.0) - ((A + 1.0) * cosW0));
b2 = A *((A + 1.0) - ((A - 1.0) * cosW0) - (2.0 * pow(A, 0.5) *alpha));
a0 = (A + 1.0) + ((A - 1.0) * cosW0) + (2.0 * pow(A, 0.5) * alpha);
a1 = -2.0 * ((A - 1.0) + ((A + 1.0) * cosW0));
a2 = (A + 1.0) + ((A - 1.0) * cosW0) - (2.0 * pow(A, 0.5) * alpha);
// param_FiltCoef->b0 = (b0 * 0.25) / a0;
// param_FiltCoef->b1 = (b1 * 0.25) / a0;
// param_FiltCoef->b2 = (b2 * 0.25) / a0;
param_FiltCoef->b0 = (b0 * 0.0625) / a0;
param_FiltCoef->b1 = (b1 * 0.0625) / a0;
param_FiltCoef->b2 = (b2 * 0.0625) / a0;
param_FiltCoef->a1 = (a1 * (-0.5)) / a0;
param_FiltCoef->a2 = (a2 * (-0.5)) / a0;
}
/**
* @brief 2nd Order High Frequency Shelving Filter Coefficient Calculation
* @param param_FiltCoef
* @param param_freq
* @param param_gainDb
* @param param_qValue
*/
void ShelvingFilter2ndHigh(
_FILT_COEF *param_FiltCoef,
float param_freq,
float param_qValue,
float param_gainDb
)
{
float w0;
float A;
float alpha;
float cosW0;
float b0, b1, b2, a0, a1, a2;
float f0;
float gainDb;
float qValue;
f0 = param_freq;
gainDb = param_gainDb;
qValue = param_qValue;
w0 = (float)g_twoPi * f0 / (float)g_fs;
A = pow(10.0, (gainDb / 40.0));
cosW0 = cos(w0);
alpha = sin(w0)/(2.0 * qValue);
b0 = A * ((A + 1.0) + ((A - 1.0) * cosW0) + (2.0 * pow(A,0.5) * alpha));
b1 = -2.0 * A * ((A - 1.0) + ((A + 1.0) * cosW0));
b2 = A * ((A + 1.0) + ((A - 1.0) * cosW0) - (2.0 * pow(A,0.5) * alpha));
a0 = (A + 1.0) - ((A - 1.0) * cosW0) + (2.0 * pow(A,0.5) * alpha);
a1 = 2.0 * ((A - 1.0) - ((A + 1.0) * cosW0));
a2 = (A + 1.0) - ((A - 1.0) * cosW0) - (2.0 * pow(A,0.5) * alpha);
// param_FiltCoef->b0 = (b0 * 0.25) / a0;
// param_FiltCoef->b1 = (b1 * 0.25) / a0;
// param_FiltCoef->b2 = (b2 * 0.25) / a0;
param_FiltCoef->b0 = (b0 * 0.0625) / a0;
param_FiltCoef->b1 = (b1 * 0.0625) / a0;
param_FiltCoef->b2 = (b2 * 0.0625) / a0;
param_FiltCoef->a1 = (a1 * (-0.5)) / a0;
param_FiltCoef->a2 = (a2 * (-0.5)) / a0;
}
/**
* 2nd Order Peaking Filter Coefficient Calculation Function
* @param param_FiltCoef
* @param param_freq
* @param param_qValue
* @param param_gainDb
*/
void PeakingFilter(
_FILT_COEF *param_FiltCoef,
float param_freq,
float param_qValue,
float param_gainDb
)
{
float w0;
float A;
float alpha;
float cosW0;
float b0, b1, b2, a0, a1, a2;
float f0;
float gainDb;
float qValue;
f0 = param_freq;
gainDb = param_gainDb;
qValue = param_qValue;
w0 = (float)g_twoPi * f0 / (float)g_fs;
A = pow(10.0, (gainDb / 40.0));
cosW0 = cos(w0);
alpha = sin(w0) / (2.0 * qValue);
b0 = 1.0 + alpha * A;
b1 = -2.0 * cos(w0);
b2 = 1.0 - alpha * A;
a0 = 1 + alpha / A;
a1 = -2.0 * cos(w0);
a2 = 1.0 - alpha / A;
// param_FiltCoef->b0 = (b0 * 0.25) / a0;
// param_FiltCoef->b1 = (b1 * 0.25) / a0;
// param_FiltCoef->b2 = (b2 * 0.25) / a0;
param_FiltCoef->b0 = (b0 * 0.0625) / a0;
param_FiltCoef->b1 = (b1 * 0.0625) / a0;
param_FiltCoef->b2 = (b2 * 0.0625) / a0;
param_FiltCoef->a1 = (a1 * (-0.5)) / a0;
param_FiltCoef->a2 = (a2 * (-0.5)) / a0;
}
/**
* 2nd Order Biquad PEQ Filter Coefficient Calculation Function
* @param param_FiltCoef
* @param param_freq
* @param param_gainDb
* @param param_qValue
*/
void PeqFilter(
_FILT_COEF *param_FiltCoef,
float param_freq,
float param_qValue,
float param_gainDb
)
{
float wc, w3;
float Qb;
float gainLin;
float sinWc64, cosWc;
float den, opa2, gtoma2;
float b0, b1, b2, a1, a2;
float f0;
float gainDb;
float qValue;
f0 = param_freq;
gainDb = param_gainDb;
qValue = param_qValue;
wc = (float)g_twoPi * f0 / (float)g_fs;
sinWc64 = sin(wc) / 64.0;
cosWc = cos(wc);
w3 = wc * (sqrt((qValue / 32.0 * qValue / 32.0 + 1.0 / 4096.0)) - 1.0 / 64.0) / (qValue /32.0);
Qb = sin(w3) * sinWc64 / (cos(w3) - cosWc);
gainLin = pow(10.0, gainDb/20.0);
if (gainDb < 0.0)
{
Qb *= gainLin;
}
den = (Qb + sinWc64);
a1 = (Qb * cosWc) / (den);
a2 = (-Qb + sinWc64) / (den * 2.0);
// opa2 = (1.0 / 2.0 - a2);
// gtoma2 = gainLin * (1.0 / 2.0 + a2);
// b0 = (opa2 + gtoma2) / 4.0;
// b1 = -a1 / 2.0;
// b2 = (opa2 - gtoma2) / 4.0;
opa2 = (0.5 - a2);
gtoma2 = gainLin * (0.5 + a2);
b0 = (opa2 + gtoma2) * 0.25;
b1 = -a1 * 0.5;
b2 = (opa2 - gtoma2) * 0.25;
// param_FiltCoef->b0 = b0;
// param_FiltCoef->b1 = b1;
// param_FiltCoef->b2 = b2;
param_FiltCoef->b0 = b0 * 0.25;
param_FiltCoef->b1 = b1 * 0.25;
param_FiltCoef->b2 = b2 * 0.25;
param_FiltCoef->a1 = a1;
param_FiltCoef->a2 = a2;
}
/**
* 1st Order Low Frequency Shelving Filter Coefficient Calculation Function
* @param param_FiltCoef
* @param param_freq
* @param param_gainDb
* @param param_qValue
*/
void ShelvingFilter1stLow(
_FILT_COEF *param_FiltCoef,
float param_freq,
float param_qValue,
float param_gainDb
)
{
float w0;
float A;
float alpha;
float cosW0;
float b0, b1, b2, a0, a1, a2;
float ggg, aaa;
float tanWc;
float f0;
float gainDb;
float qValue;
f0 = param_freq;
gainDb = param_gainDb;
qValue = param_qValue;
w0 = (float)g_twoPi * f0 / (float)g_fs;
A = pow(10.0, (gainDb / 40.0));
cosW0 = cos(w0);
alpha = sin(w0)/(2.0 * qValue);
a0 = (A + 1.0) + ((A - 1.0) * cosW0) + (2.0 * pow(A, 0.5) * alpha);
tanWc = tan(w0 * 0.5);
/* Compute coefficients */
ggg = pow(10, gainDb / 20);
if (ggg < 1)
{
tanWc = tanWc / ggg;
}
aaa = (tanWc - 1) / (tanWc + 1);
/* Compute low shelf coefficients a_1/2, b_0/4 and b_1/4 */
a1 = aaa;
a2 = 0.0;
b0 = (((1 + aaa) / 2) * (ggg / 4) + (1 - aaa) / 8) * 4;
b1 = (((1 + aaa) / 2) * (ggg / 4) - (1 - aaa) / 8) * 4;
b2 = 0.0;
/* Scale coefficients to match DSP implemention */
b0 = (b0 * 0.25) / a0;
b1 = (b1 * 0.25) / a0;
b2 = (b2 * 0.25) / a0;
a1 = (a1 * (-0.5)) / a0;
a2 = (a2 * (-0.5)) / a0;
param_FiltCoef->b0 = b0;
param_FiltCoef->b1 = b1;
param_FiltCoef->b2 = b2;
param_FiltCoef->a1 = a1;
param_FiltCoef->a2 = a2;
}
<file_sep>var dsp_filter_8c =
[
[ "PeakingFilter", "d2/d88/dsp_filter_8c.html#a254ee3f6745efa5920e091b8a8ef666f", null ],
[ "PeqFilter", "d2/d88/dsp_filter_8c.html#a96bf6847c0943b24c9809daa7fc081a9", null ],
[ "ShelvingFilter1stLow", "d2/d88/dsp_filter_8c.html#ae890b45a0c6b9efc1dd5bf146312f21a", null ],
[ "ShelvingFilter2ndHigh", "d2/d88/dsp_filter_8c.html#a15386878cb5f5b907f6d2a31f6b275f4", null ],
[ "ShelvingFilter2ndLow", "d2/d88/dsp_filter_8c.html#a8d5e02bc4a738671a9b7841ea6d12e2c", null ],
[ "g_fs", "d2/d88/dsp_filter_8c.html#a171eefc2107c2a6148dd6b050aa629ea", null ],
[ "g_twoPi", "d2/d88/dsp_filter_8c.html#ada0744b21abba6961e3e55749e1eee1f", null ]
];<file_sep>var searchData=
[
['_5ffilt_5fcoef',['_FILT_COEF',['../de/dca/dsp_filter_8h.html#aeceef54faa278512cd3b46e47d71de18',1,'dspFilter.h']]],
['_5fq_5fformat',['_Q_FORMAT',['../de/dca/dsp_filter_8h.html#ad441c1c66a421036640642bf5f66b7fa',1,'dspFilter.h']]]
];
<file_sep>var struct_____f_i_l_t___c_o_e_f =
[
[ "a1", "dd/db8/struct_____f_i_l_t___c_o_e_f.html#a0a8a4d4cc79f407d2123b75794233cd8", null ],
[ "a2", "dd/db8/struct_____f_i_l_t___c_o_e_f.html#aeb8fe784561c14b524f8d8527c723b2c", null ],
[ "b0", "dd/db8/struct_____f_i_l_t___c_o_e_f.html#ab7a4e5aa04e332119f7ed50b2fdf55bc", null ],
[ "b1", "dd/db8/struct_____f_i_l_t___c_o_e_f.html#a6b091370c641032308e29256f8ed3ea1", null ],
[ "b2", "dd/db8/struct_____f_i_l_t___c_o_e_f.html#a5d1f0db7785187119dbdd01681d9d230", null ]
];<file_sep>var dsp_q_format_convert_8h =
[
[ "M_LN2", "d9/d5e/dsp_q_format_convert_8h.html#a92428112a5d24721208748774a4f23e6", null ],
[ "M_PI", "d9/d5e/dsp_q_format_convert_8h.html#ae71449b1cc6e6250b91f539153a7a0d3", null ],
[ "SAMPLE_RATE", "d9/d5e/dsp_q_format_convert_8h.html#a4b76a0c2859cfd819a343a780070ee2b", null ],
[ "Float2QFormatConvert", "d9/d5e/dsp_q_format_convert_8h.html#a646289654152ae05600606013b945c86", null ],
[ "PrintCoef", "d9/d5e/dsp_q_format_convert_8h.html#a5f03ce0a0de11a675df423d641fe58b2", null ],
[ "QFormatConvert", "d9/d5e/dsp_q_format_convert_8h.html#a16501f69f57199c5dc647b0fdb9f00bb", null ]
];<file_sep>var searchData=
[
['dspfilter_2ec',['dspFilter.c',['../d2/d88/dsp_filter_8c.html',1,'']]],
['dspfilter_2eh',['dspFilter.h',['../de/dca/dsp_filter_8h.html',1,'']]],
['dspqformatconvert_2ec',['dspQFormatConvert.c',['../d3/d27/dsp_q_format_convert_8c.html',1,'']]],
['dspqformatconvert_2eh',['dspQFormatConvert.h',['../d9/d5e/dsp_q_format_convert_8h.html',1,'']]]
];
<file_sep>var dsp_q_format_convert_8c =
[
[ "Float2QFormatConvert", "d3/d27/dsp_q_format_convert_8c.html#a646289654152ae05600606013b945c86", null ],
[ "PrintCoef", "d3/d27/dsp_q_format_convert_8c.html#a5f03ce0a0de11a675df423d641fe58b2", null ],
[ "QForm2FloatConverter", "d3/d27/dsp_q_format_convert_8c.html#a81334f577bbbfde46b471108f5a648d4", null ],
[ "QFormat2FloatConvert", "d3/d27/dsp_q_format_convert_8c.html#afdb499fad2e27d0ac12c8ff37876f234", null ],
[ "QFormatConvert", "d3/d27/dsp_q_format_convert_8c.html#a16501f69f57199c5dc647b0fdb9f00bb", null ],
[ "g_fs", "d3/d27/dsp_q_format_convert_8c.html#a171eefc2107c2a6148dd6b050aa629ea", null ],
[ "g_twoPi", "d3/d27/dsp_q_format_convert_8c.html#ada0744b21abba6961e3e55749e1eee1f", null ],
[ "str1stLoShelfFilter", "d3/d27/dsp_q_format_convert_8c.html#a926c3674b0a07cbef1693833c86098a6", null ],
[ "str2ndHiShelfFilter", "d3/d27/dsp_q_format_convert_8c.html#addaa4776cfc6bc81f7fd3bdbc53c48fb", null ],
[ "str2ndLoShelfFilter", "d3/d27/dsp_q_format_convert_8c.html#a3d43538ea1ab2e5c29aee81a46293698", null ],
[ "strPeakFilter", "d3/d27/dsp_q_format_convert_8c.html#af1412449d6875a0a2a272e2affa062a9", null ],
[ "strPeqFilter", "d3/d27/dsp_q_format_convert_8c.html#a82f69c2969fbcf32622f497a3c348f61", null ]
];<file_sep>/**
* @file dspQFormatConvert.c
*
* @date 2015. 6. 10.
* @author i04055dt
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "dspFilter.h"
#include "dspQFormatConvert.h"
const float g_twoPi = 6.283185307179586476925286766559;
const float g_fs = SAMPLE_RATE;
const unsigned char str2ndLoShelfFilter[] = "2nd Order Low Shelf Filter:\0";
const unsigned char str2ndHiShelfFilter[] = "2nd Order High Shelf Filter:\0";
const unsigned char strPeakFilter[] = "Peaking Filter:\0";
const unsigned char strPeqFilter[] = "Parametric EQ Filter:\0";
const unsigned char str1stLoShelfFilter[] = "1st Order Low Shelf Filter:\0";
/**
* @brief Floating Point Filter Coefficient convert to Fixed Point Q Format Qm.n\n
* - Input/Output is the Structure of Filter Coefficients & Q Format Coefficients
*
* @param param_tFiltCoef Src: Floating Point Filter Coefficient
* @param param_tFiltQForm Des: Q Format Integer Filter Coefficient
* @param fixNum Q Format Fixed Bit Number
* @param fracNum Q Format Fraction Bit Number
* @return No Error: 0, Error: -1
*/
int Float2QFormatConvert(
_FILT_COEF param_tFiltCoef,
_Q_FORMAT *param_tFiltQForm,
unsigned int fixNum,
unsigned int fracNum
)
{
int ret = 0;
_FILT_COEF tFiltCoef;
_Q_FORMAT tFiltQForm;
tFiltCoef = param_tFiltCoef;
if (tFiltCoef.b0 < 0.0) tFiltQForm.b0 = ~((int)(tFiltCoef.b0 * (pow(-2, fracNum) - 1))) + 1;
else tFiltQForm.b0 = (int)(tFiltCoef.b0 * (pow(2, fracNum) - 1));
if (tFiltCoef.b1 < 0.0) tFiltQForm.b1 = ~((int)(tFiltCoef.b1 * (pow(-2, fracNum) - 1))) + 1;
else tFiltQForm.b1 = (int)(tFiltCoef.b1 * (pow(2, fracNum) - 1));
if (tFiltCoef.b2 < 0.0) tFiltQForm.b2 = ~((int)(tFiltCoef.b2 * (pow(-2, fracNum) - 1))) + 1;
else tFiltQForm.b2 = (int)(tFiltCoef.b2 * (pow(2, fracNum) -1));
if (tFiltCoef.a1 < 0.0) tFiltQForm.a1 = ~((int)(tFiltCoef.a1 * (pow(-2, fracNum) - 1))) + 1;
else tFiltQForm.a1 = (int)(tFiltCoef.a1 * (pow(2, fracNum) - 1));
if (tFiltCoef.a2 < 0.0) tFiltQForm.a2 = ~((int)(tFiltCoef.a2 * (pow(-2, fracNum) - 1))) + 1;
else tFiltQForm.a2 = (int)(tFiltCoef.a2 * (pow(2, fracNum) - 1));
*param_tFiltQForm = tFiltQForm;
return ret;
}
/**
* @brief
* @param param_filtQForm Src: Q Format Integer Filter Coefficient
* @param param_filtCoef Des: Floating Point Filter Coefficient
* @param fixNum Q Format Fixed Bit Number
* @param fracNum Q Format Fraction Bit Number
* @return
*/
int QFormat2FloatConvert(
_Q_FORMAT param_filtQForm,
_FILT_COEF *param_filtCoef,
unsigned int fixNum,
unsigned int fracNum
)
{
int ret = 0;
return ret;
}
/**
* Print Filter Coefficient Floating Value And Q1.31 Format
* @param mode EQ Filter Mode\n
* - 0: Low Pass Shelving Filter\n
* - 1: High Pass Shelving Filter\n
* - 2: Peak Filter\n
* - 3: Parametric EQ Filter\n
* - 4: 1st order Low Pass Shelving Filter
* @param param_tFiltCoef
* @param param_tFiltQForm
* @param valFreq
* @param valQ
* @param valGain
*/
void PrintCoef(
int mode,
_FILT_COEF param_tFiltCoef,
_Q_FORMAT param_tFiltQForm,
float valFreq,
float valQ,
float valGain
)
{
unsigned char *str;
switch (mode)
{
case 0:
str = (unsigned char*)str2ndLoShelfFilter;
break;
case 1:
str = (unsigned char*)str2ndHiShelfFilter;
break;
case 2:
str = (unsigned char*)strPeakFilter;
break;
case 3:
str = (unsigned char*)strPeqFilter;
break;
case 4:
str = (unsigned char*)str1stLoShelfFilter;
break;
default:
break;
}
printf("\n");
printf("%s %f Hz, Q: %f, %f dB\n", str, valFreq, valQ, valGain);
// printf("b0 = %f\n", param_tFiltCoef.b0);
// printf("b1 = %f\n", param_tFiltCoef.b1);
// printf("b2 = %f\n", param_tFiltCoef.b2);
// printf("a1 = %f\n", param_tFiltCoef.a1);
// printf("a2 = %f\n", param_tFiltCoef.a2);
//
// printf("\n");
//
// printf("b0 = 0x%08x\n", param_tFiltQForm.b0);
// printf("b1 = 0x%08x\n", param_tFiltQForm.b1);
// printf("b2 = 0x%08x\n", param_tFiltQForm.b2);
// printf("a1 = 0x%08x\n", param_tFiltQForm.a1);
// printf("a2 = 0x%08x\n", param_tFiltQForm.a2);
printf("a1 = %f\n", param_tFiltCoef.a1);
printf("b2 = %f\n", param_tFiltCoef.b2);
printf("b0 = %f\n", param_tFiltCoef.b0);
printf("b1 = %f\n", param_tFiltCoef.b1);
printf("a2 = %f\n", param_tFiltCoef.a2);
printf("\n");
printf("a1 = 0x%08x\n", param_tFiltQForm.a1);
printf("b2 = 0x%08x\n", param_tFiltQForm.b2);
printf("b0 = 0x%08x\n", param_tFiltQForm.b0);
printf("b1 = 0x%08x\n", param_tFiltQForm.b1);
printf("a2 = 0x%08x\n", param_tFiltQForm.a2);
// scanf("");
}
/**
* @brief Q Format Converter Function
* @param param_filtCoef Src: Floating Point Filter Coefficient
* @param param_filtQForm Des: Q Format Integer Filter Coefficient
* @param fracNum Q Format Fraction Bit Number (n number of Qm.n format)
* @return Error -1, Normal: 0
*/
int QFormatConvert(
float param_filtCoef,
int *param_filtQForm,
unsigned int fracNum
)
{
int ret = 0;
float filtCoef;
int *filtQForm = param_filtQForm;
filtCoef = param_filtCoef;
/* Negative Filter Coefficient */
if (filtCoef < 0.0)
{
filtQForm = (int*)(~((int)(filtCoef * (pow(-2, fracNum) - 1))) + 1);
}
/* Positive Filter Coefficient */
else
{
filtQForm = (int*)((int)(filtCoef * (pow(2, fracNum) - 1)));
}
return ret;
}
/**
*
* @param param_filtQForm
* @param param_filtCoef
* @param fracNum
* @return Error
*/
int QForm2FloatConverter(
int param_filtQForm,
float *param_filtCoef,
unsigned int fracNum
)
{
return 0;
}
|
4756fa6c1a789d87b0831372e4409ba2cece7b06
|
[
"JavaScript",
"C"
] | 15
|
JavaScript
|
sunnyside74/xmos_HelloWorld
|
4315b6099442950011a5e0978d3065602d25788d
|
1bcb8a4395be4e4e6ac368066366c5fa01148ab2
|
refs/heads/master
|
<repo_name>MarketcheckCarsInc/marketcheck-api-sdk-php<file_sep>/test/Api/CRMApiTest.php
<?php
/**
* CRMApiTest
* PHP version 5
*
* @category Class
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Marketcheck Cars API
*
* <b>Access the New, Used and Certified cars inventories for all Car Dealers in US.</b> <br/>The data is sourced from online listings by over 44,000 Car dealers in US. At any time, there are about 6.2M searchable listings (about 1.9M unique VINs) for Used & Certified cars and about 6.6M (about 3.9M unique VINs) New Car listings from all over US. We use this API at the back for our website <a href='https://www.marketcheck.com' target='_blank'>www.marketcheck.com</a> and our Android and iOS mobile apps too.<br/><h5> Few useful links : </h5><ul><li>A quick view of the API and the use cases is depicated <a href='https://portals.marketcheck.com/mcapi/' target='_blank'>here</a></li><li>The Postman collection with various usages of the API is shared here https://www.getpostman.com/collections/2752684ff636cdd7bac2</li></ul>
*
* OpenAPI spec version: 1.0.3
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.0-SNAPSHOT
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Please update the test case below to test the endpoint.
*/
require __DIR__.'/../../vendor/autoload.php';
require __DIR__.'/../../lib/Api/CRMApi.php';
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
use \marketcheck\api\sdk\Configuration;
use \marketcheck\api\sdk\ApiException;
use \marketcheck\api\sdk\ObjectSerializer;
/**
* CRMApiTest Class Doc Comment
*
* @category Class
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class CRMApiTest extends \PHPUnit_Framework_TestCase
{
private $api_key = "your api key";
private $vin = "1N4AA5AP8EC477345";
private $sale_date = array(20180305,20180606);
/**
* Setup before running any test cases
*/
public static function setUpBeforeClass()
{
}
/**
* Setup before running each test case
*/
public function setUp()
{
}
/**
* Clean up after running each test case
*/
public function tearDown()
{
}
/**
* Clean up after running all test cases
*/
public static function tearDownAfterClass()
{
}
/**
* Test case for crmCheck
*
* CRM check of a particular vin.
*
*/
public function testCrmCheck()
{
$apiInstance = new marketcheck\api\sdk\Api\CRMApi(new GuzzleHttp\Client());
echo "\nShould return true for crm check as both dates match";
try
{
$result = $apiInstance->crmCheck($this->vin, $this->sale_date[0], $this->api_key);
$this->assertEquals(true, $result["for_sale"]);
print_r("\n/v1/crm_check/$this->vin?api_key={{api_key}}&sale_date=".$this->sale_date[0].": endpoint working fine");
} catch (Exception $e) {
$this->fail($e->getMessage());
}
echo "\nShould return false for crm check";
try
{
$result = $apiInstance->crmCheck($this->vin, $this->sale_date[1], $this->api_key);
$this->assertEquals(false, $result["for_sale"]);
print_r("\n/v1/crm_check/$this->vin?api_key={{api_key}}&sale_date=".$this->sale_date[1].": endpoint working fine");
} catch (Exception $e) {
$this->fail($e->getMessage());
}
}
}
<file_sep>/lib/Model/DepreciationStats.php
<?php
/**
* DepreciationStats
*
* PHP version 5
*
* @category Class
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Marketcheck Cars API
*
* <b>Access the New, Used and Certified cars inventories for all Car Dealers in US.</b> <br/>The data is sourced from online listings by over 44,000 Car dealers in US. At any time, there are about 6.2M searchable listings (about 1.9M unique VINs) for Used & Certified cars and about 6.6M (about 3.9M unique VINs) New Car listings from all over US. We use this API at the back for our website <a href='https://www.marketcheck.com' target='_blank'>www.marketcheck.com</a> and our Android and iOS mobile apps too.<br/><h5> Few useful links : </h5><ul><li>A quick view of the API and the use cases is depicated <a href='https://portals.marketcheck.com/mcapi/' target='_blank'>here</a></li><li>The Postman collection with various usages of the API is shared here https://www.getpostman.com/collections/2752684ff636cdd7bac2</li></ul>
*
* OpenAPI spec version: 1.0.3
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.0-SNAPSHOT
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
namespace marketcheck\api\sdk\Model;
use \ArrayAccess;
use \marketcheck\api\sdk\ObjectSerializer;
/**
* DepreciationStats Class Doc Comment
*
* @category Class
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class DepreciationStats implements ModelInterface, ArrayAccess
{
const DISCRIMINATOR = null;
/**
* The original name of the model.
*
* @var string
*/
protected static $swaggerModelName = 'DepreciationStats';
/**
* Array of property to type mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerTypes = [
'name' => 'string',
'current_value' => 'float',
'one_year_from_now' => 'float',
'one_year_from_now_percent' => 'float',
'two_year_from_now' => 'float',
'two_year_from_now_percent' => 'float',
'five_year_from_now' => 'float',
'five_year_from_now_percent' => 'float'
];
/**
* Array of property to format mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerFormats = [
'name' => null,
'current_value' => null,
'one_year_from_now' => null,
'one_year_from_now_percent' => null,
'two_year_from_now' => null,
'two_year_from_now_percent' => null,
'five_year_from_now' => null,
'five_year_from_now_percent' => null
];
/**
* Array of property to type mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerTypes()
{
return self::$swaggerTypes;
}
/**
* Array of property to format mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerFormats()
{
return self::$swaggerFormats;
}
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @var string[]
*/
protected static $attributeMap = [
'name' => 'name',
'current_value' => 'current_value',
'one_year_from_now' => 'one_year_from_now',
'one_year_from_now_percent' => 'one_year_from_now_percent',
'two_year_from_now' => 'two_year_from_now',
'two_year_from_now_percent' => 'two_year_from_now_percent',
'five_year_from_now' => 'five_year_from_now',
'five_year_from_now_percent' => 'five_year_from_now_percent'
];
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @var string[]
*/
protected static $setters = [
'name' => 'setName',
'current_value' => 'setCurrentValue',
'one_year_from_now' => 'setOneYearFromNow',
'one_year_from_now_percent' => 'setOneYearFromNowPercent',
'two_year_from_now' => 'setTwoYearFromNow',
'two_year_from_now_percent' => 'setTwoYearFromNowPercent',
'five_year_from_now' => 'setFiveYearFromNow',
'five_year_from_now_percent' => 'setFiveYearFromNowPercent'
];
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @var string[]
*/
protected static $getters = [
'name' => 'getName',
'current_value' => 'getCurrentValue',
'one_year_from_now' => 'getOneYearFromNow',
'one_year_from_now_percent' => 'getOneYearFromNowPercent',
'two_year_from_now' => 'getTwoYearFromNow',
'two_year_from_now_percent' => 'getTwoYearFromNowPercent',
'five_year_from_now' => 'getFiveYearFromNow',
'five_year_from_now_percent' => 'getFiveYearFromNowPercent'
];
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @return array
*/
public static function attributeMap()
{
return self::$attributeMap;
}
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @return array
*/
public static function setters()
{
return self::$setters;
}
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @return array
*/
public static function getters()
{
return self::$getters;
}
/**
* The original name of the model.
*
* @return string
*/
public function getModelName()
{
return self::$swaggerModelName;
}
/**
* Associative array for storing property values
*
* @var mixed[]
*/
protected $container = [];
/**
* Constructor
*
* @param mixed[] $data Associated array of property values
* initializing the model
*/
public function __construct(array $data = null)
{
$this->container['name'] = isset($data['name']) ? $data['name'] : null;
$this->container['current_value'] = isset($data['current_value']) ? $data['current_value'] : null;
$this->container['one_year_from_now'] = isset($data['one_year_from_now']) ? $data['one_year_from_now'] : null;
$this->container['one_year_from_now_percent'] = isset($data['one_year_from_now_percent']) ? $data['one_year_from_now_percent'] : null;
$this->container['two_year_from_now'] = isset($data['two_year_from_now']) ? $data['two_year_from_now'] : null;
$this->container['two_year_from_now_percent'] = isset($data['two_year_from_now_percent']) ? $data['two_year_from_now_percent'] : null;
$this->container['five_year_from_now'] = isset($data['five_year_from_now']) ? $data['five_year_from_now'] : null;
$this->container['five_year_from_now_percent'] = isset($data['five_year_from_now_percent']) ? $data['five_year_from_now_percent'] : null;
}
/**
* Show all the invalid properties with reasons.
*
* @return array invalid properties with reasons
*/
public function listInvalidProperties()
{
$invalidProperties = [];
return $invalidProperties;
}
/**
* Validate all the properties in the model
* return true if all passed
*
* @return bool True if all properties are valid
*/
public function valid()
{
return count($this->listInvalidProperties()) === 0;
}
/**
* Gets name
*
* @return string
*/
public function getName()
{
return $this->container['name'];
}
/**
* Sets name
*
* @param string $name ymm_comb_name
*
* @return $this
*/
public function setName($name)
{
$this->container['name'] = $name;
return $this;
}
/**
* Gets current_value
*
* @return float
*/
public function getCurrentValue()
{
return $this->container['current_value'];
}
/**
* Sets current_value
*
* @param float $current_value Price of year make model combination
*
* @return $this
*/
public function setCurrentValue($current_value)
{
$this->container['current_value'] = $current_value;
return $this;
}
/**
* Gets one_year_from_now
*
* @return float
*/
public function getOneYearFromNow()
{
return $this->container['one_year_from_now'];
}
/**
* Sets one_year_from_now
*
* @param float $one_year_from_now price after one year from now
*
* @return $this
*/
public function setOneYearFromNow($one_year_from_now)
{
$this->container['one_year_from_now'] = $one_year_from_now;
return $this;
}
/**
* Gets one_year_from_now_percent
*
* @return float
*/
public function getOneYearFromNowPercent()
{
return $this->container['one_year_from_now_percent'];
}
/**
* Sets one_year_from_now_percent
*
* @param float $one_year_from_now_percent price depreciation percent after one year from now
*
* @return $this
*/
public function setOneYearFromNowPercent($one_year_from_now_percent)
{
$this->container['one_year_from_now_percent'] = $one_year_from_now_percent;
return $this;
}
/**
* Gets two_year_from_now
*
* @return float
*/
public function getTwoYearFromNow()
{
return $this->container['two_year_from_now'];
}
/**
* Sets two_year_from_now
*
* @param float $two_year_from_now price after two year from now
*
* @return $this
*/
public function setTwoYearFromNow($two_year_from_now)
{
$this->container['two_year_from_now'] = $two_year_from_now;
return $this;
}
/**
* Gets two_year_from_now_percent
*
* @return float
*/
public function getTwoYearFromNowPercent()
{
return $this->container['two_year_from_now_percent'];
}
/**
* Sets two_year_from_now_percent
*
* @param float $two_year_from_now_percent price depreciation percent after two year from now
*
* @return $this
*/
public function setTwoYearFromNowPercent($two_year_from_now_percent)
{
$this->container['two_year_from_now_percent'] = $two_year_from_now_percent;
return $this;
}
/**
* Gets five_year_from_now
*
* @return float
*/
public function getFiveYearFromNow()
{
return $this->container['five_year_from_now'];
}
/**
* Sets five_year_from_now
*
* @param float $five_year_from_now price after five year from now
*
* @return $this
*/
public function setFiveYearFromNow($five_year_from_now)
{
$this->container['five_year_from_now'] = $five_year_from_now;
return $this;
}
/**
* Gets five_year_from_now_percent
*
* @return float
*/
public function getFiveYearFromNowPercent()
{
return $this->container['five_year_from_now_percent'];
}
/**
* Sets five_year_from_now_percent
*
* @param float $five_year_from_now_percent price depreciation percent after five year from now
*
* @return $this
*/
public function setFiveYearFromNowPercent($five_year_from_now_percent)
{
$this->container['five_year_from_now_percent'] = $five_year_from_now_percent;
return $this;
}
/**
* Returns true if offset exists. False otherwise.
*
* @param integer $offset Offset
*
* @return boolean
*/
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
/**
* Gets offset.
*
* @param integer $offset Offset
*
* @return mixed
*/
public function offsetGet($offset)
{
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
/**
* Sets value based on offset.
*
* @param integer $offset Offset
* @param mixed $value Value to be set
*
* @return void
*/
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
/**
* Unsets offset.
*
* @param integer $offset Offset
*
* @return void
*/
public function offsetUnset($offset)
{
unset($this->container[$offset]);
}
/**
* Gets the string presentation of the object
*
* @return string
*/
public function __toString()
{
if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
return json_encode(
ObjectSerializer::sanitizeForSerialization($this),
JSON_PRETTY_PRINT
);
}
return json_encode(ObjectSerializer::sanitizeForSerialization($this));
}
}
<file_sep>/docs/Api/MarketApi.md
# marketcheck\api\sdk\MarketApi
All URIs are relative to *https://marketcheck-prod.apigee.net/v1*
Method | HTTP request | Description
------------- | ------------- | -------------
[**getMDS**](MarketApi.md#getMDS) | **GET** /mds | Market Days Supply
[**getSalesCount**](MarketApi.md#getSalesCount) | **GET** /sales | Get sales count by make, model, year, trim or taxonomy vin
# **getMDS**
> \marketcheck\api\sdk\Model\Mds getMDS($vin, $api_key, $exact, $latitude, $longitude, $radius, $debug, $include_sold)
Market Days Supply
Get the basic information on specifications for a car identified by a valid VIN
### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$apiInstance = new marketcheck\api\sdk\Api\MarketApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client()
);
$vin = "vin_example"; // string | VIN to decode
$api_key = "api_key_example"; // string | The API Authentication Key. Mandatory with all API calls.
$exact = false; // bool | Exact parameter
$latitude = 1.2; // double | Latitude component of location
$longitude = 1.2; // double | Longitude component of location
$radius = 56; // int | Radius around the search location
$debug = 0; // int | Debug parameter
$include_sold = false; // bool | To fetch sold vins
try {
$result = $apiInstance->getMDS($vin, $api_key, $exact, $latitude, $longitude, $radius, $debug, $include_sold);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling MarketApi->getMDS: ', $e->getMessage(), PHP_EOL;
}
?>
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**vin** | **string**| VIN to decode |
**api_key** | **string**| The API Authentication Key. Mandatory with all API calls. | [optional]
**exact** | **bool**| Exact parameter | [optional] [default to false]
**latitude** | **double**| Latitude component of location | [optional]
**longitude** | **double**| Longitude component of location | [optional]
**radius** | **int**| Radius around the search location | [optional]
**debug** | **int**| Debug parameter | [optional] [default to 0]
**include_sold** | **bool**| To fetch sold vins | [optional] [default to false]
### Return type
[**\marketcheck\api\sdk\Model\Mds**](../Model/Mds.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)
# **getSalesCount**
> \marketcheck\api\sdk\Model\Sales getSalesCount($api_key, $car_type, $make, $mm, $ymm, $ymmt, $taxonomy_vin, $state, $city_state, $stats)
Get sales count by make, model, year, trim or taxonomy vin
Get a sales count for city, state or national level by make, model, year, trim or taxonomy vin
### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$apiInstance = new marketcheck\api\sdk\Api\MarketApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client()
);
$api_key = "api_key_example"; // string | The API Authentication Key. Mandatory with all API calls.
$car_type = "used"; // string | Inventory type for which sales count is to be searched, default is used
$make = "make_example"; // string | Make for which sales count is to be searched
$mm = "mm_example"; // string | Make-Model for which sales count is to be searched, pipe seperated like mm=ford|f-150
$ymm = "ymm_example"; // string | Year-Make-Model for which sales count is to be searched, pipe seperated like ymm=2015|ford|f-150
$ymmt = "ymmt_example"; // string | Year-Make-Model-Trim for which sales count is to be searched, pipe seperated like ymmt=2015|ford|f-150|platinum
$taxonomy_vin = "taxonomy_vin_example"; // string | taxonomy_vin for which sales count is to be searched
$state = "state_example"; // string | State level sales count
$city_state = "city_state_example"; // string | City level sales count, pipe seperated like city_state=jacksonville|FL
$stats = "stats_example"; // string | Comma separated list of fields to generate stats for. Allowed fields in the list are - price, miles, dom (days on market) OR all
try {
$result = $apiInstance->getSalesCount($api_key, $car_type, $make, $mm, $ymm, $ymmt, $taxonomy_vin, $state, $city_state, $stats);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling MarketApi->getSalesCount: ', $e->getMessage(), PHP_EOL;
}
?>
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**api_key** | **string**| The API Authentication Key. Mandatory with all API calls. | [optional]
**car_type** | **string**| Inventory type for which sales count is to be searched, default is used | [optional] [default to used]
**make** | **string**| Make for which sales count is to be searched | [optional]
**mm** | **string**| Make-Model for which sales count is to be searched, pipe seperated like mm=ford|f-150 | [optional]
**ymm** | **string**| Year-Make-Model for which sales count is to be searched, pipe seperated like ymm=2015|ford|f-150 | [optional]
**ymmt** | **string**| Year-Make-Model-Trim for which sales count is to be searched, pipe seperated like ymmt=2015|ford|f-150|platinum | [optional]
**taxonomy_vin** | **string**| taxonomy_vin for which sales count is to be searched | [optional]
**state** | **string**| State level sales count | [optional]
**city_state** | **string**| City level sales count, pipe seperated like city_state=jacksonville|FL | [optional]
**stats** | **string**| Comma separated list of fields to generate stats for. Allowed fields in the list are - price, miles, dom (days on market) OR all | [optional]
### Return type
[**\marketcheck\api\sdk\Model\Sales**](../Model/Sales.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)
<file_sep>/docs/Api/CRMApi.md
# marketcheck\api\sdk\CRMApi
All URIs are relative to *https://marketcheck-prod.apigee.net/v1*
Method | HTTP request | Description
------------- | ------------- | -------------
[**crmCheck**](CRMApi.md#crmCheck) | **GET** /crm_check/{vin} | CRM check of a particular vin
# **crmCheck**
> \marketcheck\api\sdk\Model\CRMResponse crmCheck($vin, $sale_date, $api_key)
CRM check of a particular vin
Check whether particular vin has had a listing after stipulated date or not
### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$apiInstance = new marketcheck\api\sdk\Api\CRMApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client()
);
$vin = "vin_example"; // string | vin for which CRM check needs to be done
$sale_date = "sale_date_example"; // string | sale date after which listing has appeared or not
$api_key = "api_key_example"; // string | The API Authentication Key. Mandatory with all API calls.
try {
$result = $apiInstance->crmCheck($vin, $sale_date, $api_key);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling CRMApi->crmCheck: ', $e->getMessage(), PHP_EOL;
}
?>
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**vin** | **string**| vin for which CRM check needs to be done |
**sale_date** | **string**| sale date after which listing has appeared or not |
**api_key** | **string**| The API Authentication Key. Mandatory with all API calls. | [optional]
### Return type
[**\marketcheck\api\sdk\Model\CRMResponse**](../Model/CRMResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)
<file_sep>/lib/Model/PopularityItem.php
<?php
/**
* PopularityItem
*
* PHP version 5
*
* @category Class
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Marketcheck Cars API
*
* <b>Access the New, Used and Certified cars inventories for all Car Dealers in US.</b> <br/>The data is sourced from online listings by over 44,000 Car dealers in US. At any time, there are about 6.2M searchable listings (about 1.9M unique VINs) for Used & Certified cars and about 6.6M (about 3.9M unique VINs) New Car listings from all over US. We use this API at the back for our website <a href='https://www.marketcheck.com' target='_blank'>www.marketcheck.com</a> and our Android and iOS mobile apps too.<br/><h5> Few useful links : </h5><ul><li>A quick view of the API and the use cases is depicated <a href='https://portals.marketcheck.com/mcapi/' target='_blank'>here</a></li><li>The Postman collection with various usages of the API is shared here https://www.getpostman.com/collections/2752684ff636cdd7bac2</li></ul>
*
* OpenAPI spec version: 1.0.3
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.0-SNAPSHOT
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
namespace marketcheck\api\sdk\Model;
use \ArrayAccess;
use \marketcheck\api\sdk\ObjectSerializer;
/**
* PopularityItem Class Doc Comment
*
* @category Class
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class PopularityItem implements ModelInterface, ArrayAccess
{
const DISCRIMINATOR = null;
/**
* The original name of the model.
*
* @var string
*/
protected static $swaggerModelName = 'PopularityItem';
/**
* Array of property to type mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerTypes = [
'text' => 'string',
'left' => 'float',
'right' => 'float',
'difference' => 'float',
'thumbs' => 'string',
'delta_percent' => 'float',
'color' => 'string'
];
/**
* Array of property to format mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerFormats = [
'text' => null,
'left' => null,
'right' => null,
'difference' => null,
'thumbs' => null,
'delta_percent' => null,
'color' => null
];
/**
* Array of property to type mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerTypes()
{
return self::$swaggerTypes;
}
/**
* Array of property to format mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerFormats()
{
return self::$swaggerFormats;
}
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @var string[]
*/
protected static $attributeMap = [
'text' => 'text',
'left' => 'left',
'right' => 'right',
'difference' => 'difference',
'thumbs' => 'thumbs',
'delta_percent' => 'delta_percent',
'color' => 'color'
];
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @var string[]
*/
protected static $setters = [
'text' => 'setText',
'left' => 'setLeft',
'right' => 'setRight',
'difference' => 'setDifference',
'thumbs' => 'setThumbs',
'delta_percent' => 'setDeltaPercent',
'color' => 'setColor'
];
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @var string[]
*/
protected static $getters = [
'text' => 'getText',
'left' => 'getLeft',
'right' => 'getRight',
'difference' => 'getDifference',
'thumbs' => 'getThumbs',
'delta_percent' => 'getDeltaPercent',
'color' => 'getColor'
];
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @return array
*/
public static function attributeMap()
{
return self::$attributeMap;
}
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @return array
*/
public static function setters()
{
return self::$setters;
}
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @return array
*/
public static function getters()
{
return self::$getters;
}
/**
* The original name of the model.
*
* @return string
*/
public function getModelName()
{
return self::$swaggerModelName;
}
/**
* Associative array for storing property values
*
* @var mixed[]
*/
protected $container = [];
/**
* Constructor
*
* @param mixed[] $data Associated array of property values
* initializing the model
*/
public function __construct(array $data = null)
{
$this->container['text'] = isset($data['text']) ? $data['text'] : null;
$this->container['left'] = isset($data['left']) ? $data['left'] : null;
$this->container['right'] = isset($data['right']) ? $data['right'] : null;
$this->container['difference'] = isset($data['difference']) ? $data['difference'] : null;
$this->container['thumbs'] = isset($data['thumbs']) ? $data['thumbs'] : null;
$this->container['delta_percent'] = isset($data['delta_percent']) ? $data['delta_percent'] : null;
$this->container['color'] = isset($data['color']) ? $data['color'] : null;
}
/**
* Show all the invalid properties with reasons.
*
* @return array invalid properties with reasons
*/
public function listInvalidProperties()
{
$invalidProperties = [];
return $invalidProperties;
}
/**
* Validate all the properties in the model
* return true if all passed
*
* @return bool True if all properties are valid
*/
public function valid()
{
return count($this->listInvalidProperties()) === 0;
}
/**
* Gets text
*
* @return string
*/
public function getText()
{
return $this->container['text'];
}
/**
* Sets text
*
* @param string $text Description for which popularity should be show eg: 2016 ford F-150 Lariat vs All Other Cars
*
* @return $this
*/
public function setText($text)
{
$this->container['text'] = $text;
return $this;
}
/**
* Gets left
*
* @return float
*/
public function getLeft()
{
return $this->container['left'];
}
/**
* Sets left
*
* @param float $left Left side rating for above description (2016 ford F-150 Lariat)
*
* @return $this
*/
public function setLeft($left)
{
$this->container['left'] = $left;
return $this;
}
/**
* Gets right
*
* @return float
*/
public function getRight()
{
return $this->container['right'];
}
/**
* Sets right
*
* @param float $right Right side rating for above description (All Other Cars)
*
* @return $this
*/
public function setRight($right)
{
$this->container['right'] = $right;
return $this;
}
/**
* Gets difference
*
* @return float
*/
public function getDifference()
{
return $this->container['difference'];
}
/**
* Sets difference
*
* @param float $difference Difference depending upon left and right analysis
*
* @return $this
*/
public function setDifference($difference)
{
$this->container['difference'] = $difference;
return $this;
}
/**
* Gets thumbs
*
* @return string
*/
public function getThumbs()
{
return $this->container['thumbs'];
}
/**
* Sets thumbs
*
* @param string $thumbs Thumbs up/down depending upon left and right analysis numbers
*
* @return $this
*/
public function setThumbs($thumbs)
{
$this->container['thumbs'] = $thumbs;
return $this;
}
/**
* Gets delta_percent
*
* @return float
*/
public function getDeltaPercent()
{
return $this->container['delta_percent'];
}
/**
* Sets delta_percent
*
* @param float $delta_percent Delta percent
*
* @return $this
*/
public function setDeltaPercent($delta_percent)
{
$this->container['delta_percent'] = $delta_percent;
return $this;
}
/**
* Gets color
*
* @return string
*/
public function getColor()
{
return $this->container['color'];
}
/**
* Sets color
*
* @param string $color Color depending upon left and right analysis numbers
*
* @return $this
*/
public function setColor($color)
{
$this->container['color'] = $color;
return $this;
}
/**
* Returns true if offset exists. False otherwise.
*
* @param integer $offset Offset
*
* @return boolean
*/
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
/**
* Gets offset.
*
* @param integer $offset Offset
*
* @return mixed
*/
public function offsetGet($offset)
{
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
/**
* Sets value based on offset.
*
* @param integer $offset Offset
* @param mixed $value Value to be set
*
* @return void
*/
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
/**
* Unsets offset.
*
* @param integer $offset Offset
*
* @return void
*/
public function offsetUnset($offset)
{
unset($this->container[$offset]);
}
/**
* Gets the string presentation of the object
*
* @return string
*/
public function __toString()
{
if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
return json_encode(
ObjectSerializer::sanitizeForSerialization($this),
JSON_PRETTY_PRINT
);
}
return json_encode(ObjectSerializer::sanitizeForSerialization($this));
}
}
<file_sep>/test/Api/HistoryApiTest.php
<?php
/**
* HistoryApiTest
* PHP version 5
*
* @category Class
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Marketcheck Cars API
*
* <b>Access the New, Used and Certified cars inventories for all Car Dealers in US.</b> <br/>The data is sourced from online listings by over 44,000 Car dealers in US. At any time, there are about 6.2M searchable listings (about 1.9M unique VINs) for Used & Certified cars and about 6.6M (about 3.9M unique VINs) New Car listings from all over US. We use this API at the back for our website <a href='https://www.marketcheck.com' target='_blank'>www.marketcheck.com</a> and our Android and iOS mobile apps too.<br/><h5> Few useful links : </h5><ul><li>A quick view of the API and the use cases is depicated <a href='https://portals.marketcheck.com/mcapi/' target='_blank'>here</a></li><li>The Postman collection with various usages of the API is shared here https://www.getpostman.com/collections/2752684ff636cdd7bac2</li></ul>
*
* OpenAPI spec version: 1.0.3
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.0-SNAPSHOT
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Please update the test case below to test the endpoint.
*/
require __DIR__.'/../../vendor/autoload.php';
require __DIR__.'/../../lib/Api/HistoryApi.php';
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
use \marketcheck\api\sdk\Configuration;
use \marketcheck\api\sdk\ApiException;
use \marketcheck\api\sdk\ObjectSerializer;
/**
* HistoryApiTest Class Doc Comment
*
* @category Class
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class HistoryApiTest extends \PHPUnit_Framework_TestCase
{
private $api_key = "Your api key";
private $vin = array("1FTEW1EF9GKE64460","NM0LS7E78G1263750","1FTNE1CM0FKA52494","1FADP3N21FL364871","1FTEW1EG1FFB24493");
private $fields = null;
private $rows = null;
private $page = null;
/**
* Setup before running any test cases
*/
public static function setUpBeforeClass()
{
}
/**
* Setup before running each test case
*/
public function setUp()
{
}
/**
* Clean up after running each test case
*/
public function tearDown()
{
}
/**
* Clean up after running all test cases
*/
public static function tearDownAfterClass()
{
}
/**
* Test case for history
*
* Get a cars online listing history.
*
*/
public function testHistory()
{
echo "\nShould validate history of vin";
$apiInstance = new marketcheck\api\sdk\Api\HistoryApi(new GuzzleHttp\Client());
foreach($this->vin as $h_vin)
{
try
{
$result = $apiInstance->history($h_vin, $this->api_key);
$last_seen_at_ary = [];
$temp = [];
foreach($result as $listing)
{
array_push($temp,$listing["last_seen_at_date"]);
}
$last_seen_at_ary = $temp;
sort($last_seen_at_ary);
$this->assertNotEquals(sizeof($result), 0);
$this->assertEquals($temp, array_reverse($last_seen_at_ary));
$this->assertEquals(sizeof(array_unique($result)), sizeof($result));
print_r("\n/history/$h_vin?api_key={{api_key}}: endpoint working fine");
} catch (Exception $e) {
$this->fail($e->getMessage());
}
}
echo "\nValidate fields are returned when specified in fields param for multiple vins";
$this->fields = "seller_type,inventory_type,is_searchable,dealer_id,source,data_source";
$this->rows = null;
$this->page = null;
foreach($this->vin as $h_vin) {
try
{
$result = $apiInstance->history($h_vin, $this->api_key, $this->fields, $this->rows, $this->page);
$this->assertNotEquals(sizeof($result), 0);
foreach($result as $listing)
{
$this->assertArrayHasKey("seller_type", $listing);
$this->assertArrayHasKey("inventory_type", $listing);
$this->assertArrayHasKey("is_searchable", $listing);
$this->assertArrayHasKey("dealer_id", $listing);
$this->assertArrayHasKey("source", $listing);
$this->assertArrayHasKey("data_source", $listing);
$this->assertArrayHasKey("status_date", $listing);
}
print_r("\n/history/$h_vin?api_key={{api_key}}&fields=seller_type,inventory_type,is_searchable,dealer_id,source,data_source: endpoint working fine");
} catch (Exception $e) {
$this->fail($e->getMessage());
}
}
}
}
<file_sep>/docs/Api/DealerApi.md
# marketcheck\api\sdk\DealerApi
All URIs are relative to *https://marketcheck-prod.apigee.net/v1*
Method | HTTP request | Description
------------- | ------------- | -------------
[**dealerSearch**](DealerApi.md#dealerSearch) | **GET** /dealers | Find car dealers around
[**getDealer**](DealerApi.md#getDealer) | **GET** /dealer/{dealer_id} | Dealer by id
# **dealerSearch**
> \marketcheck\api\sdk\Model\DealersResponse dealerSearch($latitude, $longitude, $radius, $api_key, $rows, $start)
Find car dealers around
The dealers API returns a list of dealers around a given point and radius.
### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$apiInstance = new marketcheck\api\sdk\Api\DealerApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client()
);
$latitude = 1.2; // double | Latitude component of location
$longitude = 1.2; // double | Longitude component of location
$radius = 56; // int | Radius around the search location
$api_key = "api_key_example"; // string | The API Authentication Key. Mandatory with all API calls.
$rows = 8.14; // float | Number of results to return. Default is 10. Max is 50
$start = 8.14; // float | Offset for the search results. Default is 1.
try {
$result = $apiInstance->dealerSearch($latitude, $longitude, $radius, $api_key, $rows, $start);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling DealerApi->dealerSearch: ', $e->getMessage(), PHP_EOL;
}
?>
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**latitude** | **double**| Latitude component of location |
**longitude** | **double**| Longitude component of location |
**radius** | **int**| Radius around the search location |
**api_key** | **string**| The API Authentication Key. Mandatory with all API calls. | [optional]
**rows** | **float**| Number of results to return. Default is 10. Max is 50 | [optional]
**start** | **float**| Offset for the search results. Default is 1. | [optional]
### Return type
[**\marketcheck\api\sdk\Model\DealersResponse**](../Model/DealersResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)
# **getDealer**
> \marketcheck\api\sdk\Model\Dealer getDealer($dealer_id, $api_key)
Dealer by id
Get a particular dealer's information by its id
### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$apiInstance = new marketcheck\api\sdk\Api\DealerApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client()
);
$dealer_id = "dealer_id_example"; // string | Dealer id to get all the dealer info attributes
$api_key = "api_key_example"; // string | The API Authentication Key. Mandatory with all API calls.
try {
$result = $apiInstance->getDealer($dealer_id, $api_key);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling DealerApi->getDealer: ', $e->getMessage(), PHP_EOL;
}
?>
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**dealer_id** | **string**| Dealer id to get all the dealer info attributes |
**api_key** | **string**| The API Authentication Key. Mandatory with all API calls. | [optional]
### Return type
[**\marketcheck\api\sdk\Model\Dealer**](../Model/Dealer.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)
<file_sep>/lib/Model/Mds.php
<?php
/**
* Mds
*
* PHP version 5
*
* @category Class
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Marketcheck Cars API
*
* <b>Access the New, Used and Certified cars inventories for all Car Dealers in US.</b> <br/>The data is sourced from online listings by over 44,000 Car dealers in US. At any time, there are about 6.2M searchable listings (about 1.9M unique VINs) for Used & Certified cars and about 6.6M (about 3.9M unique VINs) New Car listings from all over US. We use this API at the back for our website <a href='https://www.marketcheck.com' target='_blank'>www.marketcheck.com</a> and our Android and iOS mobile apps too.<br/><h5> Few useful links : </h5><ul><li>A quick view of the API and the use cases is depicated <a href='https://portals.marketcheck.com/mcapi/' target='_blank'>here</a></li><li>The Postman collection with various usages of the API is shared here https://www.getpostman.com/collections/2752684ff636cdd7bac2</li></ul>
*
* OpenAPI spec version: 1.0.3
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.0-SNAPSHOT
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
namespace marketcheck\api\sdk\Model;
use \ArrayAccess;
use \marketcheck\api\sdk\ObjectSerializer;
/**
* Mds Class Doc Comment
*
* @category Class
* @description Describes Market days supply results for year make model trim combination
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class Mds implements ModelInterface, ArrayAccess
{
const DISCRIMINATOR = null;
/**
* The original name of the model.
*
* @var string
*/
protected static $swaggerModelName = 'Mds';
/**
* Array of property to type mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerTypes = [
'mds' => 'float',
'total_active_cars_for_ymmt' => 'float',
'total_cars_sold_in_last_45_days' => 'float',
'sold_vins' => 'string[]',
'year' => 'string',
'make' => 'string',
'model' => 'string',
'trim' => 'string'
];
/**
* Array of property to format mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerFormats = [
'mds' => null,
'total_active_cars_for_ymmt' => null,
'total_cars_sold_in_last_45_days' => null,
'sold_vins' => null,
'year' => null,
'make' => null,
'model' => null,
'trim' => null
];
/**
* Array of property to type mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerTypes()
{
return self::$swaggerTypes;
}
/**
* Array of property to format mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerFormats()
{
return self::$swaggerFormats;
}
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @var string[]
*/
protected static $attributeMap = [
'mds' => 'mds',
'total_active_cars_for_ymmt' => 'total_active_cars_for_ymmt',
'total_cars_sold_in_last_45_days' => 'total_cars_sold_in_last_45_days',
'sold_vins' => 'sold_vins',
'year' => 'year',
'make' => 'make',
'model' => 'model',
'trim' => 'trim'
];
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @var string[]
*/
protected static $setters = [
'mds' => 'setMds',
'total_active_cars_for_ymmt' => 'setTotalActiveCarsForYmmt',
'total_cars_sold_in_last_45_days' => 'setTotalCarsSoldInLast45Days',
'sold_vins' => 'setSoldVins',
'year' => 'setYear',
'make' => 'setMake',
'model' => 'setModel',
'trim' => 'setTrim'
];
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @var string[]
*/
protected static $getters = [
'mds' => 'getMds',
'total_active_cars_for_ymmt' => 'getTotalActiveCarsForYmmt',
'total_cars_sold_in_last_45_days' => 'getTotalCarsSoldInLast45Days',
'sold_vins' => 'getSoldVins',
'year' => 'getYear',
'make' => 'getMake',
'model' => 'getModel',
'trim' => 'getTrim'
];
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @return array
*/
public static function attributeMap()
{
return self::$attributeMap;
}
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @return array
*/
public static function setters()
{
return self::$setters;
}
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @return array
*/
public static function getters()
{
return self::$getters;
}
/**
* The original name of the model.
*
* @return string
*/
public function getModelName()
{
return self::$swaggerModelName;
}
/**
* Associative array for storing property values
*
* @var mixed[]
*/
protected $container = [];
/**
* Constructor
*
* @param mixed[] $data Associated array of property values
* initializing the model
*/
public function __construct(array $data = null)
{
$this->container['mds'] = isset($data['mds']) ? $data['mds'] : null;
$this->container['total_active_cars_for_ymmt'] = isset($data['total_active_cars_for_ymmt']) ? $data['total_active_cars_for_ymmt'] : null;
$this->container['total_cars_sold_in_last_45_days'] = isset($data['total_cars_sold_in_last_45_days']) ? $data['total_cars_sold_in_last_45_days'] : null;
$this->container['sold_vins'] = isset($data['sold_vins']) ? $data['sold_vins'] : null;
$this->container['year'] = isset($data['year']) ? $data['year'] : null;
$this->container['make'] = isset($data['make']) ? $data['make'] : null;
$this->container['model'] = isset($data['model']) ? $data['model'] : null;
$this->container['trim'] = isset($data['trim']) ? $data['trim'] : null;
}
/**
* Show all the invalid properties with reasons.
*
* @return array invalid properties with reasons
*/
public function listInvalidProperties()
{
$invalidProperties = [];
return $invalidProperties;
}
/**
* Validate all the properties in the model
* return true if all passed
*
* @return bool True if all properties are valid
*/
public function valid()
{
return count($this->listInvalidProperties()) === 0;
}
/**
* Gets mds
*
* @return float
*/
public function getMds()
{
return $this->container['mds'];
}
/**
* Sets mds
*
* @param float $mds Provides Market days supply count
*
* @return $this
*/
public function setMds($mds)
{
$this->container['mds'] = $mds;
return $this;
}
/**
* Gets total_active_cars_for_ymmt
*
* @return float
*/
public function getTotalActiveCarsForYmmt()
{
return $this->container['total_active_cars_for_ymmt'];
}
/**
* Sets total_active_cars_for_ymmt
*
* @param float $total_active_cars_for_ymmt Active cars for ymmt combination
*
* @return $this
*/
public function setTotalActiveCarsForYmmt($total_active_cars_for_ymmt)
{
$this->container['total_active_cars_for_ymmt'] = $total_active_cars_for_ymmt;
return $this;
}
/**
* Gets total_cars_sold_in_last_45_days
*
* @return float
*/
public function getTotalCarsSoldInLast45Days()
{
return $this->container['total_cars_sold_in_last_45_days'];
}
/**
* Sets total_cars_sold_in_last_45_days
*
* @param float $total_cars_sold_in_last_45_days Cars sold in last 45 days
*
* @return $this
*/
public function setTotalCarsSoldInLast45Days($total_cars_sold_in_last_45_days)
{
$this->container['total_cars_sold_in_last_45_days'] = $total_cars_sold_in_last_45_days;
return $this;
}
/**
* Gets sold_vins
*
* @return string[]
*/
public function getSoldVins()
{
return $this->container['sold_vins'];
}
/**
* Sets sold_vins
*
* @param string[] $sold_vins Sold vins array
*
* @return $this
*/
public function setSoldVins($sold_vins)
{
$this->container['sold_vins'] = $sold_vins;
return $this;
}
/**
* Gets year
*
* @return float
*/
public function getYear()
{
return $this->container['year'];
}
/**
* Sets year
*
* @param float $year Year of vin provided
*
* @return $this
*/
public function setYear($year)
{
$this->container['year'] = $year;
return $this;
}
/**
* Gets make
*
* @return string
*/
public function getMake()
{
return $this->container['make'];
}
/**
* Sets make
*
* @param string $make Make of vin provided
*
* @return $this
*/
public function setMake($make)
{
$this->container['make'] = $make;
return $this;
}
/**
* Gets model
*
* @return string
*/
public function getModel()
{
return $this->container['model'];
}
/**
* Sets model
*
* @param string $model Model of vin provided
*
* @return $this
*/
public function setModel($model)
{
$this->container['model'] = $model;
return $this;
}
/**
* Gets trim
*
* @return string
*/
public function getTrim()
{
return $this->container['trim'];
}
/**
* Sets trim
*
* @param string $trim Trim of vin provided
*
* @return $this
*/
public function setTrim($trim)
{
$this->container['trim'] = $trim;
return $this;
}
/**
* Returns true if offset exists. False otherwise.
*
* @param integer $offset Offset
*
* @return boolean
*/
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
/**
* Gets offset.
*
* @param integer $offset Offset
*
* @return mixed
*/
public function offsetGet($offset)
{
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
/**
* Sets value based on offset.
*
* @param integer $offset Offset
* @param mixed $value Value to be set
*
* @return void
*/
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
/**
* Unsets offset.
*
* @param integer $offset Offset
*
* @return void
*/
public function offsetUnset($offset)
{
unset($this->container[$offset]);
}
/**
* Gets the string presentation of the object
*
* @return string
*/
public function __toString()
{
if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
return json_encode(
ObjectSerializer::sanitizeForSerialization($this),
JSON_PRETTY_PRINT
);
}
return json_encode(ObjectSerializer::sanitizeForSerialization($this));
}
}
<file_sep>/docs/Api/ListingsApi.md
# marketcheck\api\sdk\ListingsApi
All URIs are relative to *https://marketcheck-prod.apigee.net/v1*
Method | HTTP request | Description
------------- | ------------- | -------------
[**getListing**](ListingsApi.md#getListing) | **GET** /listing/{id} | Listing by id
[**getListingExtra**](ListingsApi.md#getListingExtra) | **GET** /listing/{id}/extra | Long text Listings attributes for Listing with the given id
[**getListingMedia**](ListingsApi.md#getListingMedia) | **GET** /listing/{id}/media | Listing media by id
[**search**](ListingsApi.md#search) | **GET** /search | Gets active car listings for the given search criteria
# **getListing**
> \marketcheck\api\sdk\Model\Listing getListing($id, $api_key)
Listing by id
Get a particular listing by its id
### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$apiInstance = new marketcheck\api\sdk\Api\ListingsApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client()
);
$id = "id_example"; // string | Listing id to get all the listing attributes
$api_key = "api_key_example"; // string | The API Authentication Key. Mandatory with all API calls.
try {
$result = $apiInstance->getListing($id, $api_key);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ListingsApi->getListing: ', $e->getMessage(), PHP_EOL;
}
?>
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **string**| Listing id to get all the listing attributes |
**api_key** | **string**| The API Authentication Key. Mandatory with all API calls. | [optional]
### Return type
[**\marketcheck\api\sdk\Model\Listing**](../Model/Listing.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)
# **getListingExtra**
> \marketcheck\api\sdk\Model\ListingExtraAttributes getListingExtra($id, $api_key)
Long text Listings attributes for Listing with the given id
Get listing options, features, seller comments
### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$apiInstance = new marketcheck\api\sdk\Api\ListingsApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client()
);
$id = "id_example"; // string | Listing id to get all the long text listing attributes
$api_key = "api_key_example"; // string | The API Authentication Key. Mandatory with all API calls.
try {
$result = $apiInstance->getListingExtra($id, $api_key);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ListingsApi->getListingExtra: ', $e->getMessage(), PHP_EOL;
}
?>
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **string**| Listing id to get all the long text listing attributes |
**api_key** | **string**| The API Authentication Key. Mandatory with all API calls. | [optional]
### Return type
[**\marketcheck\api\sdk\Model\ListingExtraAttributes**](../Model/ListingExtraAttributes.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)
# **getListingMedia**
> \marketcheck\api\sdk\Model\ListingMedia getListingMedia($id, $api_key)
Listing media by id
Get listing media (photo, photos) by id
### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$apiInstance = new marketcheck\api\sdk\Api\ListingsApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client()
);
$id = "id_example"; // string | Listing id to get all the listing attributes
$api_key = "api_key_example"; // string | The API Authentication Key. Mandatory with all API calls.
try {
$result = $apiInstance->getListingMedia($id, $api_key);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ListingsApi->getListingMedia: ', $e->getMessage(), PHP_EOL;
}
?>
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **string**| Listing id to get all the listing attributes |
**api_key** | **string**| The API Authentication Key. Mandatory with all API calls. | [optional]
### Return type
[**\marketcheck\api\sdk\Model\ListingMedia**](../Model/ListingMedia.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)
# **search**
> \marketcheck\api\sdk\Model\SearchResponse search($api_key, $latitude, $longitude, $radius, $zip, $include_lease, $include_finance, $lease_term, $lease_down_payment, $lease_emp, $finance_loan_term, $finance_loan_apr, $finance_emp, $finance_down_payment, $finance_down_payment_per, $car_type, $seller_type, $carfax_1_owner, $carfax_clean_title, $year, $make, $model, $trim, $dealer_id, $vin, $source, $body_type, $body_subtype, $vehicle_type, $vins, $taxonomy_vins, $ymmt, $match, $cylinders, $transmission, $speeds, $doors, $drivetrain, $exterior_color, $interior_color, $engine, $engine_type, $engine_aspiration, $engine_block, $miles_range, $price_range, $dom_range, $sort_by, $sort_order, $rows, $start, $facets, $stats, $country, $plot, $nodedup, $state, $city, $dealer_name, $trim_o, $trim_r, $dom_active_range, $dom_180_range, $options, $features, $exclude_certified)
Gets active car listings for the given search criteria
This endpoint is the meat of the API and serves many purposes. This API produces a list of currently active cars from the market for the given search criteria. The API results are limited to allow pagination upto 1000 rows. The search API facilitates the following use cases - 1. Search Cars around a given geo-point within a given radius 2. Search cars for a specific year / make / model or combination of these 3. Search cars matching multiple year, make, model combinatins in the same search request 4. Filter results by most car specification attributes 5. Search for similar cars by VIN or Taxonomy VIN 6. Filter cars within a given price / miles / days on market (dom) range 7. Specify a sort order for the results on price / miles / dom / listed date 8. Search cars for a given City / State combination 9. Get Facets to build the search drill downs 10. Get Market averages for price/miles/dom/msrp for your search
### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$apiInstance = new marketcheck\api\sdk\Api\ListingsApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client()
);
$api_key = "api_key_example"; // string | The API Authentication Key. Mandatory with all API calls.
$latitude = 1.2; // double | Latitude component of location
$longitude = 1.2; // double | Longitude component of location
$radius = 56; // int | Radius around the search location
$zip = "zip_example"; // string | car search bases on zipcode
$include_lease = true; // bool | Boolean param to search for listings that include leasing options in them
$include_finance = true; // bool | Boolean param to search for listings that include finance options in them
$lease_term = "lease_term_example"; // string | Search listings with exact lease term, or inside a range with min and max seperated by a dash like lease_term=30-60
$lease_down_payment = "lease_down_payment_example"; // string | Search listings with exact down payment in lease offers, or inside a range with min and max seperated by a dash like lease_down_payment=30-60
$lease_emp = "lease_emp_example"; // string | Search listings with lease offers exactly matching Estimated Monthly Payment(EMI), or inside a range with min and max seperated by a dash like lease_emp=30-60
$finance_loan_term = "finance_loan_term_example"; // string | Search listings with exact finance loan term, or inside a range with min and max seperated by a dash like finance_loan_term=30-60
$finance_loan_apr = "finance_loan_apr_example"; // string | Search listings with finance offers exactly matching loans Annual Percentage Rate, or inside a range with min and max seperated by a dash like finance_loan_apr=30-60
$finance_emp = "finance_emp_example"; // string | Search listings with finance offers exactly matching Estimated Monthly Payment(EMI), or inside a range with min and max seperated by a dash like finance_emp=30-60
$finance_down_payment = "finance_down_payment_example"; // string | Search listings with exact down payment in finance offers, or inside a range with min and max seperated by a dash like finance_down_payment=30-60
$finance_down_payment_per = "finance_down_payment_per_example"; // string | Search listings with exact down payment percentage in finance offers, or inside a range with min and max seperated by a dash like finance_down_payment_per=30-60
$car_type = "car_type_example"; // string | Car type. Allowed values are - new / used / certified
$seller_type = "seller_type_example"; // string | Seller type to filter cars on. Valid filter values are those that our Search facets API returns for unique seller types. You can pass in multiple seller type values comma separated.
$carfax_1_owner = "carfax_1_owner_example"; // string | Indicates whether car has had only one owner or not
$carfax_clean_title = "carfax_clean_title_example"; // string | Indicates whether car has clean ownership records
$year = "year_example"; // string | Car year - 1980 onwards. Valid filter values are those that our Search facets API returns for unique years. You can pass in multiple year values comma separated.
$make = "make_example"; // string | Car Make - should be a standard OEM Make name. Valid filter values are those that our Search facets API returns for unique make. You can pass in multiple make values separated by comma. e.g. ford,audi
$model = "model_example"; // string | Car model to search. Valid filter values are those that our Search facets API returns for unique model. You can pass in multiple model values comma separated for e.g f-150,Mustang.
$trim = "trim_example"; // string | Car trim to search. Valid filter values are those that our Search facets API returns for unique trim. You can pass in multiple trim values comma separated
$dealer_id = "dealer_id_example"; // string | Dealer id to filter the cars.
$vin = "vin_example"; // string | Car vin to search
$source = "source_example"; // string | Source to search cars. Valid filter values are those that our Search facets API returns for unique source. You can pass in multiple source values comma separated
$body_type = "body_type_example"; // string | Body type to filter the cars on. Valid filter values are those that our Search facets API returns for unique body types. You can pass in multiple body types comma separated.
$body_subtype = "body_subtype_example"; // string | Body subtype to filter the cars on. Valid filter values are those that our Search facets API returns for unique body subtypes. You can pass in multiple body subtype values comma separated
$vehicle_type = "vehicle_type_example"; // string | Vehicle type to filter the cars on. Valid filter values are those that our Search facets API returns for unique vehicle types. You can pass in multiple vehicle type values comma separated
$vins = "vins_example"; // string | Comma separated list of 17 digit vins to search the matching cars for. Only 10 VINs allowed per request. If the request contains more than 10 VINs the first 10 VINs will be considered. Could be used as a More Like This or Similar Vehicles search for the given VINs. Ths vins parameter is an alternative to taxonomy_vins or ymmt parameters available with the search API. vins and taxonomy_vins parameters could be used to filter our cars with the exact build represented by the vins or taxonomy_vins whereas ymmt is a top level filter that does not filter cars by the build attributes like doors, drivetrain, cylinders, body type, body subtype, vehicle type etc
$taxonomy_vins = "taxonomy_vins_example"; // string | Comma separated list of 10 letters excert from the 17 letter VIN. The 10 letters to be picked up from the 17 letter VIN are - first 8 letters and the 10th and 11th letter. E.g. For a VIN - 1FTFW1EF3EKE57182 the taxonomy vin would be - 1FTFW1EFEK A taxonomy VIN identified a build of a car and could be used to filter our cars of a particular build. This is an alternative to the vin or ymmt parameters to the search API.
$ymmt = "ymmt_example"; // string | Comma separated list of Year, Make, Model, Trim combinations. Each combination needs to have the year,make,model, trim values separated by a pipe '|' character in the form year|make|model|trim. e.g. 2010|Audi|A5,2014|Nissan|Sentra|S 6MT,|Honda|City| You could just provide strings of the form - 'year|make||' or 'year|make|model' or '|make|model|' combinations. Individual year / make / model filters provied with the API calls will take precedence over the Year, Make, Model, Trim combinations. The Make, Model, Trim values must be valid values as per the Marketcheck Vin Decoder. If you are using a separate vin decoder then look at using the 'vins' or 'taxonomy_vins' parameter to the search api instead the year|make|model|trim combinations.
$match = "match_example"; // string | Comma separated list of Year, Make, Model, Trim fields. For example - year,make,model,trim fields for which user wants to do an exact match
$cylinders = "cylinders_example"; // string | Cylinders to filter the cars on. Valid filter values are those that our Search facets API returns for unique cylinder values. You can pass in multiple cylinder values comma separated
$transmission = "transmission_example"; // string | Transmission to filter the cars on. [a = Automatic, m = Manual]. Valid filter values are those that our Search facets API returns for unique transmission. You can pass in multiple transmission values comma separated
$speeds = "speeds_example"; // string | Speeds to filter the cars on. Valid filter values are those that our Search facets API returns for unique speeds. You can pass in multiple speeds values comma separated
$doors = "doors_example"; // string | Doors to filter the cars on. Valid filter values are those that our Search facets API returns for unique doors. You can pass in multiple doors values comma separated
$drivetrain = "drivetrain_example"; // string | Drivetrain to filter the cars on. Valid filter values are those that our Search facets API returns for unique drivetrains. You can pass in multiple drivetrain values comma separated
$exterior_color = "exterior_color_example"; // string | Exterior color to match. Valid filter values are those that our Search facets API returns for unique exterior colors. You can pass in multiple exterior color values comma separated
$interior_color = "interior_color_example"; // string | Interior color to match. Valid filter values are those that our Search facets API returns for unique interior colors. You can pass in multiple interior color values comma separated
$engine = "engine_example"; // string | Filter listings on engine
$engine_type = "engine_type_example"; // string | Engine Type to match. Valid filter values are those that our Search facets API returns for unique engine types. You can pass in multiple engine type values comma separated
$engine_aspiration = "engine_aspiration_example"; // string | Engine Aspiration to match. Valid filter values are those that our Search facets API returns for unique Engine Aspirations. You can pass in multiple Engine aspirations values comma separated
$engine_block = "engine_block_example"; // string | Engine Block to match. Valid filter values are those that our Search facets API returns for unique Engine Block. You can pass in multiple Engine Block values comma separated
$miles_range = "miles_range_example"; // string | Miles range to filter cars with miles in the given range. Range to be given in the format - min-max e.g. 1000-5000
$price_range = "price_range_example"; // string | Price range to filter cars with the price in the range given. Range to be given in the format - min-max e.g. 1000-5000
$dom_range = "dom_range_example"; // string | Days on Market range to filter cars with the DOM within the given range. Range to be given in the format - min-max e.g. 10-50
$sort_by = "sort_by_example"; // string | Sort by field - allowed fields are distance|price|miles|dom|age|posted_at|year. Default sort field is distance from the given point
$sort_order = "sort_order_example"; // string | Sort order - asc or desc. Default sort order is distance from a point.
$rows = "rows_example"; // string | Number of results to return. Default is 10. Max is 50
$start = "start_example"; // string | Page number to fetch the results for the given criteria. Default is 1. Pagination is allowed only till first 1000 results for the search and sort criteria. The page value can be only between 1 to 1000/rows
$facets = "facets_example"; // string | The comma separated list of fields for which facets are requested. Supported fields are - year, make, model, trim, vehicle_type, car_type, body_type, body_subtype, drivetrain, cylinders, transmission, exterior_color, interior_color, doors, engine_type, engine_aspiration, engine_block. Facets could be requested in addition to the listings for the search. Please note - The API calls with lots of facet fields may take longer to respond.
$stats = "stats_example"; // string | The list of fields for which stats need to be generated based on the matching listings for the search criteria. Allowed fields are - price, miles, msrp, dom The stats consists of mean, max, average and count of listings based on which the stats are calculated for the field. Stats could be requested in addition to the listings for the search. Please note - The API calls with the stats fields may take longer to respond.
$country = "country_example"; // string | Filter on Country, by default US. Search available on US (United States) and CA (Canada)
$plot = "plot_example"; // string | If plot has value true results in around 25k coordinates with limited fields to plot respective graph
$nodedup = true; // bool | If nodedup is set to true then will give results without is_searchable i.e multiple listings for single vin
$state = "state_example"; // string | Filter listsings on State
$city = "city_example"; // string | Filter listings on city
$dealer_name = "dealer_name_example"; // string | Filter listings on dealer_name
$trim_o = "trim_o_example"; // string | Filter listings on web scraped trim
$trim_r = "trim_r_example"; // string | Filter trim on custom possible matches
$dom_active_range = "dom_active_range_example"; // string | Active Days on Market range to filter cars with the DOM within the given range. Range to be given in the format - min-max e.g. 10-50
$dom_180_range = "dom_180_range_example"; // string | Last 180 Days on Market range to filter cars with the DOM within the given range. Range to be given in the format - min-max e.g. 10-50
$options = "options_example"; // string | Tokenizer search on options for multiple options use | as seperator
$features = "features_example"; // string | Tokenizer search on features for multiple options use | as seperator
$exclude_certified = true; // bool | Boolean param to exclude certified cars from search results
try {
$result = $apiInstance->search($api_key, $latitude, $longitude, $radius, $zip, $include_lease, $include_finance, $lease_term, $lease_down_payment, $lease_emp, $finance_loan_term, $finance_loan_apr, $finance_emp, $finance_down_payment, $finance_down_payment_per, $car_type, $seller_type, $carfax_1_owner, $carfax_clean_title, $year, $make, $model, $trim, $dealer_id, $vin, $source, $body_type, $body_subtype, $vehicle_type, $vins, $taxonomy_vins, $ymmt, $match, $cylinders, $transmission, $speeds, $doors, $drivetrain, $exterior_color, $interior_color, $engine, $engine_type, $engine_aspiration, $engine_block, $miles_range, $price_range, $dom_range, $sort_by, $sort_order, $rows, $start, $facets, $stats, $country, $plot, $nodedup, $state, $city, $dealer_name, $trim_o, $trim_r, $dom_active_range, $dom_180_range, $options, $features, $exclude_certified);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ListingsApi->search: ', $e->getMessage(), PHP_EOL;
}
?>
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**api_key** | **string**| The API Authentication Key. Mandatory with all API calls. | [optional]
**latitude** | **double**| Latitude component of location | [optional]
**longitude** | **double**| Longitude component of location | [optional]
**radius** | **int**| Radius around the search location | [optional]
**zip** | **string**| car search bases on zipcode | [optional]
**include_lease** | **bool**| Boolean param to search for listings that include leasing options in them | [optional]
**include_finance** | **bool**| Boolean param to search for listings that include finance options in them | [optional]
**lease_term** | **string**| Search listings with exact lease term, or inside a range with min and max seperated by a dash like lease_term=30-60 | [optional]
**lease_down_payment** | **string**| Search listings with exact down payment in lease offers, or inside a range with min and max seperated by a dash like lease_down_payment=30-60 | [optional]
**lease_emp** | **string**| Search listings with lease offers exactly matching Estimated Monthly Payment(EMI), or inside a range with min and max seperated by a dash like lease_emp=30-60 | [optional]
**finance_loan_term** | **string**| Search listings with exact finance loan term, or inside a range with min and max seperated by a dash like finance_loan_term=30-60 | [optional]
**finance_loan_apr** | **string**| Search listings with finance offers exactly matching loans Annual Percentage Rate, or inside a range with min and max seperated by a dash like finance_loan_apr=30-60 | [optional]
**finance_emp** | **string**| Search listings with finance offers exactly matching Estimated Monthly Payment(EMI), or inside a range with min and max seperated by a dash like finance_emp=30-60 | [optional]
**finance_down_payment** | **string**| Search listings with exact down payment in finance offers, or inside a range with min and max seperated by a dash like finance_down_payment=30-60 | [optional]
**finance_down_payment_per** | **string**| Search listings with exact down payment percentage in finance offers, or inside a range with min and max seperated by a dash like finance_down_payment_per=30-60 | [optional]
**car_type** | **string**| Car type. Allowed values are - new / used / certified | [optional]
**seller_type** | **string**| Seller type to filter cars on. Valid filter values are those that our Search facets API returns for unique seller types. You can pass in multiple seller type values comma separated. | [optional]
**carfax_1_owner** | **string**| Indicates whether car has had only one owner or not | [optional]
**carfax_clean_title** | **string**| Indicates whether car has clean ownership records | [optional]
**year** | **string**| Car year - 1980 onwards. Valid filter values are those that our Search facets API returns for unique years. You can pass in multiple year values comma separated. | [optional]
**make** | **string**| Car Make - should be a standard OEM Make name. Valid filter values are those that our Search facets API returns for unique make. You can pass in multiple make values separated by comma. e.g. ford,audi | [optional]
**model** | **string**| Car model to search. Valid filter values are those that our Search facets API returns for unique model. You can pass in multiple model values comma separated for e.g f-150,Mustang. | [optional]
**trim** | **string**| Car trim to search. Valid filter values are those that our Search facets API returns for unique trim. You can pass in multiple trim values comma separated | [optional]
**dealer_id** | **string**| Dealer id to filter the cars. | [optional]
**vin** | **string**| Car vin to search | [optional]
**source** | **string**| Source to search cars. Valid filter values are those that our Search facets API returns for unique source. You can pass in multiple source values comma separated | [optional]
**body_type** | **string**| Body type to filter the cars on. Valid filter values are those that our Search facets API returns for unique body types. You can pass in multiple body types comma separated. | [optional]
**body_subtype** | **string**| Body subtype to filter the cars on. Valid filter values are those that our Search facets API returns for unique body subtypes. You can pass in multiple body subtype values comma separated | [optional]
**vehicle_type** | **string**| Vehicle type to filter the cars on. Valid filter values are those that our Search facets API returns for unique vehicle types. You can pass in multiple vehicle type values comma separated | [optional]
**vins** | **string**| Comma separated list of 17 digit vins to search the matching cars for. Only 10 VINs allowed per request. If the request contains more than 10 VINs the first 10 VINs will be considered. Could be used as a More Like This or Similar Vehicles search for the given VINs. Ths vins parameter is an alternative to taxonomy_vins or ymmt parameters available with the search API. vins and taxonomy_vins parameters could be used to filter our cars with the exact build represented by the vins or taxonomy_vins whereas ymmt is a top level filter that does not filter cars by the build attributes like doors, drivetrain, cylinders, body type, body subtype, vehicle type etc | [optional]
**taxonomy_vins** | **string**| Comma separated list of 10 letters excert from the 17 letter VIN. The 10 letters to be picked up from the 17 letter VIN are - first 8 letters and the 10th and 11th letter. E.g. For a VIN - 1FTFW1EF3EKE57182 the taxonomy vin would be - 1FTFW1EFEK A taxonomy VIN identified a build of a car and could be used to filter our cars of a particular build. This is an alternative to the vin or ymmt parameters to the search API. | [optional]
**ymmt** | **string**| Comma separated list of Year, Make, Model, Trim combinations. Each combination needs to have the year,make,model, trim values separated by a pipe '|' character in the form year|make|model|trim. e.g. 2010|Audi|A5,2014|Nissan|Sentra|S 6MT,|Honda|City| You could just provide strings of the form - 'year|make||' or 'year|make|model' or '|make|model|' combinations. Individual year / make / model filters provied with the API calls will take precedence over the Year, Make, Model, Trim combinations. The Make, Model, Trim values must be valid values as per the Marketcheck Vin Decoder. If you are using a separate vin decoder then look at using the 'vins' or 'taxonomy_vins' parameter to the search api instead the year|make|model|trim combinations. | [optional]
**match** | **string**| Comma separated list of Year, Make, Model, Trim fields. For example - year,make,model,trim fields for which user wants to do an exact match | [optional]
**cylinders** | **string**| Cylinders to filter the cars on. Valid filter values are those that our Search facets API returns for unique cylinder values. You can pass in multiple cylinder values comma separated | [optional]
**transmission** | **string**| Transmission to filter the cars on. [a = Automatic, m = Manual]. Valid filter values are those that our Search facets API returns for unique transmission. You can pass in multiple transmission values comma separated | [optional]
**speeds** | **string**| Speeds to filter the cars on. Valid filter values are those that our Search facets API returns for unique speeds. You can pass in multiple speeds values comma separated | [optional]
**doors** | **string**| Doors to filter the cars on. Valid filter values are those that our Search facets API returns for unique doors. You can pass in multiple doors values comma separated | [optional]
**drivetrain** | **string**| Drivetrain to filter the cars on. Valid filter values are those that our Search facets API returns for unique drivetrains. You can pass in multiple drivetrain values comma separated | [optional]
**exterior_color** | **string**| Exterior color to match. Valid filter values are those that our Search facets API returns for unique exterior colors. You can pass in multiple exterior color values comma separated | [optional]
**interior_color** | **string**| Interior color to match. Valid filter values are those that our Search facets API returns for unique interior colors. You can pass in multiple interior color values comma separated | [optional]
**engine** | **string**| Filter listings on engine | [optional]
**engine_type** | **string**| Engine Type to match. Valid filter values are those that our Search facets API returns for unique engine types. You can pass in multiple engine type values comma separated | [optional]
**engine_aspiration** | **string**| Engine Aspiration to match. Valid filter values are those that our Search facets API returns for unique Engine Aspirations. You can pass in multiple Engine aspirations values comma separated | [optional]
**engine_block** | **string**| Engine Block to match. Valid filter values are those that our Search facets API returns for unique Engine Block. You can pass in multiple Engine Block values comma separated | [optional]
**miles_range** | **string**| Miles range to filter cars with miles in the given range. Range to be given in the format - min-max e.g. 1000-5000 | [optional]
**price_range** | **string**| Price range to filter cars with the price in the range given. Range to be given in the format - min-max e.g. 1000-5000 | [optional]
**dom_range** | **string**| Days on Market range to filter cars with the DOM within the given range. Range to be given in the format - min-max e.g. 10-50 | [optional]
**sort_by** | **string**| Sort by field - allowed fields are distance|price|miles|dom|age|posted_at|year. Default sort field is distance from the given point | [optional]
**sort_order** | **string**| Sort order - asc or desc. Default sort order is distance from a point. | [optional]
**rows** | **string**| Number of results to return. Default is 10. Max is 50 | [optional]
**start** | **string**| Page number to fetch the results for the given criteria. Default is 1. Pagination is allowed only till first 1000 results for the search and sort criteria. The page value can be only between 1 to 1000/rows | [optional]
**facets** | **string**| The comma separated list of fields for which facets are requested. Supported fields are - year, make, model, trim, vehicle_type, car_type, body_type, body_subtype, drivetrain, cylinders, transmission, exterior_color, interior_color, doors, engine_type, engine_aspiration, engine_block. Facets could be requested in addition to the listings for the search. Please note - The API calls with lots of facet fields may take longer to respond. | [optional]
**stats** | **string**| The list of fields for which stats need to be generated based on the matching listings for the search criteria. Allowed fields are - price, miles, msrp, dom The stats consists of mean, max, average and count of listings based on which the stats are calculated for the field. Stats could be requested in addition to the listings for the search. Please note - The API calls with the stats fields may take longer to respond. | [optional]
**country** | **string**| Filter on Country, by default US. Search available on US (United States) and CA (Canada) | [optional]
**plot** | **string**| If plot has value true results in around 25k coordinates with limited fields to plot respective graph | [optional]
**nodedup** | **bool**| If nodedup is set to true then will give results without is_searchable i.e multiple listings for single vin | [optional]
**state** | **string**| Filter listsings on State | [optional]
**city** | **string**| Filter listings on city | [optional]
**dealer_name** | **string**| Filter listings on dealer_name | [optional]
**trim_o** | **string**| Filter listings on web scraped trim | [optional]
**trim_r** | **string**| Filter trim on custom possible matches | [optional]
**dom_active_range** | **string**| Active Days on Market range to filter cars with the DOM within the given range. Range to be given in the format - min-max e.g. 10-50 | [optional]
**dom_180_range** | **string**| Last 180 Days on Market range to filter cars with the DOM within the given range. Range to be given in the format - min-max e.g. 10-50 | [optional]
**options** | **string**| Tokenizer search on options for multiple options use | as seperator | [optional]
**features** | **string**| Tokenizer search on features for multiple options use | as seperator | [optional]
**exclude_certified** | **bool**| Boolean param to exclude certified cars from search results | [optional]
### Return type
[**\marketcheck\api\sdk\Model\SearchResponse**](../Model/SearchResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)
<file_sep>/lib/Model/Build.php
<?php
/**
* Build
*
* PHP version 5
*
* @category Class
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Marketcheck Cars API
*
* <b>Access the New, Used and Certified cars inventories for all Car Dealers in US.</b> <br/>The data is sourced from online listings by over 44,000 Car dealers in US. At any time, there are about 6.2M searchable listings (about 1.9M unique VINs) for Used & Certified cars and about 6.6M (about 3.9M unique VINs) New Car listings from all over US. We use this API at the back for our website <a href='https://www.marketcheck.com' target='_blank'>www.marketcheck.com</a> and our Android and iOS mobile apps too.<br/><h5> Few useful links : </h5><ul><li>A quick view of the API and the use cases is depicated <a href='https://portals.marketcheck.com/mcapi/' target='_blank'>here</a></li><li>The Postman collection with various usages of the API is shared here https://www.getpostman.com/collections/2752684ff636cdd7bac2</li></ul>
*
* OpenAPI spec version: 1.0.3
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.0-SNAPSHOT
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
namespace marketcheck\api\sdk\Model;
use \ArrayAccess;
use \marketcheck\api\sdk\ObjectSerializer;
/**
* Build Class Doc Comment
*
* @category Class
* @description Describes the Car specification
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class Build implements ModelInterface, ArrayAccess
{
const DISCRIMINATOR = null;
/**
* The original name of the model.
*
* @var string
*/
protected static $swaggerModelName = 'Build';
/**
* Array of property to type mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerTypes = [
'year' => 'string',
'make' => 'string',
'model' => 'string',
'trim' => 'string',
'body_type' => 'string',
'body_subtype' => 'string',
'vehicle_type' => 'string',
'drivetrain' => 'string',
'fuel_type' => 'string',
'made_in' => 'string',
'engine' => 'string',
'engine_block' => 'string',
'engine_size' => 'string',
'engine_measure' => 'string',
'engine_aspiration' => 'string',
'transmission' => 'string',
'doors' => 'float',
'cylinders' => 'float',
'steering_type' => 'string',
'antibrake_sys' => 'string',
'tank_size' => 'string',
'overall_height' => 'string',
'overall_length' => 'string',
'overall_width' => 'string',
'std_seating' => 'string',
'highway_miles' => 'string',
'city_miles' => 'string'
];
/**
* Array of property to format mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerFormats = [
'year' => null,
'make' => null,
'model' => null,
'trim' => null,
'body_type' => null,
'body_subtype' => null,
'vehicle_type' => null,
'drivetrain' => null,
'fuel_type' => null,
'made_in' => null,
'engine' => null,
'engine_block' => null,
'engine_size' => null,
'engine_measure' => null,
'engine_aspiration' => null,
'transmission' => null,
'doors' => null,
'cylinders' => null,
'steering_type' => null,
'antibrake_sys' => null,
'tank_size' => null,
'overall_height' => null,
'overall_length' => null,
'overall_width' => null,
'std_seating' => null,
'highway_miles' => null,
'city_miles' => null
];
/**
* Array of property to type mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerTypes()
{
return self::$swaggerTypes;
}
/**
* Array of property to format mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerFormats()
{
return self::$swaggerFormats;
}
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @var string[]
*/
protected static $attributeMap = [
'year' => 'year',
'make' => 'make',
'model' => 'model',
'trim' => 'trim',
'body_type' => 'body_type',
'body_subtype' => 'body_subtype',
'vehicle_type' => 'vehicle_type',
'drivetrain' => 'drivetrain',
'fuel_type' => 'fuel_type',
'made_in' => 'made_in',
'engine' => 'engine',
'engine_block' => 'engine_block',
'engine_size' => 'engine_size',
'engine_measure' => 'engine_measure',
'engine_aspiration' => 'engine_aspiration',
'transmission' => 'transmission',
'doors' => 'doors',
'cylinders' => 'cylinders',
'steering_type' => 'steering_type',
'antibrake_sys' => 'antibrake_sys',
'tank_size' => 'tank_size',
'overall_height' => 'overall_height',
'overall_length' => 'overall_length',
'overall_width' => 'overall_width',
'std_seating' => 'std_seating',
'highway_miles' => 'highway_miles',
'city_miles' => 'city_miles'
];
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @var string[]
*/
protected static $setters = [
'year' => 'setYear',
'make' => 'setMake',
'model' => 'setModel',
'trim' => 'setTrim',
'body_type' => 'setBodyType',
'body_subtype' => 'setBodySubtype',
'vehicle_type' => 'setVehicleType',
'drivetrain' => 'setDrivetrain',
'fuel_type' => 'setFuelType',
'made_in' => 'setMadeIn',
'engine' => 'setEngine',
'engine_block' => 'setEngineBlock',
'engine_size' => 'setEngineSize',
'engine_measure' => 'setEngineMeasure',
'engine_aspiration' => 'setEngineAspiration',
'transmission' => 'setTransmission',
'doors' => 'setDoors',
'cylinders' => 'setCylinders',
'steering_type' => 'setSteeringType',
'antibrake_sys' => 'setAntibrakeSys',
'tank_size' => 'setTankSize',
'overall_height' => 'setOverallHeight',
'overall_length' => 'setOverallLength',
'overall_width' => 'setOverallWidth',
'std_seating' => 'setStdSeating',
'highway_miles' => 'setHighwayMiles',
'city_miles' => 'setCityMiles'
];
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @var string[]
*/
protected static $getters = [
'year' => 'getYear',
'make' => 'getMake',
'model' => 'getModel',
'trim' => 'getTrim',
'body_type' => 'getBodyType',
'body_subtype' => 'getBodySubtype',
'vehicle_type' => 'getVehicleType',
'drivetrain' => 'getDrivetrain',
'fuel_type' => 'getFuelType',
'made_in' => 'getMadeIn',
'engine' => 'getEngine',
'engine_block' => 'getEngineBlock',
'engine_size' => 'getEngineSize',
'engine_measure' => 'getEngineMeasure',
'engine_aspiration' => 'getEngineAspiration',
'transmission' => 'getTransmission',
'doors' => 'getDoors',
'cylinders' => 'getCylinders',
'steering_type' => 'getSteeringType',
'antibrake_sys' => 'getAntibrakeSys',
'tank_size' => 'getTankSize',
'overall_height' => 'getOverallHeight',
'overall_length' => 'getOverallLength',
'overall_width' => 'getOverallWidth',
'std_seating' => 'getStdSeating',
'highway_miles' => 'getHighwayMiles',
'city_miles' => 'getCityMiles'
];
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @return array
*/
public static function attributeMap()
{
return self::$attributeMap;
}
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @return array
*/
public static function setters()
{
return self::$setters;
}
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @return array
*/
public static function getters()
{
return self::$getters;
}
/**
* The original name of the model.
*
* @return string
*/
public function getModelName()
{
return self::$swaggerModelName;
}
/**
* Associative array for storing property values
*
* @var mixed[]
*/
protected $container = [];
/**
* Constructor
*
* @param mixed[] $data Associated array of property values
* initializing the model
*/
public function __construct(array $data = null)
{
$this->container['year'] = isset($data['year']) ? $data['year'] : null;
$this->container['make'] = isset($data['make']) ? $data['make'] : null;
$this->container['model'] = isset($data['model']) ? $data['model'] : null;
$this->container['trim'] = isset($data['trim']) ? $data['trim'] : null;
$this->container['body_type'] = isset($data['body_type']) ? $data['body_type'] : null;
$this->container['body_subtype'] = isset($data['body_subtype']) ? $data['body_subtype'] : null;
$this->container['vehicle_type'] = isset($data['vehicle_type']) ? $data['vehicle_type'] : null;
$this->container['drivetrain'] = isset($data['drivetrain']) ? $data['drivetrain'] : null;
$this->container['fuel_type'] = isset($data['fuel_type']) ? $data['fuel_type'] : null;
$this->container['made_in'] = isset($data['made_in']) ? $data['made_in'] : null;
$this->container['engine'] = isset($data['engine']) ? $data['engine'] : null;
$this->container['engine_block'] = isset($data['engine_block']) ? $data['engine_block'] : null;
$this->container['engine_size'] = isset($data['engine_size']) ? $data['engine_size'] : null;
$this->container['engine_measure'] = isset($data['engine_measure']) ? $data['engine_measure'] : null;
$this->container['engine_aspiration'] = isset($data['engine_aspiration']) ? $data['engine_aspiration'] : null;
$this->container['transmission'] = isset($data['transmission']) ? $data['transmission'] : null;
$this->container['doors'] = isset($data['doors']) ? $data['doors'] : null;
$this->container['cylinders'] = isset($data['cylinders']) ? $data['cylinders'] : null;
$this->container['steering_type'] = isset($data['steering_type']) ? $data['steering_type'] : null;
$this->container['antibrake_sys'] = isset($data['antibrake_sys']) ? $data['antibrake_sys'] : null;
$this->container['tank_size'] = isset($data['tank_size']) ? $data['tank_size'] : null;
$this->container['overall_height'] = isset($data['overall_height']) ? $data['overall_height'] : null;
$this->container['overall_length'] = isset($data['overall_length']) ? $data['overall_length'] : null;
$this->container['overall_width'] = isset($data['overall_width']) ? $data['overall_width'] : null;
$this->container['std_seating'] = isset($data['std_seating']) ? $data['std_seating'] : null;
$this->container['highway_miles'] = isset($data['highway_miles']) ? $data['highway_miles'] : null;
$this->container['city_miles'] = isset($data['city_miles']) ? $data['city_miles'] : null;
}
/**
* Show all the invalid properties with reasons.
*
* @return array invalid properties with reasons
*/
public function listInvalidProperties()
{
$invalidProperties = [];
return $invalidProperties;
}
/**
* Validate all the properties in the model
* return true if all passed
*
* @return bool True if all properties are valid
*/
public function valid()
{
return count($this->listInvalidProperties()) === 0;
}
/**
* Gets year
*
* @return float
*/
public function getYear()
{
return $this->container['year'];
}
/**
* Sets year
*
* @param float $year Year of the Car
*
* @return $this
*/
public function setYear($year)
{
$this->container['year'] = $year;
return $this;
}
/**
* Gets make
*
* @return string
*/
public function getMake()
{
return $this->container['make'];
}
/**
* Sets make
*
* @param string $make Car Make
*
* @return $this
*/
public function setMake($make)
{
$this->container['make'] = $make;
return $this;
}
/**
* Gets model
*
* @return string
*/
public function getModel()
{
return $this->container['model'];
}
/**
* Sets model
*
* @param string $model Car model
*
* @return $this
*/
public function setModel($model)
{
$this->container['model'] = $model;
return $this;
}
/**
* Gets trim
*
* @return string
*/
public function getTrim()
{
return $this->container['trim'];
}
/**
* Sets trim
*
* @param string $trim Trim of the car
*
* @return $this
*/
public function setTrim($trim)
{
$this->container['trim'] = $trim;
return $this;
}
/**
* Gets body_type
*
* @return string
*/
public function getBodyType()
{
return $this->container['body_type'];
}
/**
* Sets body_type
*
* @param string $body_type Body type of the car
*
* @return $this
*/
public function setBodyType($body_type)
{
$this->container['body_type'] = $body_type;
return $this;
}
/**
* Gets body_subtype
*
* @return string
*/
public function getBodySubtype()
{
return $this->container['body_subtype'];
}
/**
* Sets body_subtype
*
* @param string $body_subtype Body type of the car
*
* @return $this
*/
public function setBodySubtype($body_subtype)
{
$this->container['body_subtype'] = $body_subtype;
return $this;
}
/**
* Gets vehicle_type
*
* @return string
*/
public function getVehicleType()
{
return $this->container['vehicle_type'];
}
/**
* Sets vehicle_type
*
* @param string $vehicle_type Vehicle type of the car
*
* @return $this
*/
public function setVehicleType($vehicle_type)
{
$this->container['vehicle_type'] = $vehicle_type;
return $this;
}
/**
* Gets drivetrain
*
* @return string
*/
public function getDrivetrain()
{
return $this->container['drivetrain'];
}
/**
* Sets drivetrain
*
* @param string $drivetrain Drivetrain of the car
*
* @return $this
*/
public function setDrivetrain($drivetrain)
{
$this->container['drivetrain'] = $drivetrain;
return $this;
}
/**
* Gets fuel_type
*
* @return string
*/
public function getFuelType()
{
return $this->container['fuel_type'];
}
/**
* Sets fuel_type
*
* @param string $fuel_type Fuel type of the car
*
* @return $this
*/
public function setFuelType($fuel_type)
{
$this->container['fuel_type'] = $fuel_type;
return $this;
}
/**
* Gets made_in
*
* @return string
*/
public function getMadeIn()
{
return $this->container['made_in'];
}
/**
* Sets made_in
*
* @param string $made_in Made in of the car
*
* @return $this
*/
public function setMadeIn($made_in)
{
$this->container['made_in'] = $made_in;
return $this;
}
/**
* Gets engine
*
* @return string
*/
public function getEngine()
{
return $this->container['engine'];
}
/**
* Sets engine
*
* @param string $engine Engine of the car
*
* @return $this
*/
public function setEngine($engine)
{
$this->container['engine'] = $engine;
return $this;
}
/**
* Gets engine_block
*
* @return string
*/
public function getEngineBlock()
{
return $this->container['engine_block'];
}
/**
* Sets engine_block
*
* @param string $engine_block Engine block of the car
*
* @return $this
*/
public function setEngineBlock($engine_block)
{
$this->container['engine_block'] = $engine_block;
return $this;
}
/**
* Gets engine_size
*
* @return string
*/
public function getEngineSize()
{
return $this->container['engine_size'];
}
/**
* Sets engine_size
*
* @param string $engine_size Engine size of the car
*
* @return $this
*/
public function setEngineSize($engine_size)
{
$this->container['engine_size'] = $engine_size;
return $this;
}
/**
* Gets engine_measure
*
* @return string
*/
public function getEngineMeasure()
{
return $this->container['engine_measure'];
}
/**
* Sets engine_measure
*
* @param string $engine_measure Engine block of the car
*
* @return $this
*/
public function setEngineMeasure($engine_measure)
{
$this->container['engine_measure'] = $engine_measure;
return $this;
}
/**
* Gets engine_aspiration
*
* @return string
*/
public function getEngineAspiration()
{
return $this->container['engine_aspiration'];
}
/**
* Sets engine_aspiration
*
* @param string $engine_aspiration Engine aspiration of the car
*
* @return $this
*/
public function setEngineAspiration($engine_aspiration)
{
$this->container['engine_aspiration'] = $engine_aspiration;
return $this;
}
/**
* Gets transmission
*
* @return string
*/
public function getTransmission()
{
return $this->container['transmission'];
}
/**
* Sets transmission
*
* @param string $transmission Transmission of the car
*
* @return $this
*/
public function setTransmission($transmission)
{
$this->container['transmission'] = $transmission;
return $this;
}
/**
* Gets doors
*
* @return float
*/
public function getDoors()
{
return $this->container['doors'];
}
/**
* Sets doors
*
* @param float $doors No of doors of the car
*
* @return $this
*/
public function setDoors($doors)
{
$this->container['doors'] = $doors;
return $this;
}
/**
* Gets cylinders
*
* @return float
*/
public function getCylinders()
{
return $this->container['cylinders'];
}
/**
* Sets cylinders
*
* @param float $cylinders No of cylinders of the car
*
* @return $this
*/
public function setCylinders($cylinders)
{
$this->container['cylinders'] = $cylinders;
return $this;
}
/**
* Gets steering_type
*
* @return string
*/
public function getSteeringType()
{
return $this->container['steering_type'];
}
/**
* Sets steering_type
*
* @param string $steering_type Steering type of the car
*
* @return $this
*/
public function setSteeringType($steering_type)
{
$this->container['steering_type'] = $steering_type;
return $this;
}
/**
* Gets antibrake_sys
*
* @return string
*/
public function getAntibrakeSys()
{
return $this->container['antibrake_sys'];
}
/**
* Sets antibrake_sys
*
* @param string $antibrake_sys Antibrake system of the car
*
* @return $this
*/
public function setAntibrakeSys($antibrake_sys)
{
$this->container['antibrake_sys'] = $antibrake_sys;
return $this;
}
/**
* Gets tank_size
*
* @return string
*/
public function getTankSize()
{
return $this->container['tank_size'];
}
/**
* Sets tank_size
*
* @param string $tank_size Tank size of the car
*
* @return $this
*/
public function setTankSize($tank_size)
{
$this->container['tank_size'] = $tank_size;
return $this;
}
/**
* Gets overall_height
*
* @return string
*/
public function getOverallHeight()
{
return $this->container['overall_height'];
}
/**
* Sets overall_height
*
* @param string $overall_height Overall height of the car
*
* @return $this
*/
public function setOverallHeight($overall_height)
{
$this->container['overall_height'] = $overall_height;
return $this;
}
/**
* Gets overall_length
*
* @return string
*/
public function getOverallLength()
{
return $this->container['overall_length'];
}
/**
* Sets overall_length
*
* @param string $overall_length Overall length of the car
*
* @return $this
*/
public function setOverallLength($overall_length)
{
$this->container['overall_length'] = $overall_length;
return $this;
}
/**
* Gets overall_width
*
* @return string
*/
public function getOverallWidth()
{
return $this->container['overall_width'];
}
/**
* Sets overall_width
*
* @param string $overall_width Overall width of the car
*
* @return $this
*/
public function setOverallWidth($overall_width)
{
$this->container['overall_width'] = $overall_width;
return $this;
}
/**
* Gets std_seating
*
* @return string
*/
public function getStdSeating()
{
return $this->container['std_seating'];
}
/**
* Sets std_seating
*
* @param string $std_seating Std seating of the car
*
* @return $this
*/
public function setStdSeating($std_seating)
{
$this->container['std_seating'] = $std_seating;
return $this;
}
/**
* Gets highway_miles
*
* @return string
*/
public function getHighwayMiles()
{
return $this->container['highway_miles'];
}
/**
* Sets highway_miles
*
* @param string $highway_miles Highway miles of the car
*
* @return $this
*/
public function setHighwayMiles($highway_miles)
{
$this->container['highway_miles'] = $highway_miles;
return $this;
}
/**
* Gets city_miles
*
* @return string
*/
public function getCityMiles()
{
return $this->container['city_miles'];
}
/**
* Sets city_miles
*
* @param string $city_miles City miles of the car
*
* @return $this
*/
public function setCityMiles($city_miles)
{
$this->container['city_miles'] = $city_miles;
return $this;
}
/**
* Returns true if offset exists. False otherwise.
*
* @param integer $offset Offset
*
* @return boolean
*/
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
/**
* Gets offset.
*
* @param integer $offset Offset
*
* @return mixed
*/
public function offsetGet($offset)
{
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
/**
* Sets value based on offset.
*
* @param integer $offset Offset
* @param mixed $value Value to be set
*
* @return void
*/
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
/**
* Unsets offset.
*
* @param integer $offset Offset
*
* @return void
*/
public function offsetUnset($offset)
{
unset($this->container[$offset]);
}
/**
* Gets the string presentation of the object
*
* @return string
*/
public function __toString()
{
if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
return json_encode(
ObjectSerializer::sanitizeForSerialization($this),
JSON_PRETTY_PRINT
);
}
return json_encode(ObjectSerializer::sanitizeForSerialization($this));
}
}
<file_sep>/docs/Api/HistoryApi.md
# marketcheck\api\sdk\HistoryApi
All URIs are relative to *https://marketcheck-prod.apigee.net/v1*
Method | HTTP request | Description
------------- | ------------- | -------------
[**history**](HistoryApi.md#history) | **GET** /history/{vin} | Get a cars online listing history
# **history**
> \marketcheck\api\sdk\Model\HistoricalListing[] history($vin, $api_key, $fields, $page)
Get a cars online listing history
The history API returns online listing history for a car identified by its VIN. History listings are sorted in the descending order of the listing date / last seen date
### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$apiInstance = new marketcheck\api\sdk\Api\HistoryApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client()
);
$vin = "vin_example"; // string | The VIN to identify the car to fetch the listing history. Must be a valid 17 char VIN
$api_key = "api_key_example"; // string | The API Authentication Key. Mandatory with all API calls.
$fields = "fields_example"; // string | List of fields to fetch, in case the default fields list in the response is to be trimmed down
$page = 8.14; // float | Page number to fetch the results for the given criteria. Default is 1.
try {
$result = $apiInstance->history($vin, $api_key, $fields, $page);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling HistoryApi->history: ', $e->getMessage(), PHP_EOL;
}
?>
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**vin** | **string**| The VIN to identify the car to fetch the listing history. Must be a valid 17 char VIN |
**api_key** | **string**| The API Authentication Key. Mandatory with all API calls. | [optional]
**fields** | **string**| List of fields to fetch, in case the default fields list in the response is to be trimmed down | [optional]
**page** | **float**| Page number to fetch the results for the given criteria. Default is 1. | [optional]
### Return type
[**\marketcheck\api\sdk\Model\HistoricalListing[]**](../Model/HistoricalListing.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)
<file_sep>/lib/Model/Listing.php
<?php
/**
* Listing
*
* PHP version 5
*
* @category Class
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Marketcheck Cars API
*
* <b>Access the New, Used and Certified cars inventories for all Car Dealers in US.</b> <br/>The data is sourced from online listings by over 44,000 Car dealers in US. At any time, there are about 6.2M searchable listings (about 1.9M unique VINs) for Used & Certified cars and about 6.6M (about 3.9M unique VINs) New Car listings from all over US. We use this API at the back for our website <a href='https://www.marketcheck.com' target='_blank'>www.marketcheck.com</a> and our Android and iOS mobile apps too.<br/><h5> Few useful links : </h5><ul><li>A quick view of the API and the use cases is depicated <a href='https://portals.marketcheck.com/mcapi/' target='_blank'>here</a></li><li>The Postman collection with various usages of the API is shared here https://www.getpostman.com/collections/2752684ff636cdd7bac2</li></ul>
*
* OpenAPI spec version: 1.0.3
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.0-SNAPSHOT
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
namespace marketcheck\api\sdk\Model;
use \ArrayAccess;
use \marketcheck\api\sdk\ObjectSerializer;
/**
* Listing Class Doc Comment
*
* @category Class
* @description Represents a full list of attributes available with Marketcheck for a car
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class Listing implements ModelInterface, ArrayAccess
{
const DISCRIMINATOR = null;
/**
* The original name of the model.
*
* @var string
*/
protected static $swaggerModelName = 'Listing';
/**
* Array of property to type mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerTypes = [
'id' => 'string',
'heading' => 'string',
'vin' => 'string',
'stock_no' => 'string',
'price' => 'string',
'msrp' => 'string',
'miles' => 'string',
'inventory_type' => 'string',
'scraped_at_date' => 'float',
'first_seen_at' => 'float',
'first_seen_at_date' => 'string',
'vdp_url' => 'string',
'carfax_1_owner' => 'string',
'carfax_clean_title' => 'string',
'source' => 'string',
'is_certified' => 'int',
'dom' => 'float',
'dom_180' => 'float',
'dom_active' => 'float',
'seller_type' => 'string',
'last_seen_at' => 'float',
'last_seen_at_date' => 'string',
'dist' => 'float',
'build' => '\marketcheck\api\sdk\Model\Build',
'media' => '\marketcheck\api\sdk\Model\ListingMedia',
'extra' => '\marketcheck\api\sdk\Model\ListingExtraAttributes',
'dealer' => '\marketcheck\api\sdk\Model\Dealer',
'car_location' => '\marketcheck\api\sdk\Model\Location'
];
/**
* Array of property to format mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerFormats = [
'id' => null,
'heading' => null,
'vin' => null,
'stock_no' => null,
'price' => null,
'msrp' => null,
'miles' => null,
'inventory_type' => null,
'scraped_at_date' => null,
'first_seen_at' => null,
'first_seen_at_date' => null,
'vdp_url' => null,
'carfax_1_owner' => null,
'carfax_clean_title' => null,
'source' => null,
'is_certified' => null,
'dom' => null,
'dom_180' => null,
'dom_active' => null,
'seller_type' => null,
'last_seen_at' => null,
'last_seen_at_date' => null,
'dist' => null,
'build' => null,
'media' => null,
'extra' => null,
'dealer' => null,
'car_location' => null
];
/**
* Array of property to type mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerTypes()
{
return self::$swaggerTypes;
}
/**
* Array of property to format mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerFormats()
{
return self::$swaggerFormats;
}
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @var string[]
*/
protected static $attributeMap = [
'id' => 'id',
'heading' => 'heading',
'vin' => 'vin',
'stock_no' => 'stock_no',
'price' => 'price',
'msrp' => 'msrp',
'miles' => 'miles',
'inventory_type' => 'inventory_type',
'scraped_at_date' => 'scraped_at_date',
'first_seen_at' => 'first_seen_at',
'first_seen_at_date' => 'first_seen_at_date',
'vdp_url' => 'vdp_url',
'carfax_1_owner' => 'carfax_1_owner',
'carfax_clean_title' => 'carfax_clean_title',
'source' => 'source',
'is_certified' => 'is_certified',
'dom' => 'dom',
'dom_180' => 'dom_180',
'dom_active' => 'dom_active',
'seller_type' => 'seller_type',
'last_seen_at' => 'last_seen_at',
'last_seen_at_date' => 'last_seen_at_date',
'dist' => 'dist',
'build' => 'build',
'media' => 'media',
'extra' => 'extra',
'dealer' => 'dealer',
'car_location' => 'car_location'
];
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @var string[]
*/
protected static $setters = [
'id' => 'setId',
'heading' => 'setHeading',
'vin' => 'setVin',
'stock_no' => 'setStockNo',
'price' => 'setPrice',
'msrp' => 'setMsrp',
'miles' => 'setMiles',
'inventory_type' => 'setInventoryType',
'scraped_at_date' => 'setScrapedAtDate',
'first_seen_at' => 'setFirstSeenAt',
'first_seen_at_date' => 'setFirstSeenAtDate',
'vdp_url' => 'setVdpUrl',
'carfax_1_owner' => 'setCarfax1Owner',
'carfax_clean_title' => 'setCarfaxCleanTitle',
'source' => 'setSource',
'is_certified' => 'setIsCertified',
'dom' => 'setDom',
'dom_180' => 'setDom180',
'dom_active' => 'setDomActive',
'seller_type' => 'setSellerType',
'last_seen_at' => 'setLastSeenAt',
'last_seen_at_date' => 'setLastSeenAtDate',
'dist' => 'setDist',
'build' => 'setBuild',
'media' => 'setMedia',
'extra' => 'setExtra',
'dealer' => 'setDealer',
'car_location' => 'setCarLocation'
];
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @var string[]
*/
protected static $getters = [
'id' => 'getId',
'heading' => 'getHeading',
'vin' => 'getVin',
'stock_no' => 'getStockNo',
'price' => 'getPrice',
'msrp' => 'getMsrp',
'miles' => 'getMiles',
'inventory_type' => 'getInventoryType',
'scraped_at_date' => 'getScrapedAtDate',
'first_seen_at' => 'getFirstSeenAt',
'first_seen_at_date' => 'getFirstSeenAtDate',
'vdp_url' => 'getVdpUrl',
'carfax_1_owner' => 'getCarfax1Owner',
'carfax_clean_title' => 'getCarfaxCleanTitle',
'source' => 'getSource',
'is_certified' => 'getIsCertified',
'dom' => 'getDom',
'dom_180' => 'getDom180',
'dom_active' => 'getDomActive',
'seller_type' => 'getSellerType',
'last_seen_at' => 'getLastSeenAt',
'last_seen_at_date' => 'getLastSeenAtDate',
'dist' => 'getDist',
'build' => 'getBuild',
'media' => 'getMedia',
'extra' => 'getExtra',
'dealer' => 'getDealer',
'car_location' => 'getCarLocation'
];
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @return array
*/
public static function attributeMap()
{
return self::$attributeMap;
}
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @return array
*/
public static function setters()
{
return self::$setters;
}
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @return array
*/
public static function getters()
{
return self::$getters;
}
/**
* The original name of the model.
*
* @return string
*/
public function getModelName()
{
return self::$swaggerModelName;
}
/**
* Associative array for storing property values
*
* @var mixed[]
*/
protected $container = [];
/**
* Constructor
*
* @param mixed[] $data Associated array of property values
* initializing the model
*/
public function __construct(array $data = null)
{
$this->container['id'] = isset($data['id']) ? $data['id'] : null;
$this->container['heading'] = isset($data['heading']) ? $data['heading'] : null;
$this->container['vin'] = isset($data['vin']) ? $data['vin'] : null;
$this->container['stock_no'] = isset($data['stock_no']) ? $data['stock_no'] : null;
$this->container['price'] = isset($data['price']) ? $data['price'] : null;
$this->container['msrp'] = isset($data['msrp']) ? $data['msrp'] : null;
$this->container['miles'] = isset($data['miles']) ? $data['miles'] : null;
$this->container['inventory_type'] = isset($data['inventory_type']) ? $data['inventory_type'] : null;
$this->container['scraped_at_date'] = isset($data['scraped_at_date']) ? $data['scraped_at_date'] : null;
$this->container['first_seen_at'] = isset($data['first_seen_at']) ? $data['first_seen_at'] : null;
$this->container['first_seen_at_date'] = isset($data['first_seen_at_date']) ? $data['first_seen_at_date'] : null;
$this->container['vdp_url'] = isset($data['vdp_url']) ? $data['vdp_url'] : null;
$this->container['carfax_1_owner'] = isset($data['carfax_1_owner']) ? $data['carfax_1_owner'] : null;
$this->container['carfax_clean_title'] = isset($data['carfax_clean_title']) ? $data['carfax_clean_title'] : null;
$this->container['source'] = isset($data['source']) ? $data['source'] : null;
$this->container['is_certified'] = isset($data['is_certified']) ? $data['is_certified'] : null;
$this->container['dom'] = isset($data['dom']) ? $data['dom'] : null;
$this->container['dom_180'] = isset($data['dom_180']) ? $data['dom_180'] : null;
$this->container['dom_active'] = isset($data['dom_active']) ? $data['dom_active'] : null;
$this->container['seller_type'] = isset($data['seller_type']) ? $data['seller_type'] : null;
$this->container['last_seen_at'] = isset($data['last_seen_at']) ? $data['last_seen_at'] : null;
$this->container['last_seen_at_date'] = isset($data['last_seen_at_date']) ? $data['last_seen_at_date'] : null;
$this->container['dist'] = isset($data['dist']) ? $data['dist'] : null;
$this->container['build'] = isset($data['build']) ? $data['build'] : null;
$this->container['media'] = isset($data['media']) ? $data['media'] : null;
$this->container['extra'] = isset($data['extra']) ? $data['extra'] : null;
$this->container['dealer'] = isset($data['dealer']) ? $data['dealer'] : null;
$this->container['car_location'] = isset($data['car_location']) ? $data['car_location'] : null;
}
/**
* Show all the invalid properties with reasons.
*
* @return array invalid properties with reasons
*/
public function listInvalidProperties()
{
$invalidProperties = [];
return $invalidProperties;
}
/**
* Validate all the properties in the model
* return true if all passed
*
* @return bool True if all properties are valid
*/
public function valid()
{
return count($this->listInvalidProperties()) === 0;
}
/**
* Gets id
*
* @return string
*/
public function getId()
{
return $this->container['id'];
}
/**
* Sets id
*
* @param string $id Unique identifier representing a specific listing from the Marketcheck database
*
* @return $this
*/
public function setId($id)
{
$this->container['id'] = $id;
return $this;
}
/**
* Gets heading
*
* @return string
*/
public function getHeading()
{
return $this->container['heading'];
}
/**
* Sets heading
*
* @param string $heading Listing heading
*
* @return $this
*/
public function setHeading($heading)
{
$this->container['heading'] = $heading;
return $this;
}
/**
* Gets vin
*
* @return string
*/
public function getVin()
{
return $this->container['vin'];
}
/**
* Sets vin
*
* @param string $vin VIN for the car
*
* @return $this
*/
public function setVin($vin)
{
$this->container['vin'] = $vin;
return $this;
}
/**
* Gets stock_no
*
* @return string
*/
public function getStockNo()
{
return $this->container['stock_no'];
}
/**
* Sets stock_no
*
* @param string $stock_no Stock no of the car
*
* @return $this
*/
public function setStockNo($stock_no)
{
$this->container['stock_no'] = $stock_no;
return $this;
}
/**
* Gets price
*
* @return string
*/
public function getPrice()
{
return $this->container['price'];
}
/**
* Sets price
*
* @param string $price Asking price for the car
*
* @return $this
*/
public function setPrice($price)
{
$this->container['price'] = $price;
return $this;
}
/**
* Gets msrp
*
* @return string
*/
public function getMsrp()
{
return $this->container['msrp'];
}
/**
* Sets msrp
*
* @param string $msrp MSRP for the car
*
* @return $this
*/
public function setMsrp($msrp)
{
$this->container['msrp'] = $msrp;
return $this;
}
/**
* Gets miles
*
* @return string
*/
public function getMiles()
{
return $this->container['miles'];
}
/**
* Sets miles
*
* @param string $miles Odometer reading / reported miles usage for the car
*
* @return $this
*/
public function setMiles($miles)
{
$this->container['miles'] = $miles;
return $this;
}
/**
* Gets inventory_type
*
* @return string
*/
public function getInventoryType()
{
return $this->container['inventory_type'];
}
/**
* Sets inventory_type
*
* @param string $inventory_type Inventory type of car
*
* @return $this
*/
public function setInventoryType($inventory_type)
{
$this->container['inventory_type'] = $inventory_type;
return $this;
}
/**
* Gets scraped_at_date
*
* @return float
*/
public function getScrapedAtDate()
{
return $this->container['scraped_at_date'];
}
/**
* Sets scraped_at_date
*
* @param float $scraped_at_date Listing first seen at first scraped date
*
* @return $this
*/
public function setScrapedAtDate($scraped_at_date)
{
$this->container['scraped_at_date'] = $scraped_at_date;
return $this;
}
/**
* Gets first_seen_at
*
* @return float
*/
public function getFirstSeenAt()
{
return $this->container['first_seen_at'];
}
/**
* Sets first_seen_at
*
* @param float $first_seen_at Listing first seen at first scraped timestamp
*
* @return $this
*/
public function setFirstSeenAt($first_seen_at)
{
$this->container['first_seen_at'] = $first_seen_at;
return $this;
}
/**
* Gets first_seen_at_date
*
* @return string
*/
public function getFirstSeenAtDate()
{
return $this->container['first_seen_at_date'];
}
/**
* Sets first_seen_at_date
*
* @param string $first_seen_at_date Listing first seen at first scraped date
*
* @return $this
*/
public function setFirstSeenAtDate($first_seen_at_date)
{
$this->container['first_seen_at_date'] = $first_seen_at_date;
return $this;
}
/**
* Gets vdp_url
*
* @return string
*/
public function getVdpUrl()
{
return $this->container['vdp_url'];
}
/**
* Sets vdp_url
*
* @param string $vdp_url Vehicle Details Page url of the specific car
*
* @return $this
*/
public function setVdpUrl($vdp_url)
{
$this->container['vdp_url'] = $vdp_url;
return $this;
}
/**
* Gets carfax_1_owner
*
* @return string
*/
public function getCarfax1Owner()
{
return $this->container['carfax_1_owner'];
}
/**
* Sets carfax_1_owner
*
* @param string $carfax_1_owner
*
* @return $this
*/
public function setCarfax1Owner($carfax_1_owner)
{
$this->container['carfax_1_owner'] = $carfax_1_owner;
return $this;
}
/**
* Gets carfax_clean_title
*
* @return string
*/
public function getCarfaxCleanTitle()
{
return $this->container['carfax_clean_title'];
}
/**
* Sets carfax_clean_title
*
* @param string $carfax_clean_title
*
* @return $this
*/
public function setCarfaxCleanTitle($carfax_clean_title)
{
$this->container['carfax_clean_title'] = $carfax_clean_title;
return $this;
}
/**
* Gets source
*
* @return string
*/
public function getSource()
{
return $this->container['source'];
}
/**
* Sets source
*
* @param string $source Source domain of the listing
*
* @return $this
*/
public function setSource($source)
{
$this->container['source'] = $source;
return $this;
}
/**
* Gets is_certified
*
* @return int
*/
public function getIsCertified()
{
return $this->container['is_certified'];
}
/**
* Sets is_certified
*
* @param int $is_certified Flag indicating whether the car is Certified
*
* @return $this
*/
public function setIsCertified($is_certified)
{
$this->container['is_certified'] = $is_certified;
return $this;
}
/**
* Gets dom
*
* @return float
*/
public function getDom()
{
return $this->container['dom'];
}
/**
* Sets dom
*
* @param float $dom Days on Market value for the car based on current and historical listings found in the Marketcheck database for this car
*
* @return $this
*/
public function setDom($dom)
{
$this->container['dom'] = $dom;
return $this;
}
/**
* Gets dom_180
*
* @return float
*/
public function getDom180()
{
return $this->container['dom_180'];
}
/**
* Sets dom_180
*
* @param float $dom_180 Days on Market value for the car based on current and last 6 month listings found in the Marketcheck database for this car
*
* @return $this
*/
public function setDom180($dom_180)
{
$this->container['dom_180'] = $dom_180;
return $this;
}
/**
* Gets dom_active
*
* @return float
*/
public function getDomActive()
{
return $this->container['dom_active'];
}
/**
* Sets dom_active
*
* @param float $dom_active Days on Market value for the car based on current and last 30 days listings found in the Marketcheck database for this car
*
* @return $this
*/
public function setDomActive($dom_active)
{
$this->container['dom_active'] = $dom_active;
return $this;
}
/**
* Gets seller_type
*
* @return string
*/
public function getSellerType()
{
return $this->container['seller_type'];
}
/**
* Sets seller_type
*
* @param string $seller_type Seller type for the car
*
* @return $this
*/
public function setSellerType($seller_type)
{
$this->container['seller_type'] = $seller_type;
return $this;
}
/**
* Gets last_seen_at
*
* @return float
*/
public function getLastSeenAt()
{
return $this->container['last_seen_at'];
}
/**
* Sets last_seen_at
*
* @param float $last_seen_at Listing last seen at (most recent) timestamp
*
* @return $this
*/
public function setLastSeenAt($last_seen_at)
{
$this->container['last_seen_at'] = $last_seen_at;
return $this;
}
/**
* Gets last_seen_at_date
*
* @return string
*/
public function getLastSeenAtDate()
{
return $this->container['last_seen_at_date'];
}
/**
* Sets last_seen_at_date
*
* @param string $last_seen_at_date Listing last seen at (most recent) date
*
* @return $this
*/
public function setLastSeenAtDate($last_seen_at_date)
{
$this->container['last_seen_at_date'] = $last_seen_at_date;
return $this;
}
/**
* Gets dist
*
* @return string
*/
public function getDist()
{
return $this->container['dist'];
}
/**
* Sets dist
*
* @param string $dist
*
* @return $this
*/
public function setDist($dist)
{
$this->container['dist'] = $dist;
return $this;
}
/**
* Gets build
*
* @return \marketcheck\api\sdk\Model\Build
*/
public function getBuild()
{
return $this->container['build'];
}
/**
* Sets build
*
* @param \marketcheck\api\sdk\Model\Build $build Build / Specifications attributes
*
* @return $this
*/
public function setBuild($build)
{
$this->container['build'] = $build;
return $this;
}
/**
* Gets media
*
* @return \marketcheck\api\sdk\Model\ListingMedia
*/
public function getMedia()
{
return $this->container['media'];
}
/**
* Sets media
*
* @param \marketcheck\api\sdk\Model\ListingMedia $media Car Media Attributes - main photo link/url and photo links
*
* @return $this
*/
public function setMedia($media)
{
$this->container['media'] = $media;
return $this;
}
/**
* Gets extra
*
* @return \marketcheck\api\sdk\Model\ListingExtraAttributes
*/
public function getExtra()
{
return $this->container['extra'];
}
/**
* Sets extra
*
* @param \marketcheck\api\sdk\Model\ListingExtraAttributes $extra Extra attributes for the listing - options, features, seller comments etc
*
* @return $this
*/
public function setExtra($extra)
{
$this->container['extra'] = $extra;
return $this;
}
/**
* Gets dealer
*
* @return \marketcheck\api\sdk\Model\Dealer
*/
public function getDealer()
{
return $this->container['dealer'];
}
/**
* Sets dealer
*
* @param \marketcheck\api\sdk\Model\Dealer $dealer dealer
*
* @return $this
*/
public function setDealer($dealer)
{
$this->container['dealer'] = $dealer;
return $this;
}
/**
* Gets car_location
*
* @return \marketcheck\api\sdk\Model\Location
*/
public function getCarLocation()
{
return $this->container['car_location'];
}
/**
* Sets car_location
*
* @param \marketcheck\api\sdk\Model\Location $car_location Car location data. Included only if its a different location to the dealers location
*
* @return $this
*/
public function setCarLocation($car_location)
{
$this->container['car_location'] = $car_location;
return $this;
}
/**
* Returns true if offset exists. False otherwise.
*
* @param integer $offset Offset
*
* @return boolean
*/
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
/**
* Gets offset.
*
* @param integer $offset Offset
*
* @return mixed
*/
public function offsetGet($offset)
{
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
/**
* Sets value based on offset.
*
* @param integer $offset Offset
* @param mixed $value Value to be set
*
* @return void
*/
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
/**
* Unsets offset.
*
* @param integer $offset Offset
*
* @return void
*/
public function offsetUnset($offset)
{
unset($this->container[$offset]);
}
/**
* Gets the string presentation of the object
*
* @return string
*/
public function __toString()
{
if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
return json_encode(
ObjectSerializer::sanitizeForSerialization($this),
JSON_PRETTY_PRINT
);
}
return json_encode(ObjectSerializer::sanitizeForSerialization($this));
}
}
<file_sep>/docs/Model/Dealer.md
# Dealer
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **string** | The unique id associated with the dealer in the Marketcheck database | [optional]
**franchise_id** | **string** | Dealer franchise id | [optional]
**name** | **string** | Name of the dealer | [optional]
**street** | **string** | Street of the dealer | [optional]
**city** | **string** | City of the dealer | [optional]
**state** | **string** | State of the dealer | [optional]
**zip** | **string** | Zip of the dealer | [optional]
**latitude** | **string** | Latutide for the dealer location | [optional]
**longitude** | **string** | Longitude for the dealer location | [optional]
**phone** | **string** | Contact no of the dealer | [optional]
**car_type** | **string** | Car type new|used|certified | [optional]
**target_url_new** | **string** | Target url for the new cars listing | [optional]
**target_url_used** | **string** | Target url for the used cars listing | [optional]
**target_url_certified** | **string** | Target url for the certified cars listing | [optional]
**dealer_type** | **string** | Dealer type - independent, franchise, multi-brand, authorized | [optional] [default to 'independent']
**rating** | **float** | Overall rating of the dealership on scale 1-5 | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
<file_sep>/lib/Api/DealerApi.php
<?php
/**
* DealerApi
* PHP version 5
*
* @category Class
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Marketcheck Cars API
*
* <b>Access the New, Used and Certified cars inventories for all Car Dealers in US.</b> <br/>The data is sourced from online listings by over 44,000 Car dealers in US. At any time, there are about 6.2M searchable listings (about 1.9M unique VINs) for Used & Certified cars and about 6.6M (about 3.9M unique VINs) New Car listings from all over US. We use this API at the back for our website <a href='https://www.marketcheck.com' target='_blank'>www.marketcheck.com</a> and our Android and iOS mobile apps too.<br/><h5> Few useful links : </h5><ul><li>A quick view of the API and the use cases is depicated <a href='https://portals.marketcheck.com/mcapi/' target='_blank'>here</a></li><li>The Postman collection with various usages of the API is shared here https://www.getpostman.com/collections/2752684ff636cdd7bac2</li></ul>
*
* OpenAPI spec version: 1.0.3
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.0-SNAPSHOT
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
namespace marketcheck\api\sdk\Api;
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
use marketcheck\api\sdk\ApiException;
use marketcheck\api\sdk\Configuration;
use marketcheck\api\sdk\HeaderSelector;
use marketcheck\api\sdk\ObjectSerializer;
/**
* DealerApi Class Doc Comment
*
* @category Class
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class DealerApi
{
/**
* @var ClientInterface
*/
protected $client;
/**
* @var Configuration
*/
protected $config;
/**
* @var HeaderSelector
*/
protected $headerSelector;
/**
* @param ClientInterface $client
* @param Configuration $config
* @param HeaderSelector $selector
*/
public function __construct(
ClientInterface $client = null,
Configuration $config = null,
HeaderSelector $selector = null
) {
$this->client = $client ?: new Client();
$this->config = $config ?: new Configuration();
$this->headerSelector = $selector ?: new HeaderSelector();
}
/**
* @return Configuration
*/
public function getConfig()
{
return $this->config;
}
/**
* Operation dealerSearch
*
* Find car dealers around
*
* @param double $latitude Latitude component of location (required)
* @param double $longitude Longitude component of location (required)
* @param int $radius Radius around the search location (required)
* @param string $api_key The API Authentication Key. Mandatory with all API calls. (optional)
* @param float $rows Number of results to return. Default is 10. Max is 50 (optional)
* @param float $start Offset for the search results. Default is 1. (optional)
*
* @throws \marketcheck\api\sdk\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return \marketcheck\api\sdk\Model\DealersResponse
*/
public function dealerSearch($latitude, $longitude, $radius, $api_key = null, $rows = null, $start = null)
{
list($response) = $this->dealerSearchWithHttpInfo($latitude, $longitude, $radius, $api_key, $rows, $start);
return $response;
}
/**
* Operation dealerSearchWithHttpInfo
*
* Find car dealers around
*
* @param double $latitude Latitude component of location (required)
* @param double $longitude Longitude component of location (required)
* @param int $radius Radius around the search location (required)
* @param string $api_key The API Authentication Key. Mandatory with all API calls. (optional)
* @param float $rows Number of results to return. Default is 10. Max is 50 (optional)
* @param float $start Offset for the search results. Default is 1. (optional)
*
* @throws \marketcheck\api\sdk\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return array of \marketcheck\api\sdk\Model\DealersResponse, HTTP status code, HTTP response headers (array of strings)
*/
public function dealerSearchWithHttpInfo($latitude, $longitude, $radius, $api_key = null, $rows = null, $start = null)
{
$returnType = '\marketcheck\api\sdk\Model\DealersResponse';
$request = $this->dealerSearchRequest($latitude, $longitude, $radius, $api_key, $rows, $start);
try {
$options = $this->createHttpClientOption();
try {
$response = $this->client->send($request, $options);
} catch (RequestException $e) {
throw new ApiException(
"[{$e->getCode()}] {$e->getMessage()}",
$e->getCode(),
$e->getResponse() ? $e->getResponse()->getHeaders() : null,
$e->getResponse() ? $e->getResponse()->getBody()->getContents() : null
);
}
$statusCode = $response->getStatusCode();
if ($statusCode < 200 || $statusCode > 299) {
throw new ApiException(
sprintf(
'[%d] Error connecting to the API (%s)',
$statusCode,
$request->getUri()
),
$statusCode,
$response->getHeaders(),
$response->getBody()
);
}
$responseBody = $response->getBody();
if ($returnType === '\SplFileObject') {
$content = $responseBody; //stream goes to serializer
} else {
$content = $responseBody->getContents();
if ($returnType !== 'string') {
$content = json_decode($content);
}
}
return [
ObjectSerializer::deserialize($content, $returnType, []),
$response->getStatusCode(),
$response->getHeaders()
];
} catch (ApiException $e) {
switch ($e->getCode()) {
case 200:
$data = ObjectSerializer::deserialize(
$e->getResponseBody(),
'\marketcheck\api\sdk\Model\DealersResponse',
$e->getResponseHeaders()
);
$e->setResponseObject($data);
break;
default:
$data = ObjectSerializer::deserialize(
$e->getResponseBody(),
'\marketcheck\api\sdk\Model\Error',
$e->getResponseHeaders()
);
$e->setResponseObject($data);
break;
}
throw $e;
}
}
/**
* Operation dealerSearchAsync
*
* Find car dealers around
*
* @param double $latitude Latitude component of location (required)
* @param double $longitude Longitude component of location (required)
* @param int $radius Radius around the search location (required)
* @param string $api_key The API Authentication Key. Mandatory with all API calls. (optional)
* @param float $rows Number of results to return. Default is 10. Max is 50 (optional)
* @param float $start Offset for the search results. Default is 1. (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function dealerSearchAsync($latitude, $longitude, $radius, $api_key = null, $rows = null, $start = null)
{
return $this->dealerSearchAsyncWithHttpInfo($latitude, $longitude, $radius, $api_key, $rows, $start)
->then(
function ($response) {
return $response[0];
}
);
}
/**
* Operation dealerSearchAsyncWithHttpInfo
*
* Find car dealers around
*
* @param double $latitude Latitude component of location (required)
* @param double $longitude Longitude component of location (required)
* @param int $radius Radius around the search location (required)
* @param string $api_key The API Authentication Key. Mandatory with all API calls. (optional)
* @param float $rows Number of results to return. Default is 10. Max is 50 (optional)
* @param float $start Offset for the search results. Default is 1. (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function dealerSearchAsyncWithHttpInfo($latitude, $longitude, $radius, $api_key = null, $rows = null, $start = null)
{
$returnType = '\marketcheck\api\sdk\Model\DealersResponse';
$request = $this->dealerSearchRequest($latitude, $longitude, $radius, $api_key, $rows, $start);
return $this->client
->sendAsync($request, $this->createHttpClientOption())
->then(
function ($response) use ($returnType) {
$responseBody = $response->getBody();
if ($returnType === '\SplFileObject') {
$content = $responseBody; //stream goes to serializer
} else {
$content = $responseBody->getContents();
if ($returnType !== 'string') {
$content = json_decode($content);
}
}
return [
ObjectSerializer::deserialize($content, $returnType, []),
$response->getStatusCode(),
$response->getHeaders()
];
},
function ($exception) {
$response = $exception->getResponse();
$statusCode = $response->getStatusCode();
throw new ApiException(
sprintf(
'[%d] Error connecting to the API (%s)',
$statusCode,
$exception->getRequest()->getUri()
),
$statusCode,
$response->getHeaders(),
$response->getBody()
);
}
);
}
/**
* Create request for operation 'dealerSearch'
*
* @param double $latitude Latitude component of location (required)
* @param double $longitude Longitude component of location (required)
* @param int $radius Radius around the search location (required)
* @param string $api_key The API Authentication Key. Mandatory with all API calls. (optional)
* @param float $rows Number of results to return. Default is 10. Max is 50 (optional)
* @param float $start Offset for the search results. Default is 1. (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Psr7\Request
*/
protected function dealerSearchRequest($latitude, $longitude, $radius, $api_key = null, $rows = null, $start = null)
{
// verify the required parameter 'latitude' is set
if ($latitude === null || (is_array($latitude) && count($latitude) === 0)) {
throw new \InvalidArgumentException(
'Missing the required parameter $latitude when calling dealerSearch'
);
}
// verify the required parameter 'longitude' is set
if ($longitude === null || (is_array($longitude) && count($longitude) === 0)) {
throw new \InvalidArgumentException(
'Missing the required parameter $longitude when calling dealerSearch'
);
}
// verify the required parameter 'radius' is set
if ($radius === null || (is_array($radius) && count($radius) === 0)) {
throw new \InvalidArgumentException(
'Missing the required parameter $radius when calling dealerSearch'
);
}
$resourcePath = '/dealers';
$formParams = [];
$queryParams = [];
$headerParams = [];
$httpBody = '';
$multipart = false;
// query params
if ($api_key !== null) {
$queryParams['api_key'] = ObjectSerializer::toQueryValue($api_key);
}
// query params
if ($latitude !== null) {
$queryParams['latitude'] = ObjectSerializer::toQueryValue($latitude);
}
// query params
if ($longitude !== null) {
$queryParams['longitude'] = ObjectSerializer::toQueryValue($longitude);
}
// query params
if ($radius !== null) {
$queryParams['radius'] = ObjectSerializer::toQueryValue($radius);
}
// query params
if ($rows !== null) {
$queryParams['rows'] = ObjectSerializer::toQueryValue($rows);
}
// query params
if ($start !== null) {
$queryParams['start'] = ObjectSerializer::toQueryValue($start);
}
// body params
$_tempBody = null;
if ($multipart) {
$headers = $this->headerSelector->selectHeadersForMultipart(
['application/json']
);
} else {
$headers = $this->headerSelector->selectHeaders(
['application/json'],
[]
);
}
// for model (json/xml)
if (isset($_tempBody)) {
// $_tempBody is the method argument, if present
$httpBody = $_tempBody;
// \stdClass has no __toString(), so we should encode it manually
if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode($httpBody);
}
} elseif (count($formParams) > 0) {
if ($multipart) {
$multipartContents = [];
foreach ($formParams as $formParamName => $formParamValue) {
$multipartContents[] = [
'name' => $formParamName,
'contents' => $formParamValue
];
}
// for HTTP post (form)
$httpBody = new MultipartStream($multipartContents);
} elseif ($headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode($formParams);
} else {
// for HTTP post (form)
$httpBody = \GuzzleHttp\Psr7\build_query($formParams);
}
}
$defaultHeaders = [];
if ($this->config->getUserAgent()) {
$defaultHeaders['User-Agent'] = $this->config->getUserAgent();
}
$headers = array_merge(
$defaultHeaders,
$headerParams,
$headers
);
$query = \GuzzleHttp\Psr7\build_query($queryParams);
return new Request(
'GET',
$this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
$headers,
$httpBody
);
}
/**
* Operation getDealer
*
* Dealer by id
*
* @param string $dealer_id Dealer id to get all the dealer info attributes (required)
* @param string $api_key The API Authentication Key. Mandatory with all API calls. (optional)
*
* @throws \marketcheck\api\sdk\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return \marketcheck\api\sdk\Model\Dealer
*/
public function getDealer($dealer_id, $api_key = null)
{
list($response) = $this->getDealerWithHttpInfo($dealer_id, $api_key);
return $response;
}
/**
* Operation getDealerWithHttpInfo
*
* Dealer by id
*
* @param string $dealer_id Dealer id to get all the dealer info attributes (required)
* @param string $api_key The API Authentication Key. Mandatory with all API calls. (optional)
*
* @throws \marketcheck\api\sdk\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return array of \marketcheck\api\sdk\Model\Dealer, HTTP status code, HTTP response headers (array of strings)
*/
public function getDealerWithHttpInfo($dealer_id, $api_key = null)
{
$returnType = '\marketcheck\api\sdk\Model\Dealer';
$request = $this->getDealerRequest($dealer_id, $api_key);
try {
$options = $this->createHttpClientOption();
try {
$response = $this->client->send($request, $options);
} catch (RequestException $e) {
throw new ApiException(
"[{$e->getCode()}] {$e->getMessage()}",
$e->getCode(),
$e->getResponse() ? $e->getResponse()->getHeaders() : null,
$e->getResponse() ? $e->getResponse()->getBody()->getContents() : null
);
}
$statusCode = $response->getStatusCode();
if ($statusCode < 200 || $statusCode > 299) {
throw new ApiException(
sprintf(
'[%d] Error connecting to the API (%s)',
$statusCode,
$request->getUri()
),
$statusCode,
$response->getHeaders(),
$response->getBody()
);
}
$responseBody = $response->getBody();
if ($returnType === '\SplFileObject') {
$content = $responseBody; //stream goes to serializer
} else {
$content = $responseBody->getContents();
if ($returnType !== 'string') {
$content = json_decode($content);
}
}
return [
ObjectSerializer::deserialize($content, $returnType, []),
$response->getStatusCode(),
$response->getHeaders()
];
} catch (ApiException $e) {
switch ($e->getCode()) {
case 200:
$data = ObjectSerializer::deserialize(
$e->getResponseBody(),
'\marketcheck\api\sdk\Model\Dealer',
$e->getResponseHeaders()
);
$e->setResponseObject($data);
break;
default:
$data = ObjectSerializer::deserialize(
$e->getResponseBody(),
'\marketcheck\api\sdk\Model\Error',
$e->getResponseHeaders()
);
$e->setResponseObject($data);
break;
}
throw $e;
}
}
/**
* Operation getDealerAsync
*
* Dealer by id
*
* @param string $dealer_id Dealer id to get all the dealer info attributes (required)
* @param string $api_key The API Authentication Key. Mandatory with all API calls. (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function getDealerAsync($dealer_id, $api_key = null)
{
return $this->getDealerAsyncWithHttpInfo($dealer_id, $api_key)
->then(
function ($response) {
return $response[0];
}
);
}
/**
* Operation getDealerAsyncWithHttpInfo
*
* Dealer by id
*
* @param string $dealer_id Dealer id to get all the dealer info attributes (required)
* @param string $api_key The API Authentication Key. Mandatory with all API calls. (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function getDealerAsyncWithHttpInfo($dealer_id, $api_key = null)
{
$returnType = '\marketcheck\api\sdk\Model\Dealer';
$request = $this->getDealerRequest($dealer_id, $api_key);
return $this->client
->sendAsync($request, $this->createHttpClientOption())
->then(
function ($response) use ($returnType) {
$responseBody = $response->getBody();
if ($returnType === '\SplFileObject') {
$content = $responseBody; //stream goes to serializer
} else {
$content = $responseBody->getContents();
if ($returnType !== 'string') {
$content = json_decode($content);
}
}
return [
ObjectSerializer::deserialize($content, $returnType, []),
$response->getStatusCode(),
$response->getHeaders()
];
},
function ($exception) {
$response = $exception->getResponse();
$statusCode = $response->getStatusCode();
throw new ApiException(
sprintf(
'[%d] Error connecting to the API (%s)',
$statusCode,
$exception->getRequest()->getUri()
),
$statusCode,
$response->getHeaders(),
$response->getBody()
);
}
);
}
/**
* Create request for operation 'getDealer'
*
* @param string $dealer_id Dealer id to get all the dealer info attributes (required)
* @param string $api_key The API Authentication Key. Mandatory with all API calls. (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Psr7\Request
*/
protected function getDealerRequest($dealer_id, $api_key = null)
{
// verify the required parameter 'dealer_id' is set
if ($dealer_id === null || (is_array($dealer_id) && count($dealer_id) === 0)) {
throw new \InvalidArgumentException(
'Missing the required parameter $dealer_id when calling getDealer'
);
}
$resourcePath = '/dealer/{dealer_id}';
$formParams = [];
$queryParams = [];
$headerParams = [];
$httpBody = '';
$multipart = false;
// query params
if ($api_key !== null) {
$queryParams['api_key'] = ObjectSerializer::toQueryValue($api_key);
}
// path params
if ($dealer_id !== null) {
$resourcePath = str_replace(
'{' . 'dealer_id' . '}',
ObjectSerializer::toPathValue($dealer_id),
$resourcePath
);
}
// body params
$_tempBody = null;
if ($multipart) {
$headers = $this->headerSelector->selectHeadersForMultipart(
['application/json']
);
} else {
$headers = $this->headerSelector->selectHeaders(
['application/json'],
[]
);
}
// for model (json/xml)
if (isset($_tempBody)) {
// $_tempBody is the method argument, if present
$httpBody = $_tempBody;
// \stdClass has no __toString(), so we should encode it manually
if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode($httpBody);
}
} elseif (count($formParams) > 0) {
if ($multipart) {
$multipartContents = [];
foreach ($formParams as $formParamName => $formParamValue) {
$multipartContents[] = [
'name' => $formParamName,
'contents' => $formParamValue
];
}
// for HTTP post (form)
$httpBody = new MultipartStream($multipartContents);
} elseif ($headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode($formParams);
} else {
// for HTTP post (form)
$httpBody = \GuzzleHttp\Psr7\build_query($formParams);
}
}
$defaultHeaders = [];
if ($this->config->getUserAgent()) {
$defaultHeaders['User-Agent'] = $this->config->getUserAgent();
}
$headers = array_merge(
$defaultHeaders,
$headerParams,
$headers
);
$query = \GuzzleHttp\Psr7\build_query($queryParams);
return new Request(
'GET',
$this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
$headers,
$httpBody
);
}
/**
* Create http client option
*
* @throws \RuntimeException on file opening failure
* @return array of http client options
*/
protected function createHttpClientOption()
{
$options = [];
if ($this->config->getDebug()) {
$options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a');
if (!$options[RequestOptions::DEBUG]) {
throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile());
}
}
return $options;
}
}
<file_sep>/lib/ApiException.php
<?php
/**
* ApiException
* PHP version 5
*
* @category Class
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Marketcheck Cars API
*
* <b>Access the New, Used and Certified cars inventories for all Car Dealers in US.</b> <br/>The data is sourced from online listings by over 44,000 Car dealers in US. At any time, there are about 6.2M searchable listings (about 1.9M unique VINs) for Used & Certified cars and about 6.6M (about 3.9M unique VINs) New Car listings from all over US. We use this API at the back for our website <a href='https://www.marketcheck.com' target='_blank'>www.marketcheck.com</a> and our Android and iOS mobile apps too.<br/><h5> Few useful links : </h5><ul><li>A quick view of the API and the use cases is depicated <a href='https://portals.marketcheck.com/mcapi/' target='_blank'>here</a></li><li>The Postman collection with various usages of the API is shared here https://www.getpostman.com/collections/2752684ff636cdd7bac2</li></ul>
*
* OpenAPI spec version: 1.0.3
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.0-SNAPSHOT
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
namespace marketcheck\api\sdk;
use \Exception;
/**
* ApiException Class Doc Comment
*
* @category Class
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class ApiException extends Exception
{
/**
* The HTTP body of the server response either as Json or string.
*
* @var mixed
*/
protected $responseBody;
/**
* The HTTP header of the server response.
*
* @var string[]|null
*/
protected $responseHeaders;
/**
* The deserialized response object
*
* @var $responseObject;
*/
protected $responseObject;
/**
* Constructor
*
* @param string $message Error message
* @param int $code HTTP status code
* @param string[]|null $responseHeaders HTTP response header
* @param mixed $responseBody HTTP decoded body of the server response either as \stdClass or string
*/
public function __construct($message = "", $code = 0, $responseHeaders = [], $responseBody = null)
{
parent::__construct($message, $code);
$this->responseHeaders = $responseHeaders;
$this->responseBody = $responseBody;
}
/**
* Gets the HTTP response header
*
* @return string[]|null HTTP response header
*/
public function getResponseHeaders()
{
return $this->responseHeaders;
}
/**
* Gets the HTTP body of the server response either as Json or string
*
* @return mixed HTTP body of the server response either as \stdClass or string
*/
public function getResponseBody()
{
return $this->responseBody;
}
/**
* Sets the deseralized response object (during deserialization)
*
* @param mixed $obj Deserialized response object
*
* @return void
*/
public function setResponseObject($obj)
{
$this->responseObject = $obj;
}
/**
* Gets the deseralized response object (during deserialization)
*
* @return mixed the deserialized response object
*/
public function getResponseObject()
{
return $this->responseObject;
}
}
<file_sep>/docs/Model/HistoricalListing.md
# HistoricalListing
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **string** | Unique identifier representing a specific listing from the Marketcheck database | [optional]
**price** | **string** | Asking price for the car | [optional]
**msrp** | **string** | MSRP for the car | [optional]
**miles** | **string** | Odometer reading / reported miles usage for the car | [optional]
**vdp_url** | **string** | Vehicle Details Page url of the specific car | [optional]
**seller_name** | **string** | Seller name of the listing from the Marketcheck database | [optional]
**scraped_at** | **float** | Listing scraped at timestamp | [optional]
**last_seen_at** | **float** | Listing last seen at (most recent) timestamp | [optional]
**source** | **string** | Source website for the listing | [optional]
**city** | **string** | City of the listing | [optional]
**state** | **string** | State of the listing | [optional]
**zip** | **string** | Zip of the listing | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
<file_sep>/docs/Model/ListingExtraAttributes.md
# ListingExtraAttributes
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**options** | **string[]** | Installed Options of the car | [optional]
**features** | **string[]** | List of Features available with the car | [optional]
**seller_comment** | **string** | Seller comment for the car | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
<file_sep>/test/Api/DealerApiTest.php
<?php
/**
* DealerApiTest
* PHP version 5
*
* @category Class
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Marketcheck Cars API
*
* <b>Access the New, Used and Certified cars inventories for all Car Dealers in US.</b> <br/>The data is sourced from online listings by over 44,000 Car dealers in US. At any time, there are about 6.2M searchable listings (about 1.9M unique VINs) for Used & Certified cars and about 6.6M (about 3.9M unique VINs) New Car listings from all over US. We use this API at the back for our website <a href='https://www.marketcheck.com' target='_blank'>www.marketcheck.com</a> and our Android and iOS mobile apps too.<br/><h5> Few useful links : </h5><ul><li>A quick view of the API and the use cases is depicated <a href='https://portals.marketcheck.com/mcapi/' target='_blank'>here</a></li><li>The Postman collection with various usages of the API is shared here https://www.getpostman.com/collections/2752684ff636cdd7bac2</li></ul>
*
* OpenAPI spec version: 1.0.3
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.0-SNAPSHOT
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Please update the test case below to test the endpoint.
*/
require __DIR__.'/../../vendor/autoload.php';
require __DIR__.'/../../lib/Api/DealerApi.php';
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
use \marketcheck\api\sdk\Configuration;
use \marketcheck\api\sdk\ApiException;
use \marketcheck\api\sdk\ObjectSerializer;
/**
* DealerApiTest Class Doc Comment
*
* @category Class
* @package marketcheck\api\sdk
* @author <NAME>
* @link https://github.com/swagger-api/swagger-codegen
*/
class DealerApiTest extends \PHPUnit_Framework_TestCase
{
private $dealer_id = array("1016810","1016017","1016710","1017138","1016732");
private $api_key = "Your api key";
private $latitude;
private $longitude;
private $radius;
private $rows;
private $start;
/**
* Setup before running any test cases
*/
public static function setUpBeforeClass()
{
}
/**
* Setup before running each test case
*/
public function setUp()
{
}
/**
* Clean up after running each test case
*/
public function tearDown()
{
}
/**
* Clean up after running all test cases
*/
public static function tearDownAfterClass()
{
}
/**
* Test case for dealerSearch
*
* Find car dealers around.
*
*/
public function testDealerSearch()
{
$apiInstance = new marketcheck\api\sdk\Api\DealerApi(new GuzzleHttp\Client());
$dummy_test_data = array
(
array
(
"latitude" => 35,
"longitude" => -90,
"radius" => array // radius array contains radius value and expected dealer count
(
[20,126],
[30,228],
[50,255]
)
),
array
(
"latitude" => 40,
"longitude" => -80,
"radius" => array
(
[20,25],
[30,97],
[50,359]
)
),
array
(
"latitude" => 45,
"longitude" => -90,
"radius" => array
(
[20,3],
[30,34],
[50,74]
)
)
);
echo "\nValidating Dealers count";
$limit = 10;
foreach($dummy_test_data as $test_data)
{
foreach($test_data["radius"] as $dealer_data)
{
try
{
$this->latitude = $test_data["latitude"];
$this->longitude = $test_data["longitude"];
$this->radius = $dealer_data[0];
$this->expected_dealer_count = $dealer_data[1];
$result = $apiInstance->dealerSearch($this->latitude, $this->longitude, $this->radius, $this->api_key);
$lower_limit = $this->expected_dealer_count - (($limit * $this->expected_dealer_count)/100);
$upper_limit = $this->expected_dealer_count + (($limit * $this->expected_dealer_count)/100);
$api_dealer_cnt = $result["num_found"];
$this->assertGreaterThanOrEqual($lower_limit,$api_dealer_cnt);
$this->assertLessThanOrEqual($upper_limit,$api_dealer_cnt);
print_r("\n/dealers?api_key={{api_key}}&latitude=$this->latitude&longitude=$this->longitude&radius=$this->radius: endpoint working fine");
} catch (Exception $e) {
$this->fail($e->getMessage());
}
}
}
}
/**
* Test case for getDealer
*
* Dealer by id.
*
*/
public function testGetDealer()
{
echo "\nValidating dealers on the basis of dealer id";
$apiInstance = new marketcheck\api\sdk\Api\DealerApi(new GuzzleHttp\Client());
foreach($this->dealer_id as $d_id)
{
try
{
$result = $apiInstance->getDealer($d_id, $this->api_key);
$this->assertEquals($result["id"], $d_id);
print_r("\n/dealer/$d_id?api_key={{api_key}}: endpoint working fine");
} catch (Exception $e) {
$this->fail($e->getMessage());
}
}
}
}
<file_sep>/docs/Model/Listing.md
# Listing
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **string** | Unique identifier representing a specific listing from the Marketcheck database | [optional]
**heading** | **string** | Listing heading | [optional]
**vin** | **string** | VIN for the car | [optional]
**stock_no** | **string** | Stock no of the car | [optional]
**price** | **string** | Asking price for the car | [optional]
**msrp** | **string** | MSRP for the car | [optional]
**miles** | **string** | Odometer reading / reported miles usage for the car | [optional]
**inventory_type** | **string** | Inventory type of car | [optional]
**scraped_at_date** | **float** | Listing first seen at first scraped date | [optional]
**first_seen_at** | **float** | Listing first seen at first scraped timestamp | [optional]
**first_seen_at_date** | **string** | Listing first seen at first scraped date | [optional]
**vdp_url** | **string** | Vehicle Details Page url of the specific car | [optional]
**source** | **string** | Source domain of the listing | [optional]
**is_certified** | **int** | Flag indicating whether the car is Certified | [optional]
**dom** | **float** | Days on Market value for the car based on current and historical listings found in the Marketcheck database for this car | [optional]
**dom_180** | **float** | Days on Market value for the car based on current and last 6 month listings found in the Marketcheck database for this car | [optional]
**dom_active** | **float** | Days on Market value for the car based on current and last 30 days listings found in the Marketcheck database for this car | [optional]
**seller_type** | **string** | Seller type for the car | [optional]
**last_seen_at** | **float** | Listing last seen at (most recent) timestamp | [optional]
**last_seen_at_date** | **string** | Listing last seen at (most recent) date | [optional]
**build** | [**\marketcheck\api\sdk\Model\Build**](Build.md) | Build / Specifications attributes | [optional]
**media** | [**\marketcheck\api\sdk\Model\ListingMedia**](ListingMedia.md) | Car Media Attributes - main photo link/url and photo links | [optional]
**extra** | [**\marketcheck\api\sdk\Model\ListingExtraAttributes**](ListingExtraAttributes.md) | Extra attributes for the listing - options, features, seller comments etc | [optional]
**dealer** | [**\marketcheck\api\sdk\Model\Dealer**](Dealer.md) | | [optional]
**car_location** | [**\marketcheck\api\sdk\Model\Location**](Location.md) | Car location data. Included only if its a different location to the dealers location | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
<file_sep>/test/Model/MdsTest.php
<?php
/**
* MdsTest
*
* PHP version 5
*
* @category Class
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Marketcheck Cars API
*
* <b>Access the New, Used and Certified cars inventories for all Car Dealers in US.</b> <br/>The data is sourced from online listings by over 44,000 Car dealers in US. At any time, there are about 6.2M searchable listings (about 1.9M unique VINs) for Used & Certified cars and about 6.6M (about 3.9M unique VINs) New Car listings from all over US. We use this API at the back for our website <a href='https://www.marketcheck.com' target='_blank'>www.marketcheck.com</a> and our Android and iOS mobile apps too.<br/><h5> Few useful links : </h5><ul><li>A quick view of the API and the use cases is depicated <a href='https://portals.marketcheck.com/mcapi/' target='_blank'>here</a></li><li>The Postman collection with various usages of the API is shared here https://www.getpostman.com/collections/2752684ff636cdd7bac2</li></ul>
*
* OpenAPI spec version: 1.0.3
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.0-SNAPSHOT
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Please update the test case below to test the model.
*/
namespace marketcheck\api\sdk;
/**
* MdsTest Class Doc Comment
*
* @category Class
* @description Describes Market days supply results for year make model trim combination
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class MdsTest extends \PHPUnit_Framework_TestCase
{
/**
* Setup before running any test case
*/
public static function setUpBeforeClass()
{
}
/**
* Setup before running each test case
*/
public function setUp()
{
}
/**
* Clean up after running each test case
*/
public function tearDown()
{
}
/**
* Clean up after running all test cases
*/
public static function tearDownAfterClass()
{
}
/**
* Test "Mds"
*/
public function testMds()
{
}
/**
* Test attribute "mds"
*/
public function testPropertyMds()
{
}
/**
* Test attribute "total_active_cars_for_ymmt"
*/
public function testPropertyTotalActiveCarsForYmmt()
{
}
/**
* Test attribute "total_cars_sold_in_last_45_days"
*/
public function testPropertyTotalCarsSoldInLast45Days()
{
}
/**
* Test attribute "sold_vins"
*/
public function testPropertySoldVins()
{
}
/**
* Test attribute "year"
*/
public function testPropertyYear()
{
}
/**
* Test attribute "make"
*/
public function testPropertyMake()
{
}
/**
* Test attribute "model"
*/
public function testPropertyModel()
{
}
/**
* Test attribute "trim"
*/
public function testPropertyTrim()
{
}
}
<file_sep>/test/Api/VINDecoderApiTest.php
<?php
/**
* VINDecoderApiTest
* PHP version 5
*
* @category Class
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Marketcheck Cars API
*
* <b>Access the New, Used and Certified cars inventories for all Car Dealers in US.</b> <br/>The data is sourced from online listings by over 44,000 Car dealers in US. At any time, there are about 6.2M searchable listings (about 1.9M unique VINs) for Used & Certified cars and about 6.6M (about 3.9M unique VINs) New Car listings from all over US. We use this API at the back for our website <a href='https://www.marketcheck.com' target='_blank'>www.marketcheck.com</a> and our Android and iOS mobile apps too.<br/><h5> Few useful links : </h5><ul><li>A quick view of the API and the use cases is depicated <a href='https://portals.marketcheck.com/mcapi/' target='_blank'>here</a></li><li>The Postman collection with various usages of the API is shared here https://www.getpostman.com/collections/2752684ff636cdd7bac2</li></ul>
*
* OpenAPI spec version: 1.0.3
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.0-SNAPSHOT
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Please update the test case below to test the endpoint.
*/
require __DIR__.'/../../vendor/autoload.php';
require __DIR__.'/../../lib/Api/VINDecoderApi.php';
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
use \marketcheck\api\sdk\Configuration;
use \marketcheck\api\sdk\ApiException;
use \marketcheck\api\sdk\ObjectSerializer;
/**
* VINDecoderApiTest Class Doc Comment
*
* @category Class
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class VINDecoderApiTest extends \PHPUnit_Framework_TestCase
{
private $vin;
private $api_key = "Your api key";
/**
* Setup before running any test cases
*/
public static function setUpBeforeClass()
{
}
/**
* Setup before running each test case
*/
public function setUp()
{
}
/**
* Clean up after running each test case
*/
public function tearDown()
{
}
/**
* Clean up after running all test cases
*/
public static function tearDownAfterClass()
{
}
/**
* Test case for decode
*
* VIN Decoder.
*
*/
public function testDecode()
{
$apiInstance = new marketcheck\api\sdk\Api\VINDecoderApi(new GuzzleHttp\Client());
echo "\nTesting Vindecoder";
$this->vin = "1FAHP3F28CL148530";
try {
$result = $apiInstance->decode($this->vin, $this->api_key);
$this->assertEquals($result["make"], "Ford");
$this->assertEquals($result["year"], 2012);
$this->assertEquals($result["model"], "Focus");
print_r("\n/vin/$this->vin/specs?api_key={{api_key}}: endpoint working fine");
} catch (Exception $e) {
$this->fail($e->getMessage());
}
}
}
<file_sep>/lib/Model/BaseListing.php
<?php
/**
* BaseListing
*
* PHP version 5
*
* @category Class
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Marketcheck Cars API
*
* <b>Access the New, Used and Certified cars inventories for all Car Dealers in US.</b> <br/>The data is sourced from online listings by over 44,000 Car dealers in US. At any time, there are about 6.2M searchable listings (about 1.9M unique VINs) for Used & Certified cars and about 6.6M (about 3.9M unique VINs) New Car listings from all over US. We use this API at the back for our website <a href='https://www.marketcheck.com' target='_blank'>www.marketcheck.com</a> and our Android and iOS mobile apps too.<br/><h5> Few useful links : </h5><ul><li>A quick view of the API and the use cases is depicated <a href='https://portals.marketcheck.com/mcapi/' target='_blank'>here</a></li><li>The Postman collection with various usages of the API is shared here https://www.getpostman.com/collections/2752684ff636cdd7bac2</li></ul>
*
* OpenAPI spec version: 1.0.3
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.0-SNAPSHOT
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
namespace marketcheck\api\sdk\Model;
use \ArrayAccess;
use \marketcheck\api\sdk\ObjectSerializer;
/**
* BaseListing Class Doc Comment
*
* @category Class
* @description Minimal set of attributes describing a listing
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class BaseListing implements ModelInterface, ArrayAccess
{
const DISCRIMINATOR = null;
/**
* The original name of the model.
*
* @var string
*/
protected static $swaggerModelName = 'BaseListing';
/**
* Array of property to type mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerTypes = [
'id' => 'string',
'heading' => 'string',
'vin' => 'string',
'stock_no' => 'string',
'price' => 'string',
'miles' => 'string',
'inventory_type' => 'string',
'last_seen_at' => 'float',
'last_seen_at_date' => 'string',
'scraped_at_date' => 'float',
'first_seen_at' => 'float',
'first_seen_at_date' => 'string',
'ref_price' => 'string',
'ref_miles' => 'string',
'ref_price_dt' => 'int',
'ref_miles_dt' => 'int',
'dom' => 'float',
'dom_180' => 'float',
'dom_active' => 'float',
'seller_type' => 'string',
'exterior_color' => 'string',
'interior_color' => 'string',
'vdp_url' => 'string',
'carfax_1_owner' => 'bool',
'carfax_clean_title' => 'bool',
'source' => 'string',
'financing_options' => '\marketcheck\api\sdk\Model\ListingFinance[]',
'leasing_options' => '\marketcheck\api\sdk\Model\ListingLease[]',
'media' => '\marketcheck\api\sdk\Model\ListingMedia',
'build' => '\marketcheck\api\sdk\Model\Build',
'dealer' => '\marketcheck\api\sdk\Model\Dealer',
'is_certified' => 'int',
'distance' => 'float'
];
/**
* Array of property to format mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerFormats = [
'id' => null,
'heading' => null,
'vin' => null,
'stock_no' => null,
'price' => null,
'miles' => null,
'inventory_type' => null,
'last_seen_at' => null,
'last_seen_at_date' => null,
'scraped_at_date' => null,
'first_seen_at' => null,
'first_seen_at_date' => null,
'ref_price' => null,
'ref_miles' => null,
'ref_price_dt' => null,
'ref_miles_dt' => null,
'dom' => null,
'dom_180' => null,
'dom_active' => null,
'seller_type' => null,
'exterior_color' => null,
'interior_color' => null,
'vdp_url' => null,
'carfax_1_owner' => null,
'carfax_clean_title' => null,
'source' => null,
'financing_options' => null,
'leasing_options' => null,
'media' => null,
'build' => null,
'dealer' => null,
'is_certified' => null,
'distance' => null
];
/**
* Array of property to type mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerTypes()
{
return self::$swaggerTypes;
}
/**
* Array of property to format mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerFormats()
{
return self::$swaggerFormats;
}
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @var string[]
*/
protected static $attributeMap = [
'id' => 'id',
'heading' => 'heading',
'vin' => 'vin',
'stock_no' => 'stock_no',
'price' => 'price',
'miles' => 'miles',
'inventory_type' => 'inventory_type',
'last_seen_at' => 'last_seen_at',
'last_seen_at_date' => 'last_seen_at_date',
'scraped_at_date' => 'scraped_at_date',
'first_seen_at' => 'first_seen_at',
'first_seen_at_date' => 'first_seen_at_date',
'ref_price' => 'ref_price',
'ref_miles' => 'ref_miles',
'ref_price_dt' => 'ref_price_dt',
'ref_miles_dt' => 'ref_miles_dt',
'dom' => 'dom',
'dom_180' => 'dom_180',
'dom_active' => 'dom_active',
'seller_type' => 'seller_type',
'exterior_color' => 'exterior_color',
'interior_color' => 'interior_color',
'vdp_url' => 'vdp_url',
'carfax_1_owner' => 'carfax_1_owner',
'carfax_clean_title' => 'carfax_clean_title',
'source' => 'source',
'financing_options' => 'financing_options',
'leasing_options' => 'leasing_options',
'media' => 'media',
'build' => 'build',
'dealer' => 'dealer',
'is_certified' => 'is_certified',
'distance' => 'distance'
];
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @var string[]
*/
protected static $setters = [
'id' => 'setId',
'heading' => 'setHeading',
'vin' => 'setVin',
'stock_no' => 'setStockNo',
'price' => 'setPrice',
'miles' => 'setMiles',
'inventory_type' => 'setInventoryType',
'last_seen_at' => 'setLastSeenAt',
'last_seen_at_date' => 'setLastSeenAtDate',
'scraped_at_date' => 'setScrapedAtDate',
'first_seen_at' => 'setFirstSeenAt',
'first_seen_at_date' => 'setFirstSeenAtDate',
'ref_price' => 'setRefPrice',
'ref_miles' => 'setRefMiles',
'ref_price_dt' => 'setRefPriceDt',
'ref_miles_dt' => 'setRefMilesDt',
'dom' => 'setDom',
'dom_180' => 'setDom180',
'dom_active' => 'setDomActive',
'seller_type' => 'setSellerType',
'exterior_color' => 'setExteriorColor',
'interior_color' => 'setInteriorColor',
'vdp_url' => 'setVdpUrl',
'carfax_1_owner' => 'setCarfax1Owner',
'carfax_clean_title' => 'setCarfaxCleanTitle',
'source' => 'setSource',
'financing_options' => 'setFinancingOptions',
'leasing_options' => 'setLeasingOptions',
'media' => 'setMedia',
'build' => 'setBuild',
'dealer' => 'setDealer',
'is_certified' => 'setIsCertified',
'distance' => 'setDistance'
];
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @var string[]
*/
protected static $getters = [
'id' => 'getId',
'heading' => 'getHeading',
'vin' => 'getVin',
'stock_no' => 'getStockNo',
'price' => 'getPrice',
'miles' => 'getMiles',
'inventory_type' => 'getInventoryType',
'last_seen_at' => 'getLastSeenAt',
'last_seen_at_date' => 'getLastSeenAtDate',
'scraped_at_date' => 'getScrapedAtDate',
'first_seen_at' => 'getFirstSeenAt',
'first_seen_at_date' => 'getFirstSeenAtDate',
'ref_price' => 'getRefPrice',
'ref_miles' => 'getRefMiles',
'ref_price_dt' => 'getRefPriceDt',
'ref_miles_dt' => 'getRefMilesDt',
'dom' => 'getDom',
'dom_180' => 'getDom180',
'dom_active' => 'getDomActive',
'seller_type' => 'getSellerType',
'exterior_color' => 'getExteriorColor',
'interior_color' => 'getInteriorColor',
'vdp_url' => 'getVdpUrl',
'carfax_1_owner' => 'getCarfax1Owner',
'carfax_clean_title' => 'getCarfaxCleanTitle',
'source' => 'getSource',
'financing_options' => 'getFinancingOptions',
'leasing_options' => 'getLeasingOptions',
'media' => 'getMedia',
'build' => 'getBuild',
'dealer' => 'getDealer',
'is_certified' => 'getIsCertified',
'distance' => 'getDistance'
];
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @return array
*/
public static function attributeMap()
{
return self::$attributeMap;
}
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @return array
*/
public static function setters()
{
return self::$setters;
}
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @return array
*/
public static function getters()
{
return self::$getters;
}
/**
* The original name of the model.
*
* @return string
*/
public function getModelName()
{
return self::$swaggerModelName;
}
/**
* Associative array for storing property values
*
* @var mixed[]
*/
protected $container = [];
/**
* Constructor
*
* @param mixed[] $data Associated array of property values
* initializing the model
*/
public function __construct(array $data = null)
{
$this->container['id'] = isset($data['id']) ? $data['id'] : null;
$this->container['heading'] = isset($data['heading']) ? $data['heading'] : null;
$this->container['vin'] = isset($data['vin']) ? $data['vin'] : null;
$this->container['stock_no'] = isset($data['stock_no']) ? $data['stock_no'] : null;
$this->container['price'] = isset($data['price']) ? $data['price'] : null;
$this->container['miles'] = isset($data['miles']) ? $data['miles'] : null;
$this->container['inventory_type'] = isset($data['inventory_type']) ? $data['inventory_type'] : null;
$this->container['last_seen_at'] = isset($data['last_seen_at']) ? $data['last_seen_at'] : null;
$this->container['last_seen_at_date'] = isset($data['last_seen_at_date']) ? $data['last_seen_at_date'] : null;
$this->container['scraped_at_date'] = isset($data['scraped_at_date']) ? $data['scraped_at_date'] : null;
$this->container['first_seen_at'] = isset($data['first_seen_at']) ? $data['first_seen_at'] : null;
$this->container['first_seen_at_date'] = isset($data['first_seen_at_date']) ? $data['first_seen_at_date'] : null;
$this->container['ref_price'] = isset($data['ref_price']) ? $data['ref_price'] : null;
$this->container['ref_miles'] = isset($data['ref_miles']) ? $data['ref_miles'] : null;
$this->container['ref_price_dt'] = isset($data['ref_price_dt']) ? $data['ref_price_dt'] : null;
$this->container['ref_miles_dt'] = isset($data['ref_miles_dt']) ? $data['ref_miles_dt'] : null;
$this->container['dom'] = isset($data['dom']) ? $data['dom'] : null;
$this->container['dom_180'] = isset($data['dom_180']) ? $data['dom_180'] : null;
$this->container['dom_active'] = isset($data['dom_active']) ? $data['dom_active'] : null;
$this->container['seller_type'] = isset($data['seller_type']) ? $data['seller_type'] : null;
$this->container['exterior_color'] = isset($data['exterior_color']) ? $data['exterior_color'] : null;
$this->container['interior_color'] = isset($data['interior_color']) ? $data['interior_color'] : null;
$this->container['vdp_url'] = isset($data['vdp_url']) ? $data['vdp_url'] : null;
$this->container['carfax_1_owner'] = isset($data['carfax_1_owner']) ? $data['carfax_1_owner'] : null;
$this->container['carfax_clean_title'] = isset($data['carfax_clean_title']) ? $data['carfax_clean_title'] : null;
$this->container['source'] = isset($data['source']) ? $data['source'] : null;
$this->container['financing_options'] = isset($data['financing_options']) ? $data['financing_options'] : null;
$this->container['leasing_options'] = isset($data['leasing_options']) ? $data['leasing_options'] : null;
$this->container['media'] = isset($data['media']) ? $data['media'] : null;
$this->container['build'] = isset($data['build']) ? $data['build'] : null;
$this->container['dealer'] = isset($data['dealer']) ? $data['dealer'] : null;
$this->container['is_certified'] = isset($data['is_certified']) ? $data['is_certified'] : null;
$this->container['distance'] = isset($data['distance']) ? $data['distance'] : null;
}
/**
* Show all the invalid properties with reasons.
*
* @return array invalid properties with reasons
*/
public function listInvalidProperties()
{
$invalidProperties = [];
return $invalidProperties;
}
/**
* Validate all the properties in the model
* return true if all passed
*
* @return bool True if all properties are valid
*/
public function valid()
{
return count($this->listInvalidProperties()) === 0;
}
/**
* Gets id
*
* @return string
*/
public function getId()
{
return $this->container['id'];
}
/**
* Sets id
*
* @param string $id Unique identifier representing a specific listing from the Marketcheck database
*
* @return $this
*/
public function setId($id)
{
$this->container['id'] = $id;
return $this;
}
/**
* Gets heading
*
* @return string
*/
public function getHeading()
{
return $this->container['heading'];
}
/**
* Sets heading
*
* @param string $heading Listing title as displayed on the source website
*
* @return $this
*/
public function setHeading($heading)
{
$this->container['heading'] = $heading;
return $this;
}
/**
* Gets vin
*
* @return string
*/
public function getVin()
{
return $this->container['vin'];
}
/**
* Sets vin
*
* @param string $vin VIN for the car
*
* @return $this
*/
public function setVin($vin)
{
$this->container['vin'] = $vin;
return $this;
}
/**
* Gets stock_no
*
* @return string
*/
public function getStockNo()
{
return $this->container['stock_no'];
}
/**
* Sets stock_no
*
* @param string $stock_no Stock no of the car
*
* @return $this
*/
public function setStockNo($stock_no)
{
$this->container['stock_no'] = $stock_no;
return $this;
}
/**
* Gets price
*
* @return string
*/
public function getPrice()
{
return $this->container['price'];
}
/**
* Sets price
*
* @param string $price Asking price for the car
*
* @return $this
*/
public function setPrice($price)
{
$this->container['price'] = $price;
return $this;
}
/**
* Gets miles
*
* @return string
*/
public function getMiles()
{
return $this->container['miles'];
}
/**
* Sets miles
*
* @param string $miles Odometer reading / reported miles usage for the car
*
* @return $this
*/
public function setMiles($miles)
{
$this->container['miles'] = $miles;
return $this;
}
/**
* Gets inventory_type
*
* @return string
*/
public function getInventoryType()
{
return $this->container['inventory_type'];
}
/**
* Sets inventory_type
*
* @param string $inventory_type Inventory type of car
*
* @return $this
*/
public function setInventoryType($inventory_type)
{
$this->container['inventory_type'] = $inventory_type;
return $this;
}
/**
* Gets last_seen_at
*
* @return float
*/
public function getLastSeenAt()
{
return $this->container['last_seen_at'];
}
/**
* Sets last_seen_at
*
* @param float $last_seen_at Listing last seen at (most recent) timestamp
*
* @return $this
*/
public function setLastSeenAt($last_seen_at)
{
$this->container['last_seen_at'] = $last_seen_at;
return $this;
}
/**
* Gets last_seen_at_date
*
* @return string
*/
public function getLastSeenAtDate()
{
return $this->container['last_seen_at_date'];
}
/**
* Sets last_seen_at_date
*
* @param string $last_seen_at_date Listing last seen at (most recent) date
*
* @return $this
*/
public function setLastSeenAtDate($last_seen_at_date)
{
$this->container['last_seen_at_date'] = $last_seen_at_date;
return $this;
}
/**
* Gets scraped_at_date
*
* @return float
*/
public function getScrapedAtDate()
{
return $this->container['scraped_at_date'];
}
/**
* Sets scraped_at_date
*
* @param float $scraped_at_date Listing first seen at first scraped date
*
* @return $this
*/
public function setScrapedAtDate($scraped_at_date)
{
$this->container['scraped_at_date'] = $scraped_at_date;
return $this;
}
/**
* Gets first_seen_at
*
* @return float
*/
public function getFirstSeenAt()
{
return $this->container['first_seen_at'];
}
/**
* Sets first_seen_at
*
* @param float $first_seen_at Listing first seen at first scraped timestamp
*
* @return $this
*/
public function setFirstSeenAt($first_seen_at)
{
$this->container['first_seen_at'] = $first_seen_at;
return $this;
}
/**
* Gets first_seen_at_date
*
* @return string
*/
public function getFirstSeenAtDate()
{
return $this->container['first_seen_at_date'];
}
/**
* Sets first_seen_at_date
*
* @param string $first_seen_at_date Listing first seen at first scraped date
*
* @return $this
*/
public function setFirstSeenAtDate($first_seen_at_date)
{
$this->container['first_seen_at_date'] = $first_seen_at_date;
return $this;
}
/**
* Gets ref_price
*
* @return string
*/
public function getRefPrice()
{
return $this->container['ref_price'];
}
/**
* Sets ref_price
*
* @param string $ref_price Last reported price for the car. If the asking price value is not or is available then the last_price could perhaps be used. last_price is the price for the car listed on the source website as of last_price_dt date
*
* @return $this
*/
public function setRefPrice($ref_price)
{
$this->container['ref_price'] = $ref_price;
return $this;
}
/**
* Gets ref_miles
*
* @return string
*/
public function getRefMiles()
{
return $this->container['ref_miles'];
}
/**
* Sets ref_miles
*
* @param string $ref_miles Last Odometer reading / reported miles usage for the car. If the asking miles value is not or is available then the last_miles could perhaps be used. last_miles is the miles for the car listed on the source website as of last_miles_dt date
*
* @return $this
*/
public function setRefMiles($ref_miles)
{
$this->container['ref_miles'] = $ref_miles;
return $this;
}
/**
* Gets ref_price_dt
*
* @return int
*/
public function getRefPriceDt()
{
return $this->container['ref_price_dt'];
}
/**
* Sets ref_price_dt
*
* @param int $ref_price_dt The date at which the last price was reported online. This is earlier to last_seen_date
*
* @return $this
*/
public function setRefPriceDt($ref_price_dt)
{
$this->container['ref_price_dt'] = $ref_price_dt;
return $this;
}
/**
* Gets ref_miles_dt
*
* @return int
*/
public function getRefMilesDt()
{
return $this->container['ref_miles_dt'];
}
/**
* Sets ref_miles_dt
*
* @param int $ref_miles_dt The date at which the last miles was reported online. This is earlier to last_seen_date
*
* @return $this
*/
public function setRefMilesDt($ref_miles_dt)
{
$this->container['ref_miles_dt'] = $ref_miles_dt;
return $this;
}
/**
* Gets dom
*
* @return float
*/
public function getDom()
{
return $this->container['dom'];
}
/**
* Sets dom
*
* @param float $dom Days on Market value for the car based on current and historical listings found in the Marketcheck database for this car
*
* @return $this
*/
public function setDom($dom)
{
$this->container['dom'] = $dom;
return $this;
}
/**
* Gets dom_180
*
* @return float
*/
public function getDom180()
{
return $this->container['dom_180'];
}
/**
* Sets dom_180
*
* @param float $dom_180 Days on Market value for the car based on current and last 6 month listings found in the Marketcheck database for this car
*
* @return $this
*/
public function setDom180($dom_180)
{
$this->container['dom_180'] = $dom_180;
return $this;
}
/**
* Gets dom_active
*
* @return float
*/
public function getDomActive()
{
return $this->container['dom_active'];
}
/**
* Sets dom_active
*
* @param float $dom_active Days on Market value for the car based on current and last 30 days listings found in the Marketcheck database for this car
*
* @return $this
*/
public function setDomActive($dom_active)
{
$this->container['dom_active'] = $dom_active;
return $this;
}
/**
* Gets seller_type
*
* @return string
*/
public function getSellerType()
{
return $this->container['seller_type'];
}
/**
* Sets seller_type
*
* @param string $seller_type Seller type for the car
*
* @return $this
*/
public function setSellerType($seller_type)
{
$this->container['seller_type'] = $seller_type;
return $this;
}
/**
* Gets exterior_color
*
* @return string
*/
public function getExteriorColor()
{
return $this->container['exterior_color'];
}
/**
* Sets exterior_color
*
* @param string $exterior_color Exterior color of the car
*
* @return $this
*/
public function setExteriorColor($exterior_color)
{
$this->container['exterior_color'] = $exterior_color;
return $this;
}
/**
* Gets interior_color
*
* @return string
*/
public function getInteriorColor()
{
return $this->container['interior_color'];
}
/**
* Sets interior_color
*
* @param string $interior_color Interior color of the car
*
* @return $this
*/
public function setInteriorColor($interior_color)
{
$this->container['interior_color'] = $interior_color;
return $this;
}
/**
* Gets vdp_url
*
* @return string
*/
public function getVdpUrl()
{
return $this->container['vdp_url'];
}
/**
* Sets vdp_url
*
* @param string $vdp_url Vehicle Details Page url of the specific car
*
* @return $this
*/
public function setVdpUrl($vdp_url)
{
$this->container['vdp_url'] = $vdp_url;
return $this;
}
/**
* Gets carfax_1_owner
*
* @return bool
*/
public function getCarfax1Owner()
{
return $this->container['carfax_1_owner'];
}
/**
* Sets carfax_1_owner
*
* @param bool $carfax_1_owner Flag to indicate whether listing is carfax_1_owner
*
* @return $this
*/
public function setCarfax1Owner($carfax_1_owner)
{
$this->container['carfax_1_owner'] = $carfax_1_owner;
return $this;
}
/**
* Gets carfax_clean_title
*
* @return bool
*/
public function getCarfaxCleanTitle()
{
return $this->container['carfax_clean_title'];
}
/**
* Sets carfax_clean_title
*
* @param bool $carfax_clean_title Flag to indicate whether listing is carfax_clean_title
*
* @return $this
*/
public function setCarfaxCleanTitle($carfax_clean_title)
{
$this->container['carfax_clean_title'] = $carfax_clean_title;
return $this;
}
/**
* Gets source
*
* @return string
*/
public function getSource()
{
return $this->container['source'];
}
/**
* Sets source
*
* @param string $source Source domain of the listing
*
* @return $this
*/
public function setSource($source)
{
$this->container['source'] = $source;
return $this;
}
/**
* Gets financing_options
*
* @return \marketcheck\api\sdk\Model\ListingFinance[]
*/
public function getFinancingOptions()
{
return $this->container['financing_options'];
}
/**
* Sets financing_options
*
* @param \marketcheck\api\sdk\Model\ListingFinance[] $financing_options Array of all finance offers for this listing
*
* @return $this
*/
public function setFinancingOptions($financing_options)
{
$this->container['financing_options'] = $financing_options;
return $this;
}
/**
* Gets leasing_options
*
* @return \marketcheck\api\sdk\Model\ListingLease[]
*/
public function getLeasingOptions()
{
return $this->container['leasing_options'];
}
/**
* Sets leasing_options
*
* @param \marketcheck\api\sdk\Model\ListingLease[] $leasing_options Array of all finance offers for this listing
*
* @return $this
*/
public function setLeasingOptions($leasing_options)
{
$this->container['leasing_options'] = $leasing_options;
return $this;
}
/**
* Gets media
*
* @return \marketcheck\api\sdk\Model\ListingMedia
*/
public function getMedia()
{
return $this->container['media'];
}
/**
* Sets media
*
* @param \marketcheck\api\sdk\Model\ListingMedia $media Car Media Attributes - main photo link/url and photo links
*
* @return $this
*/
public function setMedia($media)
{
$this->container['media'] = $media;
return $this;
}
/**
* Gets build
*
* @return \marketcheck\api\sdk\Model\Build
*/
public function getBuild()
{
return $this->container['build'];
}
/**
* Sets build
*
* @param \marketcheck\api\sdk\Model\Build $build build
*
* @return $this
*/
public function setBuild($build)
{
$this->container['build'] = $build;
return $this;
}
/**
* Gets dealer
*
* @return \marketcheck\api\sdk\Model\Dealer
*/
public function getDealer()
{
return $this->container['dealer'];
}
/**
* Sets dealer
*
* @param \marketcheck\api\sdk\Model\Dealer $dealer dealer
*
* @return $this
*/
public function setDealer($dealer)
{
$this->container['dealer'] = $dealer;
return $this;
}
/**
* Gets is_certified
*
* @return int
*/
public function getIsCertified()
{
return $this->container['is_certified'];
}
/**
* Sets is_certified
*
* @param int $is_certified Certified car
*
* @return $this
*/
public function setIsCertified($is_certified)
{
$this->container['is_certified'] = $is_certified;
return $this;
}
/**
* Gets distance
*
* @return float
*/
public function getDistance()
{
return $this->container['distance'];
}
/**
* Sets distance
*
* @param float $distance Distance of the car's location from the specified user lcoation
*
* @return $this
*/
public function setDistance($distance)
{
$this->container['distance'] = $distance;
return $this;
}
/**
* Returns true if offset exists. False otherwise.
*
* @param integer $offset Offset
*
* @return boolean
*/
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
/**
* Gets offset.
*
* @param integer $offset Offset
*
* @return mixed
*/
public function offsetGet($offset)
{
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
/**
* Sets value based on offset.
*
* @param integer $offset Offset
* @param mixed $value Value to be set
*
* @return void
*/
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
/**
* Unsets offset.
*
* @param integer $offset Offset
*
* @return void
*/
public function offsetUnset($offset)
{
unset($this->container[$offset]);
}
/**
* Gets the string presentation of the object
*
* @return string
*/
public function __toString()
{
if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
return json_encode(
ObjectSerializer::sanitizeForSerialization($this),
JSON_PRETTY_PRINT
);
}
return json_encode(ObjectSerializer::sanitizeForSerialization($this));
}
}
<file_sep>/test/Api/MarketApiTest.php
<?php
/**
* MarketApiTest
* PHP version 5
*
* @category Class
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Marketcheck Cars API
*
* <b>Access the New, Used and Certified cars inventories for all Car Dealers in US.</b> <br/>The data is sourced from online listings by over 44,000 Car dealers in US. At any time, there are about 6.2M searchable listings (about 1.9M unique VINs) for Used & Certified cars and about 6.6M (about 3.9M unique VINs) New Car listings from all over US. We use this API at the back for our website <a href='https://www.marketcheck.com' target='_blank'>www.marketcheck.com</a> and our Android and iOS mobile apps too.<br/><h5> Few useful links : </h5><ul><li>A quick view of the API and the use cases is depicated <a href='https://portals.marketcheck.com/mcapi/' target='_blank'>here</a></li><li>The Postman collection with various usages of the API is shared here https://www.getpostman.com/collections/2752684ff636cdd7bac2</li></ul>
*
* OpenAPI spec version: 1.0.3
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.0-SNAPSHOT
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Please update the test case below to test the endpoint.
*/
require __DIR__.'/../../vendor/autoload.php';
require __DIR__.'/../../lib/Api/ListingsApi.php';
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
use \marketcheck\api\sdk\Configuration;
use \marketcheck\api\sdk\ApiException;
use \marketcheck\api\sdk\ObjectSerializer;
/**
* MarketApiTest Class Doc Comment
*
* @category Class
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class MarketApiTest extends \PHPUnit_Framework_TestCase
{
private $api_key = "your api key";
private $vin = array("1GYS4BKJ8FR290257","3GYFNBE3XFS537500","1FT7W2BT5FEA75059","1FMCU9J90FUA21186");
private $latitude;
private $longitude;
private $radius;
private $exact;
private $start;
private $debug;
private $include_sold;
private $year;
private $make;
private $model;
private $trim;
private $body_type;
private $stats;
private $car_type;
private $mm;
private $ymm;
private $ymmt;
private $taxonomy_vin;
private $state;
private $city_state;
/**
* Setup before running any test cases
*/
public static function setUpBeforeClass()
{
}
/**
* Setup before running each test case
*/
public function setUp()
{
}
/**
* Clean up after running each test case
*/
public function tearDown()
{
}
/**
* Clean up after running all test cases
*/
public static function tearDownAfterClass()
{
}
/**
* Test case for getMDS
*
* Market Days Supply.
*
*/
public function testGetMDS()
{
$apiInstance = new marketcheck\api\sdk\Api\MarketApi(new GuzzleHttp\Client());
$this->latitude = 37.998;
$this->longitude = -84.522;
$this->radius = 1000;
$this->debug = "1";
$this->include_sold = 'false';
echo "\nValidate ymmt available in response or not and will verify mds count with exact and debug";
foreach($this->vin as $h_vin)
{
try
{
$this->exact = "true";
$result = $apiInstance->getMDS($h_vin, $this->api_key, $this->exact, $this->latitude, $this->longitude, $this->radius, $this->debug, $this->include_sold);
$this->assertArrayHasKey("year", $result);
$this->assertArrayHasKey("make", $result);
$this->assertArrayHasKey("model", $result);
$this->assertArrayHasKey("trim", $result);
$this->assertNotNull($result["mds"]);
$this->assertNotEquals(sizeof($result), 0);
$this->assertNotEquals($result["total_cars_sold_in_last_45_days"], 0);
$this->assertNotNull($result["total_cars_sold_in_last_45_days"]);
$per_day_sold_rate = round($result["total_cars_sold_in_last_45_days"]/45,2);
$mds = round($result["total_active_cars_for_ymmt"]/$per_day_sold_rate);
$this->assertEquals($result["mds"], $mds);
print_r("\n/mds?api_key={{api_key}}&vin=$h_vin&latitude=37.998&longitude=-84.522&radius=1000&exact=true&debug=1: endpoint working fine");
} catch (Exception $e) {
$this->fail($e->getMessage());
}
}
echo "\nValidate ymmt available in response or not and will verify mds count with debug and without exact";
foreach($this->vin as $h_vin)
{
try
{
$this->exact = "false";
$result = $apiInstance->getMDS($h_vin, $this->api_key, $this->exact, $this->latitude, $this->longitude, $this->radius, $this->debug, $this->include_sold);
$this->assertArrayHasKey("year", $result);
$this->assertArrayHasKey("make", $result);
$this->assertArrayHasKey("model", $result);
$this->assertNotNull($result["mds"]);
$this->assertNotEquals(sizeof($result), 0);
$this->assertNotEquals($result["total_cars_sold_in_last_45_days"], 0);
$this->assertNotNull($result["total_cars_sold_in_last_45_days"]);
$per_day_sold_rate = round($result["total_cars_sold_in_last_45_days"]/45,2);
$mds = round($result["total_active_cars_for_ymmt"]/$per_day_sold_rate);
$this->assertEquals($result["mds"], $mds);
print_r("\n/mds?api_key={{api_key}}&vin=$h_vin&latitude=37.998&longitude=-84.522&radius=1000&exact=true&debug=1: endpoint working fine");
} catch (Exception $e) {
$this->fail($e->getMessage());
}
}
echo "\nValidate mds count with debug and without exact";
foreach($this->vin as $h_vin)
{
try
{
$this->exact = "false";
$result = $apiInstance->getMDS($h_vin, $this->api_key, $this->exact, $this->latitude, $this->longitude, $this->radius, $this->debug, $this->include_sold);
$this->assertNotNull($result["mds"]);
$this->assertNotEquals(sizeof($result), 0);
$this->assertNotEquals($result["total_active_cars_for_ymmt"], 0);
$this->assertNotNull($result["total_active_cars_for_ymmt"]);
$this->assertNotEquals($result["total_cars_sold_in_last_45_days"], 0);
$this->assertNotNull($result["total_cars_sold_in_last_45_days"]);
$per_day_sold_rate = round($result["total_cars_sold_in_last_45_days"]/45,2);
$mds = round($result["total_active_cars_for_ymmt"]/$per_day_sold_rate);
$this->assertEquals($result["mds"], $mds);
print_r("\n/mds?api_key={{api_key}}&vin=$h_vin&latitude=37.998&longitude=-84.522&radius=1000&exact=true&debug=1: endpoint working fine");
} catch (Exception $e) {
$this->fail($e->getMessage());
}
}
}
/**
* Test case for getSalesCount
*
* Get sales count by make, model, year, trim or taxonomy vin.
*
*/
public function testGetSalesCount()
{
$apiInstance = new marketcheck\api\sdk\Api\MarketApi(new GuzzleHttp\Client());
$this->car_type = 'used';
$this->make;
$this->mm;
$this->ymm;
$this->ymmt;
$this->taxonomy_vin;
$this->state;
$this->city_state;
$this->stats;
//$result = $apiInstance->getSalesCount($this->api_key, $this->car_type, $this->make, $this->mm, $this->ymm, $this->ymmt, $this->taxonomy_vin, $this->state, $this->city_state, $this->stats);
//print($result);
}
}
<file_sep>/test/Model/ListingLeaseTest.php
<?php
/**
* ListingLeaseTest
*
* PHP version 5
*
* @category Class
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Marketcheck Cars API
*
* <b>Access the New, Used and Certified cars inventories for all Car Dealers in US.</b> <br/>The data is sourced from online listings by over 44,000 Car dealers in US. At any time, there are about 6.2M searchable listings (about 1.9M unique VINs) for Used & Certified cars and about 6.6M (about 3.9M unique VINs) New Car listings from all over US. We use this API at the back for our website <a href='https://www.marketcheck.com' target='_blank'>www.marketcheck.com</a> and our Android and iOS mobile apps too.<br/><h5> Few useful links : </h5><ul><li>A quick view of the API and the use cases is depicated <a href='https://portals.marketcheck.com/mcapi/' target='_blank'>here</a></li><li>The Postman collection with various usages of the API is shared here https://www.getpostman.com/collections/2752684ff636cdd7bac2</li></ul>
*
* OpenAPI spec version: 1.0.3
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.0-SNAPSHOT
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Please update the test case below to test the model.
*/
namespace marketcheck\api\sdk;
/**
* ListingLeaseTest Class Doc Comment
*
* @category Class
* @description ListingLease
* @package marketcheck\api\sdk
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class ListingLeaseTest extends \PHPUnit_Framework_TestCase
{
/**
* Setup before running any test case
*/
public static function setUpBeforeClass()
{
}
/**
* Setup before running each test case
*/
public function setUp()
{
}
/**
* Clean up after running each test case
*/
public function tearDown()
{
}
/**
* Clean up after running all test cases
*/
public static function tearDownAfterClass()
{
}
/**
* Test "ListingLease"
*/
public function testListingLease()
{
}
/**
* Test attribute "lease_term"
*/
public function testPropertyLeaseTerm()
{
}
/**
* Test attribute "down_payment"
*/
public function testPropertyDownPayment()
{
}
/**
* Test attribute "estimated_monthly_payment"
*/
public function testPropertyEstimatedMonthlyPayment()
{
}
}
|
0a8d4985622864128de2860187cc1ce3b4ad97c9
|
[
"Markdown",
"PHP"
] | 24
|
PHP
|
MarketcheckCarsInc/marketcheck-api-sdk-php
|
7ee483b7ee26bc133583ad876fdffa6b14745072
|
d54fd69dacd193de71982744a4c14642ff0f1f70
|
refs/heads/master
|
<repo_name>JohnMTrimbleIII/mediafoundationsamples<file_sep>/MFWebCamRtp/MFWebCamRtp.cpp
/// Filename: MFWebCamRtp.cpp
///
/// Description:
/// This file contains a C++ console application that captures the realtime video stream from a webcam using
/// Windows Media Foundation, encodes it as H264 and then transmits it to an RTP end point using the real-time
/// communications API from Live555 (http://live555.com/).
///
/// To view the RTP feed produced by this sample the steps are:
/// 1. Download ffplay from http://ffmpeg.zeranoe.com/builds/ (the static build has a ready to go ffplay executable),
/// 2. Create a file called test.sdp with contents as below:
/// v=0
/// o = -0 0 IN IP4 127.0.0.1
/// s = No Name
/// t = 0 0
/// c = IN IP4 127.0.0.1
/// m = video 1234 RTP / AVP 96
/// a = rtpmap:96 H264 / 90000
/// a = fmtp : 96 packetization - mode = 1
/// 3. Start ffplay BEFORE running this sample:
/// ffplay -i test.sdp -x 800 -y 600 -profile:v baseline
///
/// History:
/// 07 Sep 2015 <NAME> (<EMAIL>) Created.
///
/// License: Public
/// License for Live555: LGPL (http://live555.com/liveMedia/#license)
#include "liveMedia.hh"
#include "BasicUsageEnvironment.hh"
#include "GroupsockHelper.hh"
#include <stdint.h>
#include <stdio.h>
#include <tchar.h>
#include <evr.h>
#include <mfapi.h>
#include <mfplay.h>
#include <mfreadwrite.h>
#include <mferror.h>
#include <wmcodecdsp.h>
#include <codecapi.h>
#include "..\Common\MFUtility.h"
#pragma comment(lib, "mf.lib")
#pragma comment(lib, "mfplat.lib")
#pragma comment(lib, "mfplay.lib")
#pragma comment(lib, "mfreadwrite.lib")
#pragma comment(lib, "mfuuid.lib")
#pragma comment(lib, "wmcodecdspuuid.lib")
class MediaFoundationH264LiveSource :
public FramedSource
{
private:
static const int CAMERA_RESOLUTION_WIDTH = 640; // 800; // 1280;
static const int CAMERA_RESOLUTION_HEIGHT = 480; // 600; // 1024;
static const int TARGET_FRAME_RATE = 30;// 5; 15; 30 // Note that this if the video device does not support this frame rate the video source reader will fail to initialise.
static const int TARGET_AVERAGE_BIT_RATE = 1000000; // Adjusting this affects the quality of the H264 bit stream.
static const int WEBCAM_DEVICE_INDEX = 0; // <--- Set to 0 to use default system webcam.
bool _isInitialised = false;
EventTriggerId eventTriggerId = 0;
int _frameCount = 0;
long int _lastSendAt;
IMFTransform *_pTransform = NULL; //< this is H264 Encoder MFT
IMFSourceReader *_videoReader = NULL;
MFT_OUTPUT_DATA_BUFFER _outputDataBuffer;
IMFMediaSource *videoSource = NULL;
IMFMediaType *videoSourceOutputType = NULL, *pSrcOutMediaType = NULL;
IUnknown *spTransformUnk = NULL;
IMFMediaType *pMFTInputMediaType = NULL, *pMFTOutputMediaType = NULL;
DWORD mftStatus = 0;
public:
static MediaFoundationH264LiveSource* createNew(UsageEnvironment& env)
{
return new MediaFoundationH264LiveSource(env);
}
MediaFoundationH264LiveSource(UsageEnvironment& env) :
FramedSource(env)
{
_lastSendAt = GetTickCount();
eventTriggerId = envir().taskScheduler().createEventTrigger(deliverFrame0);
}
~MediaFoundationH264LiveSource()
{ }
bool isH264VideoStreamFramer() const {
return true;
}
static void deliverFrame0(void* clientData) {
((MediaFoundationH264LiveSource*)clientData)->doGetNextFrame();
}
bool initialise()
{
UINT32 videoDeviceCount = 0;
IMFAttributes *videoConfig = NULL;
IMFActivate **videoDevices = NULL;
WCHAR *webcamFriendlyName;
CHECK_HR(MFTRegisterLocalByCLSID(
__uuidof(CColorConvertDMO),
MFT_CATEGORY_VIDEO_PROCESSOR,
L"",
MFT_ENUM_FLAG_SYNCMFT,
0,
NULL,
0,
NULL
), "Error registering colour converter DSP.\n");
// Get the first available webcam.
CHECK_HR(MFCreateAttributes(&videoConfig, 1), "Error creating video configuation.\n");
// Request video capture devices.
CHECK_HR(videoConfig->SetGUID(
MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID), "Error initialising video configuration object.");
CHECK_HR(MFEnumDeviceSources(videoConfig, &videoDevices, &videoDeviceCount), "Error enumerating video devices.\n");
CHECK_HR(videoDevices[WEBCAM_DEVICE_INDEX]->GetAllocatedString(MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME, &webcamFriendlyName, NULL), "Error retrieving vide device friendly name.\n");
wprintf(L"First available webcam: %s\n", webcamFriendlyName);
CHECK_HR(videoDevices[WEBCAM_DEVICE_INDEX]->ActivateObject(IID_PPV_ARGS(&videoSource)), "Error activating video device.\n");
// Create a source reader.
CHECK_HR(MFCreateSourceReaderFromMediaSource(
videoSource,
videoConfig,
&_videoReader), "Error creating video source reader.\n");
//ListModes(_videoReader);
CHECK_HR(_videoReader->GetCurrentMediaType(
(DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM,
&videoSourceOutputType), "Error retrieving current media type from first video stream.\n");
Console::WriteLine(GetMediaTypeDescription(videoSourceOutputType));
// Note the webcam needs to support this media type. The list of media types supported can be obtained using the ListTypes function in MFUtility.h.
MFCreateMediaType(&pSrcOutMediaType);
pSrcOutMediaType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);
//pSrcOutMediaType->SetGUID(MF_MT_SUBTYPE, WMMEDIASUBTYPE_I420);
pSrcOutMediaType->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_RGB24);
MFSetAttributeSize(pSrcOutMediaType, MF_MT_FRAME_SIZE, CAMERA_RESOLUTION_WIDTH, CAMERA_RESOLUTION_HEIGHT);
CHECK_HR(MFSetAttributeRatio(pSrcOutMediaType, MF_MT_FRAME_RATE, TARGET_FRAME_RATE, 1), "Failed to set frame rate on video device out type.\n");
CHECK_HR(_videoReader->SetCurrentMediaType(0, NULL, pSrcOutMediaType), "Failed to set media type on source reader.\n");
//CHECK_HR(_videoReader->SetCurrentMediaType(0, NULL, videoSourceOutputType), "Failed to setdefault media type on source reader.\n");
// Create H.264 encoder.
CHECK_HR(CoCreateInstance(CLSID_CMSH264EncoderMFT, NULL, CLSCTX_INPROC_SERVER,
IID_IUnknown, (void**)&spTransformUnk), "Failed to create H264 encoder MFT.\n");
CHECK_HR(spTransformUnk->QueryInterface(IID_PPV_ARGS(&_pTransform)), "Failed to get IMFTransform interface from H264 encoder MFT object.\n");
MFCreateMediaType(&pMFTOutputMediaType);
pMFTOutputMediaType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);
pMFTOutputMediaType->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_H264);
//pMFTOutputMediaType->SetUINT32(MF_MT_AVG_BITRATE, 240000);
CHECK_HR(pMFTOutputMediaType->SetUINT32(MF_MT_AVG_BITRATE, TARGET_AVERAGE_BIT_RATE), "Failed to set average bit rate on H264 output media type.\n");
CHECK_HR(MFSetAttributeSize(pMFTOutputMediaType, MF_MT_FRAME_SIZE, CAMERA_RESOLUTION_WIDTH, CAMERA_RESOLUTION_HEIGHT), "Failed to set frame size on H264 MFT out type.\n");
CHECK_HR(MFSetAttributeRatio(pMFTOutputMediaType, MF_MT_FRAME_RATE, TARGET_FRAME_RATE, 1), "Failed to set frame rate on H264 MFT out type.\n");
CHECK_HR(MFSetAttributeRatio(pMFTOutputMediaType, MF_MT_PIXEL_ASPECT_RATIO, 1, 1), "Failed to set aspect ratio on H264 MFT out type.\n");
pMFTOutputMediaType->SetUINT32(MF_MT_INTERLACE_MODE, 2); // 2 = Progressive scan, i.e. non-interlaced.
pMFTOutputMediaType->SetUINT32(MF_MT_ALL_SAMPLES_INDEPENDENT, TRUE);
//CHECK_HR(MFSetAttributeRatio(pMFTOutputMediaType, MF_MT_MPEG2_PROFILE, eAVEncH264VProfile_Base), "Failed to set profile on H264 MFT out type.\n");
//CHECK_HR(pMFTOutputMediaType->SetDouble(MF_MT_MPEG2_LEVEL, 3.1), "Failed to set level on H264 MFT out type.\n");
//CHECK_HR(pMFTOutputMediaType->SetUINT32(MF_MT_MAX_KEYFRAME_SPACING, 10), "Failed to set key frame interval on H264 MFT out type.\n");
//CHECK_HR(pMFTOutputMediaType->SetUINT32(CODECAPI_AVEncCommonQuality, 100), "Failed to set H264 codec qulaity.\n");
//hr = pAttributes->SetUINT32(CODECAPI_AVEncMPVGOPSize, 1)
CHECK_HR(_pTransform->SetOutputType(0, pMFTOutputMediaType, 0), "Failed to set output media type on H.264 encoder MFT.\n");
MFCreateMediaType(&pMFTInputMediaType);
pMFTInputMediaType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);
pMFTInputMediaType->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_IYUV);
CHECK_HR(MFSetAttributeSize(pMFTInputMediaType, MF_MT_FRAME_SIZE, CAMERA_RESOLUTION_WIDTH, CAMERA_RESOLUTION_HEIGHT), "Failed to set frame size on H264 MFT out type.\n");
CHECK_HR(MFSetAttributeRatio(pMFTInputMediaType, MF_MT_FRAME_RATE, TARGET_FRAME_RATE, 1), "Failed to set frame rate on H264 MFT out type.\n");
CHECK_HR(MFSetAttributeRatio(pMFTInputMediaType, MF_MT_PIXEL_ASPECT_RATIO, 1, 1), "Failed to set aspect ratio on H264 MFT out type.\n");
pMFTInputMediaType->SetUINT32(MF_MT_INTERLACE_MODE, 2);
CHECK_HR(_pTransform->SetInputType(0, pMFTInputMediaType, 0), "Failed to set input media type on H.264 encoder MFT.\n");
CHECK_HR(_pTransform->GetInputStatus(0, &mftStatus), "Failed to get input status from H.264 MFT.\n");
if (MFT_INPUT_STATUS_ACCEPT_DATA != mftStatus) {
printf("E: ApplyTransform() pTransform->GetInputStatus() not accept data.\n");
goto done;
}
//Console::WriteLine(GetMediaTypeDescription(pMFTOutputMediaType));
CHECK_HR(_pTransform->ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, NULL), "Failed to process FLUSH command on H.264 MFT.\n");
CHECK_HR(_pTransform->ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, NULL), "Failed to process BEGIN_STREAMING command on H.264 MFT.\n");
CHECK_HR(_pTransform->ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, NULL), "Failed to process START_OF_STREAM command on H.264 MFT.\n");
memset(&_outputDataBuffer, 0, sizeof _outputDataBuffer);
return true;
done:
printf("MediaFoundationH264LiveSource initialisation failed.\n");
return false;
}
virtual void doGetNextFrame()
{
if (!_isInitialised)
{
_isInitialised = true;
if (!initialise())
{
printf("Video device initialisation failed, stopping.");
return;
}
}
if (!isCurrentlyAwaitingData()) return;
DWORD processOutputStatus = 0;
IMFSample *videoSample = NULL;
DWORD streamIndex, flags;
LONGLONG llVideoTimeStamp, llSampleDuration;
HRESULT mftProcessInput = S_OK;
HRESULT mftProcessOutput = S_OK;
MFT_OUTPUT_STREAM_INFO StreamInfo;
IMFMediaBuffer *pBuffer = NULL;
IMFSample *mftOutSample = NULL;
DWORD mftOutFlags;
bool frameSent = false;
CHECK_HR(_videoReader->ReadSample(
MF_SOURCE_READER_FIRST_VIDEO_STREAM,
0, // Flags.
&streamIndex, // Receives the actual stream index.
&flags, // Receives status flags.
&llVideoTimeStamp, // Receives the time stamp.
&videoSample // Receives the sample or NULL.
), "Error reading video sample.");
if (videoSample)
{
_frameCount++;
CHECK_HR(videoSample->SetSampleTime(llVideoTimeStamp), "Error setting the video sample time.\n");
CHECK_HR(videoSample->GetSampleDuration(&llSampleDuration), "Error getting video sample duration.\n");
// Pass the video sample to the H.264 transform.
CHECK_HR(_pTransform->ProcessInput(0, videoSample, 0), "The resampler H264 ProcessInput call failed.\n");
CHECK_HR(_pTransform->GetOutputStatus(&mftOutFlags), "H264 MFT GetOutputStatus failed.\n");
if (mftOutFlags == MFT_OUTPUT_STATUS_SAMPLE_READY)
{
printf("Sample ready.\n");
CHECK_HR(_pTransform->GetOutputStreamInfo(0, &StreamInfo), "Failed to get output stream info from H264 MFT.\n");
CHECK_HR(MFCreateSample(&mftOutSample), "Failed to create MF sample.\n");
CHECK_HR(MFCreateMemoryBuffer(StreamInfo.cbSize, &pBuffer), "Failed to create memory buffer.\n");
CHECK_HR(mftOutSample->AddBuffer(pBuffer), "Failed to add sample to buffer.\n");
while (true)
{
_outputDataBuffer.dwStreamID = 0;
_outputDataBuffer.dwStatus = 0;
_outputDataBuffer.pEvents = NULL;
_outputDataBuffer.pSample = mftOutSample;
mftProcessOutput = _pTransform->ProcessOutput(0, 1, &_outputDataBuffer, &processOutputStatus);
if (mftProcessOutput != MF_E_TRANSFORM_NEED_MORE_INPUT)
{
CHECK_HR(_outputDataBuffer.pSample->SetSampleTime(llVideoTimeStamp), "Error setting MFT sample time.\n");
CHECK_HR(_outputDataBuffer.pSample->SetSampleDuration(llSampleDuration), "Error setting MFT sample duration.\n");
IMFMediaBuffer *buf = NULL;
DWORD bufLength;
CHECK_HR(_outputDataBuffer.pSample->ConvertToContiguousBuffer(&buf), "ConvertToContiguousBuffer failed.\n");
CHECK_HR(buf->GetCurrentLength(&bufLength), "Get buffer length failed.\n");
BYTE * rawBuffer = NULL;
auto now = GetTickCount();
printf("Writing sample %i, spacing %I64dms, sample time %I64d, sample duration %I64d, sample size %i.\n", _frameCount, now - _lastSendAt, llVideoTimeStamp, llSampleDuration, bufLength);
fFrameSize = bufLength;
fDurationInMicroseconds = 0;
gettimeofday(&fPresentationTime, NULL);
buf->Lock(&rawBuffer, NULL, NULL);
memmove(fTo, rawBuffer, fFrameSize);
FramedSource::afterGetting(this);
buf->Unlock();
SafeRelease(&buf);
frameSent = true;
_lastSendAt = GetTickCount();
}
SafeRelease(&pBuffer);
SafeRelease(&mftOutSample);
break;
}
}
else {
printf("No sample.\n");
}
SafeRelease(&videoSample);
}
if (!frameSent)
{
envir().taskScheduler().triggerEvent(eventTriggerId, this);
}
return;
done:
printf("MediaFoundationH264LiveSource doGetNextFrame failed.\n");
}
};
int main()
{
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
MFStartup(MF_VERSION);
TaskScheduler* scheduler = BasicTaskScheduler::createNew();
UsageEnvironment* env = BasicUsageEnvironment::createNew(*scheduler);
in_addr dstAddr = { 127, 0, 0, 1 };
Groupsock rtpGroupsock(*env, dstAddr, 1233, 255);
rtpGroupsock.addDestination(dstAddr, 1234, 0);
RTPSink * rtpSink = H264VideoRTPSink::createNew(*env, &rtpGroupsock, 96);
MediaFoundationH264LiveSource * mediaFoundationH264Source = MediaFoundationH264LiveSource::createNew(*env);
rtpSink->startPlaying(*mediaFoundationH264Source, NULL, NULL);
// This function call does not return.
env->taskScheduler().doEventLoop();
return 0;
}
|
3034ffde79d69a1fb0faf707efe1902afddfb095
|
[
"C++"
] | 1
|
C++
|
JohnMTrimbleIII/mediafoundationsamples
|
4c4b01f9ec9195991f9aa5f39d6168ab0e69ff33
|
cc38c16d9fef883b45c91645dcd4b1786d6a8890
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Quiz_solver
{
public partial class Form2 : Form, IView
{
public Form2()
{
InitializeComponent();
}
#region inferfejsu
public decimal points { get; set; }
public bool end_of_test { get; set; }
public string pytanie
{
set
{
textBoxQuestion.Text = value;
}
}
public string odp1
{
set
{
textBoxA.Text = value;
}
}
public string odp2
{
set
{
textBoxB.Text = value;
}
}
public string odp3
{
set
{
textBoxC.Text = value;
}
}
public string odp4
{
set
{
textBoxD.Text = value;
}
}
public decimal num1
{
get; set;
}
public decimal num2
{
get; set;
}
public decimal num3
{
get; set;
}
public decimal num4
{
get; set;
}
public decimal time
{
get
{
return Decimal.Parse(label_time.Text);
}
set
{
label_time.Text = value.ToString();
}
}
#endregion
public event Action New_Question;
public event Action Points_summary;
private void button_next_Click(object sender, EventArgs e)
{
check_answers();
Points_summary?.Invoke();
timer1.Stop();
textBoxC.Visible = false;
checkBoxC.Visible = false;
textBoxD.Visible = false;
checkBoxD.Visible = false;
checkBoxA.Checked = false;
checkBoxB.Checked = false;
checkBoxC.Checked = false;
checkBoxD.Checked = false;
checkBoxA.Enabled = true;
checkBoxB.Enabled = true;
checkBoxC.Enabled = true;
checkBoxD.Enabled = true;
if (end_of_test == true)
{
this.Hide();
var form3 = new Form3(points);
form3.Closed += (s, args) => this.Close();
form3.Show();
}
else
{
next_question_for_both_functions();
}
}
private void form2_FormClosed(object sender, FormClosedEventArgs e)
{
this.Close();
}
private void Form2_Load(object sender, EventArgs e)
{
next_question_for_both_functions();
}
private void next_question_for_both_functions()
{
New_Question?.Invoke();
if (textBoxC.Text != "")
{
textBoxC.Visible = true;
checkBoxC.Visible = true;
}
if (textBoxD.Text != "")
{
textBoxD.Visible = true;
checkBoxD.Visible = true;
}
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000; // 1 second
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
time--;
if (time == 0)
{
timer1.Stop();
checkBoxA.Enabled = false;
checkBoxB.Enabled = false;
checkBoxC.Enabled = false;
checkBoxD.Enabled = false;
}
label_time.Text = time.ToString();
}
private void check_answers()
{
if (checkBoxA.Checked == false)
{
num1 = 0;
}
if (checkBoxB.Checked == false)
{
num2 = 0;
}
if (checkBoxC.Checked == false)
{
num3 = 0;
}
if (checkBoxD.Checked == false)
{
num4 = 0;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Quiz_solver
{
class Presenter
{
private int index = 0;
IView view;
Model model;
List<Questions> list;
public Presenter(IView view, Model model)
{
this.view = view;
this.model = model;
this.view.New_Question += Next_Question;
this.view.Points_summary += Points_summary;
}
private void Next_Question()
{
list = model.ReadXML();
try
{
view.num1 = Decimal.Parse(list[index].valA);
view.num2 = Decimal.Parse(list[index].valB);
view.num3 = Decimal.Parse(list[index].valC);
view.num4 = Decimal.Parse(list[index].valD);
view.odp1 = list[index].ansA;
view.odp2 = list[index].ansB;
view.odp3 = list[index].ansC;
view.odp4 = list[index].ansD;
view.pytanie = list[index].question;
view.time = Decimal.Parse(list[index].time);
}
catch (System.ArgumentOutOfRangeException)
{
}
index++;
if (index == list.Count)
{
view.end_of_test = true;
}
}
private void Points_summary()
{
view.points = model.Points_summary(view.num1, view.num2, view.num3, view.num4);
}
}
}
<file_sep># MVP-Quiz-Solver
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Collections;
using System.Xml.Serialization;
using System.Windows.Forms;
using System.Timers;
namespace Quiz_solver
{
class Model
{
public List<Questions> listOfQuestions = new List<Questions>();
private decimal points = 0, l = 0;
string filePath = string.Empty;
public List<Questions> ReadXML()
{
// Create an instance of the XmlSerializer specifying type and namespace.
if (l == 0)
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "Pliki XML (*.xml)|*.xml";
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//Get the path of specified file
filePath = openFileDialog.FileName;
}
}
}
l=1;
Console.WriteLine("Reading with XmlReader");
XmlSerializer serializer = new XmlSerializer(typeof(List<Questions>));
FileStream fs = new FileStream(filePath, FileMode.Open);
XmlReader reader = XmlReader.Create(fs);
List<Questions> list;
list = (List<Questions>)serializer.Deserialize(reader);
fs.Close();
return list;
}
public decimal Points_summary(decimal i, decimal j, decimal k, decimal l)
{
points = points + i+j+k+l;
Console.WriteLine(points);
return points;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Quiz_solver
{
interface IView
{
bool end_of_test { get; set; }
string pytanie {set; }
string odp1 { set; }
string odp2 {set; }
string odp3 {set; }
string odp4 {set; }
decimal num1 { get; set; }
decimal num2 { get; set; }
decimal num3 { get; set; }
decimal num4 { get; set; }
decimal points { set; }
decimal time {set; }
event Action Points_summary;
event Action New_Question;
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Quiz_solver
{
public class Questions //class describing single question
{
public string index { get; set; }
public string question { get; set; }
public string ansA { get; set; }
public string ansB { get; set; }
public string ansC { get; set; }
public string ansD { get; set; }
public string time { get; set; }
public string valA { get; set; }
public string valB { get; set; }
public string valC { get; set; }
public string valD{ get; set; }
public Questions(string index, string question, string ansA, string ansB, string ansC, string ansD, string valA, string valB, string valC, string valD, string time)
{
this.index = index;
this.question = question;
this.ansA = ansA;
this.ansB = ansB;
this.ansC = ansC;
this.ansD = ansD;
this.valA = valA;
this.valB = valB;
this.valC = valC;
this.valD = valD;
this.time = time;
}
public Questions() { }
public override string ToString()
{
return index + question + ansA + ansB + ansC + ansD + valA + valB + valC + valD + time;
}
}
}
|
dca1382687c2406c658f024384b59012247ea729
|
[
"Markdown",
"C#"
] | 6
|
C#
|
DanielBroczkowski/MVP-Quiz-Solver
|
50a6f121144460cf201d76ef530e23627e04ce43
|
906a69a6936fba78a2c9d004a6cc1e20a9a33648
|
refs/heads/master
|
<repo_name>raileanualex03/snake<file_sep>/Game.cpp
#include "Game.h"
#include <iostream>
# include <conio.h>
# include <Windows.h>
void Game::run()
{
printf("Hi, %s !", name.c_str());
printf(" \n Let's have a fun time!\n");
system("pause");
generateRandomPoint();
while (isFinished() == false) {
Sleep(500);
if (_kbhit()) {
switch (_getch()) {
case 'a':
currentDirection = LEFT;
break;
case 'w':
currentDirection = UP;
break;
case 's':
currentDirection = DOWN;
break;
case 'd':
currentDirection = RIGHT;
break;
}
}
snake.move(currentDirection);
if (eatenPoint() == true) {
snake.eatPoint(point, currentDirection);
generateRandomPoint();
}
system("cls");
if (isFinished() == true)
break;
putSnakeInTable();
showTable();
restoreTable();
}
printf("Congratulations! \n Your score was: %d :) \n", score);
system("pause");
}
void Game::showTable()
{
printf("___________________\n");
for (int i = 0; i < length;i++) {
printf("|");
for (int j = 0; j < width;j++) {
if (table[i][j] == 0)
std::cout << " ";
else
std::cout << table[i][j]<<" ";
}
printf("|");
std::cout << "\n";
}printf("____________________\n");
printf("SCORE=%d\n", score);
}
void Game::generateRandomPoint()
{
int line = rand() % (length-2)+1;
int column = rand() % (width-2)+1;
pair pointt = pair{ line, column };
point = pointt;
}
bool Game::isFinished()
{
if (snake.isFinished() == true)
return true;
if (snake.getCoordinates()[0].first < 0 || snake.getCoordinates()[0].second < 0)
return true;
if (snake.getCoordinates()[0].first >= length || snake.getCoordinates()[0].second >= width)
return true;
return false;
}
void Game::putSnakeInTable()
{
for (pair p : snake.getCoordinates()) {
table[p.first][p.second] = 7;
}
table[snake.getCoordinates()[0].first][snake.getCoordinates()[0].second] = 4;
// putting also the point here
table[point.first][point.second] = 9;
}
void Game::restoreTable()
{
std::vector<std::vector<int>> newTable;
for (int i = 0; i < length; i++) {
std::vector<int> line;
for (int j = 0; j < width; j++) {
line.push_back(0);
}
newTable.push_back(line);
}
table = newTable;
}
bool Game::eatenPoint()
{
if (snake.getCoordinates()[0].first == point.first && snake.getCoordinates()[0].second == point.second)
{
score += 15;
return true;
}
else {
return false;
}
}
<file_sep>/Game.h
#pragma once
#include "Snake.h"
# include <string>
class Game
{
private:
std::vector<std::vector<int>> table;
Snake& snake;
int length, width;
int currentDirection = UP;
pair point;
int score = 0;
public:
std::string name{ " " };
public:
Game(char* name, Snake& snake, int l, int w) : name{ name }, snake { snake }, length{ l }, width{ w }{
for (int i = 0; i < length; i++) {
std::vector<int> line;
for (int j = 0; j < width; j++) {
line.push_back(0);
}
table.push_back(line);
}
};
void run();
void showTable();
void generateRandomPoint();
bool isFinished();
void putSnakeInTable();
void restoreTable();
bool eatenPoint();
};
<file_sep>/main.cpp
# include "Game.h"
# include "Snake.h"
#include <conio.h>
int main()
{
printf(" Welcome to Snake 2020\n");
system("color f4");
char name[64];
printf("\n\n Please enter your name: "); scanf("%s", name);
int number;
pair p1{ 3, 3 };
pair p2{ 4, 4 };
std::vector<pair> pairs;
pairs.push_back(p1);
pairs.push_back(p2);
Snake s = Snake(2, pairs);
Game game{ name, s, 8, 8 };
//Game game{ name, s, 8, 8 };
while (1) {
printf(" Menu \n");
printf("1.Start\n");
printf("2.Change name\n");
printf("3.Settings\n");
printf("0.Exit\n");
printf("Your choice is: "); scanf("%d", &number);
switch (number) {
case 1:
game.run();
break;
case 2:
printf("Enter new name: "); scanf("%s", name);
game.name = name;
printf("Name changed!\n");
break;
case 3:
printf("To be done...\n");
break;
case 0:
exit(0);
}
}
return 0;
}<file_sep>/README.md
# Snake
Just implementing the classic Snake game in C++.
Enjoy it if you see it :)
<file_sep>/Snake.cpp
// Snake.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include "Snake.h"
void Snake::move(int direction)
{
for (int i = coordinates.size()-1; i >= 1; i--)
coordinates[i] = coordinates[i-1];
if (direction == RIGHT) {
coordinates[0].second++;
}
else if (direction == LEFT)
coordinates[0].second--;
else if (direction == UP)
coordinates[0].first--;
else if (direction == DOWN)
coordinates[0].first++;
}
void Snake::eatPoint(pair p, int direction)
{
this->size++;
this->coordinates.insert(coordinates.begin(), p);
if (direction == RIGHT) {
coordinates[0].second++;
}
else if (direction == LEFT)
coordinates[0].second--;
else if (direction == UP)
coordinates[0].first--;
else if (direction == DOWN)
coordinates[0].first++;
}
bool Snake::isFinished()
{
for (auto i = 1; i < coordinates.size(); i++) {
if (coordinates[0].first == coordinates[i].first && coordinates[0].second == coordinates[i].second)
return true;
}
return false;
}
std::vector<pair> Snake::getCoordinates()
{
return coordinates;
}
<file_sep>/Snake.h
#pragma once
#include <vector>
# define pair std::pair<int, int>
# define LEFT 1
# define RIGHT 2
# define UP 3
# define DOWN 4
class Snake
{
private:
int size;
std::vector<pair> coordinates;
public:
Snake(int size, std::vector<pair> c) : size{ size }, coordinates{ c }{};
void move(int direction);
void eatPoint(pair p, int direction);
bool isFinished();
std::vector<pair> getCoordinates();
};
|
7d193b3b18f0f6159686b072bb0f9f6dd040f513
|
[
"Markdown",
"C++"
] | 6
|
C++
|
raileanualex03/snake
|
577fa15200b234204fbf0f9d86721d3f852631d6
|
e01685e2ecd0bcab6116cfbe57da109755095900
|
refs/heads/master
|
<repo_name>masonauseth/unit1<file_sep>/unit1/src/app/App.java
package app;
import java.util.Random;
import java.util.Scanner;
public class App {
public static void main(String[] args) throws Exception {
cool("Mason");}
public static String cool(String a){
System.out.println(a + " is cool");
return (a);
}
}
|
219fd4f89ff1e6f29961e440e92b19f1f870e475
|
[
"Java"
] | 1
|
Java
|
masonauseth/unit1
|
e517ec051e520a7edc3b2e3f19b9aa2861359867
|
9dfa249f7cb9ccd846de478b071f7da8a7ec4899
|
refs/heads/master
|
<file_sep>// ScrollTop Btn
window.onscroll = function() {
scrollFunction()
};
function scrollFunction() {
if (document.body.scrollTop > 200 || document.documentElement.scrollTop > 200) {
document.getElementById("toTop").style.display = "block";
} else {
document.getElementById("toTop").style.display = "none";
}
}
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
// ScrollTop Btn
// Mobile Menu
function openNav() {
var x = window.matchMedia("(max-width:900px)");
if (x.matches) {
document.getElementById("mySidepanel").style.width = "80%";
} else {
document.getElementById("mySidepanel").style.width = "35%";
}
};
function closeNav() {
document.getElementById("mySidepanel").style.width = "0";
};
$('.sidepanel').ready(function(){
$('.the_menu').click(function () {
document.getElementById("mySidepanel").style.width = "0";
});
});
//End Mobile menu
// Phone Menu
function openPhone() {
var x = window.matchMedia("(max-width:900px)");
if (x.matches) {
document.getElementById("myOpenphone").style.width = "80%";
} else {
document.getElementById("myOpenphone").style.width = "25%";
}
};
function closePhone() {
document.getElementById("myOpenphone").style.width = "0";
};
//End Phone Menu
// spSlider
$(document).ready(function(){
$('.spSlider').owlCarousel({
loop: true,
margin: 10,
dots: false,
responsive:{
0:{
items:1
},
500:{
items:1
},
900:{
items:2
},
1024:{
items:3
},
1600:{
items:3
}
}
});
});
// End spSlider
//Testimonials Slider
$(document).ready(function(){
$('.testimonialSlider').owlCarousel({
loop: true,
autoplay: true,
autoplayTimeout: 10000,
center: true,
margin: 10,
dots: true,
nav: true,
responsive:{
0:{
items:1
},
500:{
items:1
},
900:{
items:1
},
1200:{
items:1
},
1920:{
items:1
}
},
onInitialized: function(e) {
$('.counter').text('1 / ' + this.items().length)
console.log();
}
});
var testimonialSlider = $('.testimonialSlider');
testimonialSlider.owlCarousel();
$('.nextBtn').click(function() {
testimonialSlider.trigger('next.owl.carousel');
});
$('.prevBtn').click(function() {
testimonialSlider.trigger('prev.owl.carousel', [300]);
});
var owl = $('.owl-carousel');
owl.owlCarousel();
owl.on('changed.owl.carousel', function(e) {
$('.counter').text(++e.page.index + ' / ' + e.item.count)
});
});
//End Testimonials Slider
// File Upload JPG
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
// End File Upload JPG
<file_sep><!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="shortcut icon" href="images/favicon.png" type="img/x-icon">
<meta name="description" content="...">
<meta name="keywords" content="...">
<meta name="author" content="...">
<title>Document</title>
<!--OWL-->
<link rel="stylesheet" href="css/owl.carousel.css">
<link rel="stylesheet" href="css/owl.theme.default.css">
<!--CSS-->
<link rel="stylesheet" href="css/jquery.fancybox.css">
<link rel="stylesheet" href="css/jquery-ui.min.css">
<link rel="stylesheet" href="css/styles.css">
<!--Fonts-->
<link href="https://fonts.googleapis.com/css?family=Montserrat:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i|Open+Sans:300,300i,400,400i,600,600i,700,700i,800,800i&display=swap&subset=cyrillic" rel="stylesheet">
<!--FontAwesome-->
<link rel="stylesheet" href="css/font-awesome-4.7.0/css/font-awesome.min.css">
</head>
<body>
<!--ToTop-->
<button class="toTop" onclick="topFunction()" id="toTop"><i class="fa fa-angle-up" aria-hidden="true"></i></button>
<!--End ToTop-->
<!--Header-->
<header class="header" id="header">
<div class="left_box"></div>
<div class="right_box"></div>
<div class="container">
<div class="row">
<div class="top_menu">
<div class="logo">
<a href="index.html" class="logo_link">
<img src="images/logo.png" alt="" class="logo_img">
</a>
</div>
<div class="contacts">
<div class="phone one_numb">
<i class="fa fa-phone" aria-hidden="true"></i>
<p class="phone_number">+38 (012) 345 67 89</p>
</div>
<div class="phone two_numb">
<i class="fa fa-phone" aria-hidden="true"></i>
<p class="phone_number">+38 (012) 345 67 89</p>
</div>
<div class="hamburger">
<button class="openbtn" onclick="openNav()">
<i class="fa fa-bars" aria-hidden="true"></i>
</button>
</div>
<button class="callback" data-fancybox data-src="#callback" href="javascript:;">
Заказать обратный звонок
</button>
<div id="mySidepanel" class="sidepanel">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<img src="images/logolight.png" alt="" class="sidepanel_logo">
<a class="the_menu" href="index.html">Главная</a>
<a class="the_menu" href="#whatis">Звездная карта - это</a>
<a class="the_menu" href="#whyis">Лучший подарок</a>
<a class="the_menu" href="#mapsize">Резмеры и цены</a>
<a class="the_menu" href="#paydelivery">Оплата и доставка</a>
<a class="the_menu" href="#testimonials">Отзывы</a>
<a class="the_menu" href="#contacts">Контакты</a>
<a class="the_menu" href="starmap.html">Заказать карту</a>
<div class="sidepanel_social">
<a href="#" class="insta">
<img src="images/instalight.png" alt="">
</a>
<a href="#" class="fb">
<img src="images/fblight.png" alt="">
</a>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="title_box">
<p class="title_text">
Ваша карта звездного неба
</p>
<h2 class="title_slogan">
Так сложились звезды
</h2>
<a class="get_order" href="starmap.html">
Заказать карту
</a>
<ul class="socials">
<li>
<a href="#" class="instagram">
<img src="images/instadark.png" alt="">
</a>
</li>
<li>
<a href="#" class="fb">
<img src="images/fbdark.png" alt="">
</a>
</li>
</ul>
</div>
</div>
</div>
</header>
<!--End Header-->
<!--What Is-->
<section class="whatis" id="whatis">
<div class="container">
<div class="row">
<div class="block_title">
<h2>
Что такое звездная карта
</h2>
<div class="left_squares">
<div class="grey_sq"></div>
<div class="white_sq"></div>
<div class="transparent_sq"></div>
<div class="b_line"></div>
<div class="first_line"></div>
<div class="sec_line"></div>
<div class="third_line"></div>
</div>
</div>
</div>
</div>
<div class="container left_blank">
<div class="row">
<div class="whatis_img">
<img src="images/whatisstarmap.png" alt="">
</div>
<div class="whatis_text">
<p>
Звездная карта - это карта абсолютно реалистичного ночного звездного неба. Именно так в этом городе и в этой время были расположены звезды.
<br><br>Для того, чтобы каждая карта получилась уникальной мы берем Йельский каталог ярких звёзд - это каталог звёзд, которые теоретически можно увидеть невооружённым глазом (имеющих звёздную величину 6,5m или ярче).
<br><br>Используя параметры звёзд из каталога, вычисляем их положение на небесной сфере.
<br><br>Кроме того, используя показатель цвета B−V определяем цвет звезды. По заданным кординатам, времени наблюдения и другим параметрам, определяем видимые в данный момент звёзды, их координаты и переводим их из сферической системы координат на плоскость.
<br><br>Таким образом получается реалистичная карта ночного звёздного неба.
<br><br>В качестве отображаемых созвездий мы используем данные по 88 официальным созвездиям, утверждённым Международным астрономическим союзом на I генеральной ассамблее в 1922 году. Предлагаем вам на выбор использовать их латинские или русские названия.
<br><br>Система генерирует Вашу карту звезд и вставляет получившийся рассчет в оформление.
<br><br>Именно так мы фотографируем звезды именно в тот момент и в том городе, чтобы вы запомнили этот момент.
</p>
<div class="order_btn">
<a class="order_map" href="starmap.html">
Заказать карту
</a>
</div>
</div>
</div>
</div>
</section>
<!--End What Is-->
<!--Why Is-->
<section class="whyis" id="whyis">
<div class="container">
<div class="row">
<div class="block_title">
<h2>
Зачем нужна звездная карта
</h2>
<div class="right_squares">
<div class="grey_sq"></div>
<div class="white_sq"></div>
<div class="transparent_sq"></div>
<div class="b_line"></div>
<div class="first_line"></div>
<div class="sec_line"></div>
<div class="third_line"></div>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="whyis_text">
<p>
<strong>Звездная карта</strong> это уникальный и неповторимый подарок который поможет Вам запомнить этот день. Это настоящее расположение звезд, именно такое как было в тот день, который вы хотите запомнить!
<br>Интересно, а как были расположены звёзды в самый счастливый для вас момент? Был ли это день вашей свадьбы, первый поцелуй или рождение ребёнка? День рождения вашей второй половинки? Покупка собственной машины или квартиры? А может просто момент, который вы не хотите забыть? Подарите карту звёздного неба, чтобы всегда помнить ту особенную ночь!
</p>
</div>
</div>
<div class="row">
<div class="owl-carousel owl-theme spSlider">
<div class="item">
<img src="images/wedding.png" alt="">
<p class="first">
День
</p>
<p class="second">
свадьбы
</p>
</div>
<div class="item">
<img src="images/bday.png" alt="">
<p class="first">
День
</p>
<p class="second">
рождения
</p>
</div>
<div class="item">
<img src="images/birth.png" alt="">
<p class="first">
Рождение
</p>
<p class="second">
ребенка
</p>
</div>
</div>
<div class="order_map_btn">
<a class="order_btn" href="starmap.html">
Заказать карту
</a>
</div>
</div>
</div>
</section>
<!--End Why Is-->
<!--Map Size-->
<section class="mapsize" id="mapsize">
<div class="container">
<div class="row">
<div class="block_title">
<h2>
Какой размер карты выбрать
</h2>
<div class="left_squares">
<div class="grey_sq"></div>
<div class="white_sq"></div>
<div class="transparent_sq"></div>
<div class="b_line"></div>
<div class="first_line"></div>
<div class="sec_line"></div>
<div class="third_line"></div>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row mapsize_display">
<div class="mapsize_text">
<p>
Карта звездного неба подогнана под самые удобные форматы для печати и интерьера.
<br>Небольшая карта 21 см на 29,7 см
<br>Средняя карта - 29,7 см на 42.
<br>И большая карта - 84,1 см 118,9 см., которая займет основное акцентное место на стене
<br>Распечатанная карта доставляется без рамы, в красивом крепком тубусе.
<br>Карты помещаются в стандартные рамки соответвующих размеров. Обрезка карты не требуется.
<br>Дизайн карт ориентирован вертикально.
</p>
<a class="order_btn" href="starmap.html">
Заказать карту
</a>
</div>
<div class="mapsize_clouds">
<div class="cloud_1">
<img src="images/cloud.png" alt="">
<h3 class="map_name">
Звездная карта фрмата А4
</h3>
<p class="map_size">
(Размер 21 см*29,7 см)
</p>
<p class="map_price">
500 грн
</p>
</div>
<div class="cloud_2">
<img src="images/cloud.png" alt="">
<h3 class="map_name">
Звездная карта фрмата А3
</h3>
<p class="map_size">
(Размер 29,7 см*42 см)
</p>
<p class="map_price">
700 грн
</p>
</div>
<div class="cloud_3">
<img src="images/cloud.png" alt="">
<h3 class="map_name">
Звездная карта фрмата А2
</h3>
<p class="map_size">
(Размер 42 см*59,4 см)
</p>
<p class="map_price">
950 грн
</p>
</div>
<div class="cloud_4">
<img src="images/cloud.png" alt="">
<h3 class="map_name">
Звездная карта фрмата А0
</h3>
<p class="map_size">
(Размер 84,1 см*118,9 см)
</p>
<p class="map_price">
950 грн
</p>
</div>
</div>
</div>
<div class="row mapsize_mobile">
<div class="mapsize_mobile_text">
<p>
Карта звездного неба подогнана под самые удобные форматы для печати и интерьера.
Небольшая карта 21 см на 29,7 см
Средняя карта - 29,7 см на 42.
И большая карта - 84,1 см 118,9 см., которая займет основное акцентное место на стене
Распечатанная карта доставляется без рамы, в красивом крепком тубусе.
Карты помещаются в стандартные рамки соответвующих размеров. Обрезка карты не требуется.
Дизайн карт ориентирован вертикально.
</p>
<div class="mobile_clouds">
<div class="mc">
<img src="images/cloud.png" alt="">
<p class="name">
Звездная карта фрмата А4
</p>
<p class="size">
(Размер 21 см*29,7 см)
</p>
<p class="price">
500 грн
</p>
</div>
<div class="mc">
<img src="images/cloud.png" alt="">
<p class="name">
Звездная карта фрмата А3
</p>
<p class="size">
(Размер 29,7 см*42 см)
</p>
<p class="price">
700 грн
</p>
</div>
<div class="mc">
<img src="images/cloud.png" alt="">
<p class="name">
Звездная карта фрмата А2
</p>
<p class="size">
(Размер 42 см*59,4 см)
</p>
<p class="price">
950 грн
</p>
</div>
<div class="mc">
<img src="images/cloud.png" alt="">
<p class="name">
Звездная карта фрмата А0
</p>
<p class="size">
(Размер 84,1 см*118,9 см)
</p>
<p class="price">
950 грн
</p>
</div>
</div>
</div>
</div>
</div>
</section>
<!--End Map Size-->
<!--Pay And Delivery-->
<section class="paydelivery" id="paydelivery">
<div class="container">
<div class="row">
<div class="block_title">
<h2>
Как получить звездную карту
</h2>
<div class="right_squares">
<div class="grey_sq"></div>
<div class="white_sq"></div>
<div class="transparent_sq"></div>
<div class="b_line"></div>
<div class="first_line"></div>
<div class="sec_line"></div>
<div class="third_line"></div>
</div>
<p class="paydelivery_text">
Для того что бы получить Вашу уникальною карту ночного звездного неба , необходимо сделать совсем не много. Ваго лишь три шага отделяют Вас от идеального подарка
</p>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="map_steps">
<div class="step_3">
<p class="step_title">
Шаг 3
</p>
<img src="images/step.png" alt="">
<p class="step_stage">
Заберите карту
</p>
<p class="step_text">
Мы отправляем “Новой почтой”, “Укрпочтой”, а также любыми другими перевозчиками, которые работают в вашем городе.
</p>
<button class="show_more" data-fancybox data-src="#buy_starmap" href="javascript:;">
Узнать подробней
</button>
</div>
<div class="step_2">
<p class="step_title">
Шаг 2
</p>
<img src="images/step.png" alt="">
<p class="step_stage">
Оплатите карту
</p>
<p class="step_text">
Вы получите свою карту после полной оплаты. Оплата совершается сразу при заказе всеми возможными способами в защищенном режиме. Срок поступления средств и выполнения заказа от 1 минуты до 3-х часов
</p>
<button class="show_more" data-fancybox data-src="#buy_starmap" href="javascript:;">
Узнать подробней
</button>
</div>
<div class="step_1">
<p class="step_title">
Шаг 1
</p>
<img src="images/step.png" alt="">
<p class="step_stage">
Отправить заявку
</p>
<p class="step_text">
Вы можете заказать Звездною карту одним из удобных для Вас способов: заполнить и отправить заявку прямо сейчас нажав на кнопку "Заказать карту" или позвонить по телефону +38(012) 345 67 89
</p>
<a class="order_btn" href="starmap.html">
Заказать карту
</a>
</div>
</div>
<div class="map_steps_mobile">
<div class="mobile_step">
<p class="ms_name">Шаг 1</p>
<p class="ms_title">
Оплатите карту
</p>
<p class="ms_text">
Вы получите свою карту после полной оплаты. Оплата совершается сразу при заказе всеми возможными способами в защищенном режиме. Срок поступления средств от 1 минуты до 3-х дней
</p>
<div class="ms_btns">
<button class="ms_order_btn" data-fancybox data-src="#order-starmap" href="javascript:;">
Заказать карту
</button>
</div>
</div>
<div class="mobile_step">
<p class="ms_name">Шаг 2</p>
<p class="ms_title">
Отправить заявку
</p>
<p class="ms_text">
Вы можете заказать Звездною карту одним из удобных для Вас способов: заполнить и отправить заявку прямо сейчас нажав на кнопку "Заказать карту" или позвонить по телефону
+38(012) 345 67 89
</p>
<div class="ms_btns_right">
<button class="ms_order_btn_r" data-fancybox data-src="#buy_starmap" href="javascript:;">
Узнать подробней
</button>
</div>
</div>
<div class="mobile_step">
<p class="ms_name">Шаг 3</p>
<p class="ms_title">
Заберите карту
</p>
<p class="ms_text">
Мы отправляем “Новой почтой”, “Укрпочтой”, а также любыми другими перевозчиками, которые работают в вашем городе.
</p>
<div class="ms_btns_right">
<button class="ms_order_btn_r" data-fancybox data-src="#buy_starmap" href="javascript:;">
Узнать подробней
</button>
</div>
</div>
</div>
</div>
</div>
</section>
<!--End Pay And Delivery-->
<!--Testimonials-->
<section class="testimonials" id="testimonials">
<div class="container">
<div class="row">
<div class="owl-carousel owl-theme testimonialSlider">
<div class="item">
<div class="testimonial_block">
<div class="block_title">
<h2>
Что о нас говорят клиенты
</h2>
<div class="left_squares">
<div class="grey_sq"></div>
<div class="white_sq"></div>
<div class="transparent_sq"></div>
<div class="b_line"></div>
<div class="first_line"></div>
<div class="sec_line"></div>
<div class="third_line"></div>
</div>
</div>
<div class="image_box_mobile">
<img src="images/testimonials.png" alt="">
</div>
<div class="testimonial_text">
<p class="name">
Алина
</p>
<p class="text">
Знаете, что означает эта картина звездного неба?
Когда мы с Ильей первый раз встретились, в этот день звезды были именно в таком положении, а в самом снизу та самая дата.
Чуть выше написано
«On this day we did not even think to keep our eyes on the sky...” правда офигенно? тоже Илья придумал
Повесим ее сегодня в доме, так классно вписалась в интерьер....
</p>
<div class="show_more_btn">
<button class="show_testimonial" data-fancybox data-src="#show_testimonial" href="javascript:;">
Просмотреть весь отзыв
</button>
</div>
</div>
</div>
<div class="image_box">
<img src="images/testimonials.png" alt="">
</div>
</div>
</div>
</div>
<div class="row">
<!--Controls-->
<div class="controls">
<div class="prevnext">
<button class="nextBtn">Предыдущий отзыв</button>
<button class="prevBtn">Следующий отзыв</button>
</div>
<div class="counter"></div>
<div class="get_testimonial">
<button class="get" data-fancybox data-src="#get_testimonial" href="javascript:;">
Оставить свой отзыв
</button>
</div>
</div>
<!--End Controls-->
</div>
</div>
</section>
<!--End Testimonials-->
<!--Contacts-->
<section class="ourcontacts" id="contacts">
<div class="left_box"></div>
<div class="right_box">
<div class="container">
<div class="row">
<div class="block_title">
<h2>
Как с нами связаться
</h2>
<div class="right_squares">
<div class="grey_sq"></div>
<div class="white_sq"></div>
<div class="transparent_sq"></div>
<div class="b_line"></div>
<div class="first_line"></div>
<div class="sec_line"></div>
<div class="third_line"></div>
</div>
</div>
</div>
<div class="row">
<div class="contact_dsc">
<p class="contact_box_text">
Мы принимаем заявки круглосуточно и без выходных.
Но наш менеджер всё понимающий живой человек…так что он свяжется с Вами лишь в рабочие дни с 09:00 до 18:00.
А также Вы можете связаться с нами позвонив по телефону, отправив письмо на электронный адрес или с помощью формы обратной связи
</p>
<div class="contacts_info">
<ul>
<li class="phones">
<div class="phone">
<img src="images/phone-dark.png" alt="">
<p class="text">
+38 (012) 345-67-89
</p>
</div>
<div class="phone">
<img src="images/phone-dark.png" alt="">
<p class="text">
+38 (012) 345-67-89
</p>
</div>
</li>
<li class="emails">
<div class="email">
<img src="images/mail-dark.png" alt="">
<p class="text">
<EMAIL>
</p>
</div>
</li>
</ul>
</div>
<form class="contact_form">
<input type="name" class="name" placeholder="Ваше имя">
<input type="email" class="email" placeholder="Ваш email">
<textarea name="info" id="info" rows="5" placeholder="Ваше сообщеие"></textarea>
<button class="send_msg">
Отправить
</button>
</form>
</div>
</div>
</div>
</div>
</section>
<!--End Contacts-->
<footer class="footer" id="footer">
<div class="container">
<div class="row">
<div class="block_title">
<h2>
Не забудте подписаться
</h2>
<div class="left_squares">
<div class="grey_sq"></div>
<div class="white_sq"></div>
<div class="transparent_sq"></div>
<div class="b_line"></div>
<div class="first_line"></div>
<div class="sec_line"></div>
<div class="third_line"></div>
</div>
</div>
</div>
<div class="row">
<div class="footer_info">
<p>
Мы присылаем только информацию о предложениях и напоминания к праздникам.
Подпишитесь сейчас, чтобы не потерять такую чудесною идею подарка
</p>
</div>
<form class="footer_form">
<input type="name" class="name" placeholder="<NAME>">
<input type="email" class="email" placeholder="Ваш email">
<input type="phone" class="phone" placeholder="Ваш телефон">
<div class="send_btn">
<button class="send">
Подписаться
</button>
</div>
</form>
</div>
</div>
<div class="container copyright">
<div class="row">
<p class="copyright_info">
StarMaps © Copyright 2019. Разработано компанией <a href="#">SFdevelop</a>
</p>
<div class="footer_social">
<a href="#" class="fb">
<img src="images/fbdark.png" alt="">
</a>
<a href="#" class="insta">
<img src="images/instadark.png" alt="">
</a>
</div>
</div>
</div>
</footer>
<!--Callback-->
<div class="mobile-search-content fancybox-content" style="display: none;" id="callback">
<div class="callback_modal">
<div class="callback_block_title">
<h2 class="callback_modal_title">
Заказать обратный звонок
</h2>
<div class="left_squares">
<div class="grey_sq"></div>
<div class="white_sq"></div>
<div class="transparent_sq"></div>
<div class="b_line"></div>
<div class="first_line"></div>
<div class="sec_line"></div>
</div>
</div>
<form class="callback_form">
<div class="callback_name">
<label for="callname" class="callname">Ваше имя *</label>
<input type="callname" name="callname" id="callname">
</div>
<div class="callback_email">
<label for="callemail" class="callemail">Ваше email *</label>
<input type="callemail" name="callemail" id="callemail">
</div>
<p class="call_subs">* поля обязательные для заполнения</p>
<div class="call_agree_box">
<div class="call_check">
<input type="checkbox" class="call_agree" id="call_agree" value="agree" checked>
<label for="call_agree">Я даю согласие на обработку персональных данных</label>
</div>
</div>
<div class="call_send_msg_btns">
<button class="call_sent_msg">Отправить</button>
</div>
</form>
</div>
</div>
<!--End Callback-->
<!--Buy Starmap-->
<div class="mobile-search-content fancybox-content" style="display: none;" id="buy_starmap">
<div class="buy_starmap_modal">
<div class="buy_starmap_block_title">
<h2 class="buy_starmap_modal_title">
Как оплатить Ваш заказ
</h2>
<div class="left_squares">
<div class="grey_sq"></div>
<div class="white_sq"></div>
<div class="transparent_sq"></div>
<div class="b_line"></div>
<div class="first_line"></div>
<div class="sec_line"></div>
</div>
</div>
<p class="buy_starmap_text">
Вы получите свою карту после полной оплаты.
После того как наш менеджер с Вами свяжется и уточнит все детали заказа, он вышлет Вам банковские реквизиты для оплаты на Ваш телефон или email
Сделав оплату - сообщите нам об этом позвонив по телефону. Сохраняйте чек до подтверждения о зачислении средств! После оплаты на карту мы отправляем Ваш заказ любым указанным Вами способом. Срок поступления средств от 1-го до 3-х дней, это зависит от условий Вашего банка
</p>
</div>
</div>
<!--End Buy Starmap-->
<!--Fansybox Testimonial-->
<div class="mobile-search-content fancybox-content" style="display: none;" id="show_testimonial">
<div class="show_testi_modal">
<p class="name">
Алина
</p>
<p class="text">
Знаете, что означает эта картина звездного неба?
Когда мы с Ильей первый раз встретились, в этот день звезды были именно в таком положении, а в самом снизу та самая дата.
Чуть выше написано
«On this day we did not even think to keep our eyes on the sky...” правда офигенно? тоже Илья придумал
Повесим ее сегодня в доме, так классно вписалась в интерьер....
</p>
</div>
</div>
<!--End Fancybox Testimonial-->
<div class="mobile-search-content fancybox-content" style="display: none;" id="get_testimonial">
<div class="testimonials_modal">
<div class="modal_leftbox">
<div class="testimon_block_title">
<h2 class="testimonial_modal_title">
Оставьте свой отзыв
</h2>
<div class="left_squares">
<div class="grey_sq"></div>
<div class="white_sq"></div>
<div class="transparent_sq"></div>
<div class="b_line"></div>
<div class="first_line"></div>
<div class="sec_line"></div>
</div>
</div>
<p class="testimonial_modal_text">
Здесь Вы можете оставить свой отзыв. Будем очень благодарны если Вы загрузите свое фото вместе с Вашей звездной картой.
Внимание!!! Для качественного отображения размер фотографии должен быть 747х747
</p>
<form class="testimonial_modal_form">
<div class="tmf_name_box">
<label for="yourname" class="yourname"> Ваше имя *</label>
<input type="yourname" name="yourname" id="yourname">
</div>
<div class="tmf_email_box">
<label for="youremail" class="youremail"> Ваш email *</label>
<input type="youremail" name="youremail" id="youremail">
</div>
<div class="tmf_phone_box">
<label for="yourphone" class="yourphone"> Ваш телефон *</label>
<input type="yourphone" name="yourphone" id="yourphone">
</div>
<div class="tmf_msg_box">
<label for="yourmsg" class="yourmsg"> Ваш отзыв *</label>
<textarea type="yourmsg" name="yourmsg" id="yourmsg" rows="5"></textarea>
</div>
<p class="tmf_subs">* поля обязательные для заполнения</p>
<div class="tmf_agree_box">
<div class="tmf_check">
<input type="checkbox" class="tmf_agree" id="tmf_agree" value="agree" checked>
<label for="tmf_agree">Я даю согласие на обработку персональных данных</label>
</div>
</div>
<div class="tmf_send_msg_btns">
<button class="tmf_sent_msg">Отправить</button>
<input class="input_file" type='file' onchange="readURL(this);" />
</div>
</form>
</div>
<div class="modal_rightbox">
<img id="blah" src="images/avatar.png" alt="" class="avatar">
</div>
</div>
</div>
<!--End Fansybox Testimonial-->
<!--End Modal-->
<!--Scripts-->
<script src="js/jquery-3.4.1.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script src="js/jquery.fancybox.js"></script>
<script src="js/owl.carousel.js"></script>
<script src="js/main.js"></script>
</body>
</html>
|
16a7135a86b041bfff22c3b252e3143b57aaa623
|
[
"JavaScript",
"HTML"
] | 2
|
JavaScript
|
KolomoetsAndrey/starmaps
|
8c799ddc0bcec087e2dbfd6736ac279812d88d4e
|
2e0ff5663c4afda8f27baa0ec6fe4c8bcf9c01e8
|
refs/heads/main
|
<repo_name>bhumijgupta/daenode<file_sep>/src/index.ts
#!/usr/bin/env node
import childProcess from "child_process";
import chowkidar from "chokidar";
import path from "path";
import treeKill from "tree-kill";
import { Writable } from "stream";
type restartEvent = "Manual reload" | "File change";
class Daenode {
private previousReload: undefined | NodeJS.Timeout;
private processExited = true;
private nodeProcess!: childProcess.ChildProcessByStdio<Writable, null, null>;
private pathsToWatch = [
path.join(process.cwd(), "/**/*.js"),
path.join(process.cwd(), "/**/*.json"),
path.join(process.cwd(), "/**/*.env.*"),
];
constructor() {
if (process.argv.length !== 3)
console.error(
`Expected 1 argument, recieved ${process.argv.length - 2} arguments`
);
else this.init();
}
init = async () => {
this.nodeProcess = await this.startProcess();
this.watchFiles();
process.once("SIGINT", async () => await this.exitHandler("SIGINT"));
process.once("SIGTERM", async () => await this.exitHandler("SIGTERM"));
process.stdin.on("data", async (chunk) => {
const str = chunk.toString();
if (str === "rs\n") await this.reload("Manual reload");
});
};
private startProcess = () => {
const nodeProcess = childProcess.spawn("node", [process.argv[2]], {
stdio: ["pipe", process.stdout, process.stderr],
});
this.processExited = false;
// First exit happens and then close
// Exit ->child process exits but stdio is not closed
// Close -> Child process stdio is also closed
// nodeProcess.on("exit", (code) => {
// this.print("log",`Process ${nodeProcess.pid} exited with code ${code}`);
// });
process.stdin.pipe(nodeProcess.stdin);
nodeProcess.stdin.on("close", () => {
process.stdin.unpipe(nodeProcess.stdin);
process.stdin.resume();
});
nodeProcess.on("close", (code, signal) => {
this.processExited = true;
this.print(
"log",
`Process ${nodeProcess.pid} exited with ${
code ? `code ${code}` : `signal ${signal}`
}`
);
});
nodeProcess.on("error", (err) => {
this.processExited = true;
this.print("log", `Failed to start process ${process.argv[2]}`);
});
return nodeProcess;
};
private print = (type: keyof Console, message: string) => {
console[type](`[DAENODE]: ${message}`);
};
private watchFiles = () => {
chowkidar
.watch(this.pathsToWatch, {
ignored: "**/node_modules/*",
ignoreInitial: true,
})
.on("all", async () => {
let timeoutKey = setTimeout(async () => {
if (this.previousReload) clearTimeout(this.previousReload);
await this.reload("File change");
}, 1000);
this.previousReload = timeoutKey;
});
};
private reload = async (event: restartEvent) => {
this.print("info", `${event} detected. Restarting process`);
await this.stopProcess();
this.nodeProcess = this.startProcess();
};
private stopProcess = async () => {
if (this.processExited) return true;
return new Promise<boolean>((resolve, reject) => {
treeKill(this.nodeProcess.pid, "SIGTERM", (err) => {
if (err) treeKill(this.nodeProcess.pid, "SIGKILL", () => {});
});
const key = setInterval(() => {
if (this.processExited) {
clearInterval(key);
resolve(true);
}
}, 500);
});
};
private exitHandler = async (signal: string) => {
this.print("debug", `Detected signal ${signal}. Exiting...`);
await this.stopProcess();
process.exit();
};
}
new Daenode();
<file_sep>/README.md
# Daenode
Daenode is a simple nodemon clone writen in Typescript in under 120 lines. Created for educational purposes.
[](https://youtu.be/5rAtUryNJB4)
## Features
1. Detect file changes and restart node process
2. Perform manual restart by typing `rs`
### Things learnt
1. Spawning a new process in node
2. Different exit signals
3. Debounce function
4. NodeJS Streams
5. NPM package to CLI binary
6. Watching files and directories for changes
|
06b9152a69cf996ab0226353f323ff9216589462
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
bhumijgupta/daenode
|
9c581010eb777823d7b680125b718a1429e904bb
|
25bb050101b04efa66fd3e834bc807ae7b112603
|
refs/heads/master
|
<repo_name>jornathanJ/angular-winform-seed<file_sep>/src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { WjGridModule } from 'wijmo/wijmo.angular2.grid';
import { WjGridFilterModule } from 'wijmo/wijmo.angular2.grid.filter';
import { WjGridMultirowModule } from 'wijmo/wijmo.angular2.grid.multirow';
import { WjGridSheetModule } from 'wijmo/wijmo.angular2.grid.sheet';
import { WjInputModule } from 'wijmo/wijmo.angular2.input';
import { WjNavModule } from 'wijmo/wijmo.angular2.nav';
import { WjChartModule } from 'wijmo/wijmo.angular2.chart';
import { WjChartAnalyticsModule } from 'wijmo/wijmo.angular2.chart.analytics';
import { WjChartFinanceModule } from 'wijmo/wijmo.angular2.chart.finance';
import { WjChartHierarchicalModule } from 'wijmo/wijmo.angular2.chart.hierarchical';
import { WjChartInteractionModule } from 'wijmo/wijmo.angular2.chart.interaction';
import { WjChartRadarModule } from 'wijmo/wijmo.angular2.chart.radar';
import { WjOlapModule } from 'wijmo/wijmo.angular2.olap';
import { WjGaugeModule } from 'wijmo/wijmo.angular2.gauge';
import { WjViewerModule } from 'wijmo/wijmo.angular2.viewer';
import { SampleOneComponent } from './pages/sample-one/sample-one.component';
@NgModule({
imports: [
BrowserModule, FormsModule,
WjGridModule,
WjGridFilterModule,
WjGridMultirowModule,
WjGridSheetModule,
WjInputModule,
WjNavModule,
WjChartModule,
WjChartAnalyticsModule,
WjChartFinanceModule,
WjChartHierarchicalModule,
WjChartInteractionModule,
WjChartRadarModule,
WjOlapModule,
WjGaugeModule,
WjViewerModule,
],
declarations: [AppComponent, HelloComponent, SampleOneComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/src/app/hello.component.ts
import { Component, Input, OnInit, AfterViewInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import * as wjcCore from 'wijmo/wijmo';
import * as wjcGrid from 'wijmo/wijmo.grid';
import { WjGridModule } from 'wijmo/wijmo.angular2.grid';
import { WjInputModule } from 'wijmo/wijmo.angular2.input';
import * as Plotly from 'plotly.js-dist';
@Component({
selector: 'hello',
templateUrl: './hello.component.html',
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
@Input() name: string;
uuid: string = "test1234";
divPlotly: Plotly.PlotlyHTMLElement;
layout: any;
config: any;
data: any;
wijmoData: any;
constructor() {
this.data = [
{ x: 0, y: 0 },
{ x: 1, y: 1 },
{ x: 2, y: 2 },
{ x: 3, y: 3 },
{ x: 4, y: 4 },
{ x: 5, y: 5 },
{ x: 6, y: 6 },
{ x: 7, y: 7 },
{ x: 8, y: 8 },
{ x: 9, y: 9 },
];
}
ngOnInit() {
}
ngAfterViewInit(): void {
this.divPlotly = <Plotly.PlotlyHTMLElement>document.getElementById(this.uuid);
}
drawChart() {
let xValue: number[] = [];
let yValue: number[] = [];
for (let data of this.data) {
xValue.push(data.x);
yValue.push(data.y);
}
var trace1 = {
x: xValue,
y: yValue,
line: {
dash: 'solid',
shape: 'linear'
},
mode: 'lines+markers',
type: 'scatter'
};
Plotly.newPlot(
this.uuid,
[trace1],
this.layout,
this.config
);
}
bindDataToGrid() {
this.wijmoData = this.data;
}
clear() {
this.wijmoData = null;
Plotly.react(this.uuid,
[],
this.layout,
this.config
);
}
}<file_sep>/README.md
# angular-winform-seed
[Edit on StackBlitz ⚡️](https://stackblitz.com/edit/angular-winform-seed)
|
0141ddf173ad14b0698640436f0b9fb90a253c45
|
[
"Markdown",
"TypeScript"
] | 3
|
TypeScript
|
jornathanJ/angular-winform-seed
|
c3ae350a28dd99c5f0e97d1e307548047b804fdf
|
ca494f9de8532135cb34a3590a2ab449b3114409
|
refs/heads/master
|
<repo_name>prateek-sys/mysite<file_sep>/mysite/blog/admin.py
from django.contrib import admin
from .models import Post
# class PostAdmin(admin.ModelAdmin):
# fields = ['title', 'slug', 'summary', 'content', 'published', 'created']
admin.site.register(Post)
|
cef0f0bffc3d13b254cedf802fef545f46399790
|
[
"Python"
] | 1
|
Python
|
prateek-sys/mysite
|
e9aac816a67261d59474c9a5ea05d060f5849315
|
9ad90e69c2e9c852af474b81f9f5688b91f27c66
|
refs/heads/master
|
<repo_name>ejelome/archaic<file_sep>/js/f2e-web-toolkit/src/jsx/components/button.jsx
import React, {createClass, PropTypes} from 'react';
import classNames from 'classnames';
export default createClass({
propTypes: {
className: PropTypes.string,
initialCount: PropTypes.number
},
getDefaultProps: function () {
return {
className: classNames(['btn']),
initialCount: 0
};
},
getInitialState: function () {
return {
count: this.props.initialCount
};
},
handleClick: function () {
this.setState({
count: this.state.count + 1
});
},
render: function () {
return (
<button className={this.props.className}
onClick={this.handleClick}>{this.state.count}</button>
);
}
});
<file_sep>/py/collect-cdn/collect.py
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""collect.py:
Download and move CDN files based from collect.ini.
"""
import configparser
import logging
import os
import re
import shutil
import requests
from lxml import html
logging.basicConfig(level=logging.INFO)
logging.getLogger('requests').setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
config = configparser.ConfigParser()
config_file = 'collect.ini'
config.readfp(open(config_file))
cdn = dict(config.items('cdn'))
option = dict(config.items('option'))
files = list(filter(None, cdn['file'].split('\n')))
urls = list(filter(None, cdn['url'].split('\n')))
files_from_files = [i.split('/')[-1] for i in files]
files_from_urls = [i.split('/')[-1].split('.')[0] for i in urls]
def save_file(obj, name, dest):
"""Save a file to `dest`.
Args:
name (str): The name of the file after save.
obj (obj): The `request` file object.
dest (str): The destination of the file.
Returns:
bool: True if writing isSuccessful, otherwise, False.
Examples:
>>> obj = requests.get('https://path/to/file.ext', stream=True)
>>> name = 'file.ext'
>>> dest = 'ext/subdir'
>>> save_file(obj, name, dest)
INFO:__main__:Success: file.ext downloaded
INFO:__main__:Success: file.ext moved to ext/subdir
"""
name_only = name.split('.')[0]
dot_length = len(file_name.split('.')) - 1
file_path = os.path.join(dest, name)
if os.path.exists(file_path) and os.path.isfile(file_path):
logger.warning('Skipped: %s: already exists', name)
elif (name_only not in files_from_files
and name_only not in files_from_urls):
logger.warning('Ignored: %s file name mismatch', name)
elif dot_length > int(option['dot_length']):
logger.warning('Ignored: %s file name length mismatch', name)
else:
if not (os.path.exists(dest) or os.path.isdir(dest)):
os.makedirs(dest)
with open(name, 'wb') as output:
if obj.ok:
for block in obj.iter_content(1024):
if block:
output.write(block)
logger.info('Success: %s downloaded', name)
shutil.move(name, file_path)
logger.info('Success: %s moved to %s', name, dest)
return True
return False
for file_ in files:
file_path = os.path.join(cdn['path'], file_)
if '/' in file_:
file_base_path = file_.split('/')[0]
file_path = os.path.join(cdn['path'], file_base_path)
file_ = file_.split('/')[-1]
files.append(file_)
request = requests.get(file_path)
dom = html.fromstring(request.text)
dom_urls = dom.xpath(option['xpath'])
for url in dom_urls:
if re.search(r'{}'.format(option['extension']), url):
file_obj = requests.get(url, stream=True)
file_name = url.split('/')[-1]
file_extension = file_name.split('.')[-1]
dir_path = os.path.join(file_extension, option['subdir'])
save_file(file_obj, file_name, dir_path)
for url in urls:
file_obj = requests.get(url, stream=True)
file_name = url.split('/')[-1]
file_extension = file_name.split('.')[-1]
dir_path = os.path.join(file_extension, option['subdir'])
save_file(file_obj, file_name, dir_path)
<file_sep>/html-css/web-design/README.md
web-design
==========
Beginner web design experiments
-------------------------------------------------------------------------------
Usage
-----
``` bash
$ python -m http.server
```
Then visit <http://localhost:8000>.
-------------------------------------------------------------------------------
Transcript
----------
> Brief overview about these portfolio links:
>
> NOTE:
>
> The following portfolios are old, and don't describe my current capacity/knowledge/ability any longer,
> however, they were my foundations that played a big role for what I can be able to do today. Some of
> them, although validates, holds bad practices that I have long been avoided.
>
> I really don't have the time to create new design templates, as I'm currently spending my time and
> knowledge on FeWSE (http:///fewse.org/), for this reason, I apologize.
> ...
>
> 1. Ragnashop (/portfolio/ragnashop/)
> - This was my very first project during my learning period of XHTML and CSS.
> - I'm not familiar with Minimalist Design or KISS back then,
> though I never have realized that I was already doing it.
>
> 2. Full Metal Alchemist (/portfolio/fma/)
> - This was my second project during my learning period, but not for XHTML and CSS, but for Microformats.
> - The goal of the experiment was to include an hReview in the template while using some complicated CSS properties
> like z-index, pseudo-class selectors (:before and :after) and a bit of aesthetic design (though again, Minimalist).
>
> 3. Blog Name (/portfolio/blogname/)
> - This was my very first task (as a test) from cr8v web solutions (http://www.cr8vwebsolutions.com/).
> - Though sadly, during the final interview, the CEO boycotted me, maybe they realized that the design was ugly enough, though usable.
>
> 4. Design Project (/portfolio/designproject/)
> - This was my second task (another test) from my College instructor.
> - Although my batchmates told me he liked it, I never heard from him directly, so I considered it a failed opportunity and moved forward.
>
> 5. Yagit's Blog (/portfolio/yagitsblog/)
> - This was the first WordPress theme I ever made, it was created during August 2010.
> - I intentionally made it look dull and tried to adopt <NAME>'s site (http://useit.com/).
> - However, later I realized that Web Usability is not everything, and aesthetics plays a big role in User Experience.
>
> 6. WebCafe (/portfolio/webcafe/)
> - This was my third task, and was simply a test from SimpleX Internet (converting PSD to Valid HTML/CSS).
> - Fortunately, I passed and was able to join their company for 3 months.
>
> 7. pPC (or pRO Pricelist Check: /portfolio/ppc/)
> - This was the 2nd personal project, which aims to improve the previous static page (Ragnashop).
> - It was also my second WordPress theme which I made when I was working at SimpleX Internet.
> - It's different from the previous one (Yagit's Blog) because I'm trying to insert aesthetic (though, I'm much comfortable doing Minimalist and KISS design approach).
> - I was only able to finish the registration, login, forgot password, and admin pages.
>
> You can try to login using this account:
>
> * username: e-jelome
> * password: <PASSWORD>
>
> You can also view the following pages:
>
> 1. Login (/portfolio/ppc/wp-login.php?redirect_to=/portfolio/ppc/wp-admin/profile.php)
> 2. Registration (/portfolio/ppc/wp-login.php?action=register)
> 3. Forgot Password (/portfolio/ppc/wp-login.php?action=lostpassword)
>
> I wasn't able to continue it, because of job hunting and because, later, http://noobsociety.com/ expired (July 9 2011).
-------------------------------------------------------------------------------
Drafts
------
| Name | Created | Included | Reason |
| :---------------- | :-------- | :-------: | :-------- |
| FarmForSale | 2009 Nov | ✕ | WordPress |
| [Eye Health] | 2010 Mar | ✓ | |
| [Ragna Store] | 2010 May | ✓ | |
| [Ragnashop] | 2010 May | ✓ | |
| [Ragnashop V2] | 2010 May | ✓ | |
| [Microformats] | 2010 May | ✓ | |
| [Photo-Shoot] | 2010 May | ✓ | |
| [Design Template] | 2010 July | ✓ | |
| [Blog Name] | 2010 July | ✓ | |
| [Design Project] | 2010 Aug | ✓ | |
| Yagit's Blog | 2010 Aug | ✕ | WordPress |
| WebCafe | 2010 Nov | ✕ | Ownership |
| pPC | 2011 Apr | ✕ | WordPress |
[Eye Health]: ./drafts/eye-health
[Ragna Store]: ./drafts/ragna-store
[Ragnashop]: ./drafts/ragnashop
[Ragnashop V2]: ./drafts/ragnashop-v2
[Microformats]: ./drafts/microformats
[Photo-Shoot]: ./drafts/photo-shoot
[Design Template]: ./drafts/design-template
[Blog Name]: ./drafts/blog-name
[Design Project]: ./drafts/design-project
-------------------------------------------------------------------------------
`Created: 2010 Aug`
<file_sep>/py/wooji/wooji/__init__.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""__init__.py: Make these modules accessible when wooji is called."""
import app
import config
import defaults
import db
import dbmodels
import filters
import helpers
import routes
import server
import session
<file_sep>/py/resume/config.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""config.py: Default configuration."""
import datetime
import os
# Paths (Absolute):
ROOT = os.path.abspath(os.path.dirname(__file__))
LOGS = '{base}/logs'.format(base=ROOT)
DATABASE = '{base}/database.sqlite'.format(base=ROOT)
TEMPLATES = '{base}/templates'.format(base=ROOT)
EMAILS = '{base}/emails'.format(base=TEMPLATES)
PAGES = '{base}/pages'.format(base=TEMPLATES)
ASSETS = '{base}/assets'.format(base=ROOT)
IMAGES = '{base}/img'.format(base=ASSETS)
SESSION = '{base}/session'.format(base=ROOT)
COOKIE = '/'
# Paths (Relative):
FAVICON = '/favicon.ico'
PHOTO = '/img/photo.png'
CSS = '/css/style-0.1.css'
JS = '/js/script-0.1.js'
# Server:
SERVER = 'wsgiref'
HOST = 'localhost'
PORT = 8080
DEBUG = True
# Meta:
SITE_NAME = 'ejelome'
SITE_URI = 'http://localhost'
SITE_TAGLINE = 'Web designer, Python Programmer, Emacs user'
SITE_DESCRIPTION = 'This is an online hresume and temporary website.'
LICENSE_URL = 'https://github.com/ejelome/resume/blob/master/LICENSE.md'
# Upload:
UPLOAD_MAX_SIZE = (1024 * 1024) * 2 # (1024 bytes -> 1kb, 1024kb -> 1mb)
UPLOAD_ALLOWED_EXTENSIONS = ['ico', 'gif', 'png', 'jpg', 'jpeg']
UPLOAD_ALLOWED_MIME_TYPES = [
'image/x-icon',
'image/gif',
'image/png',
'image/jpeg'
]
# Image:
THUMB_SIZE = 150, 150
# Mailbox:
SMTP_SERVER = ''
SMTP_EMAIL = ''
SMTP_USERNAME = ''
SMTP_PASSWORD = ''
# Session:
SESSION_TYPE = 'file'
SESSION_AUTO = True
# Cookie (and morsel instances):
COOKIE_EXPIRES = (
datetime.datetime.today() +
datetime.timedelta(days=3)
).strftime('%a, %d %b %Y %H:%M:%S')
COOKIE_MAX_AGE = 60 * 60 * 24 * 3 # 3 days
COOKIE_HTTP_ONLY = True
COOKIE_COMMENT = ''
COOKIE_SECURE = ''
COOKIE_VERSION = ''
<file_sep>/py/resume/templates/pages/site/footer.html
## /site/footer.html
<%
import datetime
year = datetime.datetime.today().strftime('%Y')
%>
<div class="footer">
<p class="copyright">Copyright © ${year}
<a href="/">${meta['site_name']}</a>.
<a href="${meta['license_url']}"
rel="nofollow">Some rights reserved.</a>
</p>
</div>
<file_sep>/py/alchemified/app/README.md
app README
==========
Getting Started
---------------
### Run app ###
``` bash
$ pip install -e app/
$ initialize_app_db app/development.ini
$ pserve app/development.ini --reload
```
### Test app ###
``` bash
$ pip install -e app/[testing]
$ py.test --cov=app/ -q
```
<file_sep>/js/rw-test/src/components/header.jsx
import React, {Component} from 'react';
const Profile = (props) => {
return (
<div className="profile">
<img className="photo"
src={props.photo}
width={100}
height={100}
alt={props.name} />
<h1 className="name">{props.name}</h1>
<p className="bio">{props.bio}</p>
</div>
);
}
export default class Header extends Component {
constructor() {
super();
this.state = {
name: "",
bio: "",
photo: ""
};
}
componentDidMount() {
fetch('/data/user.json')
.then((response) => {
return response.json();
}).then((json) => {
this.setState(json);
});
}
render() {
return (
<header>
<Profile {...this.state} />
</header>
);
}
}
<file_sep>/py/template-blog/mysite/_posts/000 - python-introduction.markdown
---
draft: False
title: Python Introduction
summary: Python is an interpreted, dynamically-typed, object-oriented,
high-level, and a general-purpose programming language created by Guido
<NAME>. It was inspired by the ABC programming language and was
named after the BBC's show — Monty Python's Flying Circus.
author: EJelome
date: 2012/11/07 10:35:00
updated: 2012/10/07 10:35:00
featured_image: /img/python.png
categories: Python
tags: python, programming, programming language, interpreted,
dynamically-typed, object-oriented, high-level, general-purpose, abc
---
Why Python?
-----------
There's a lot of things why I personally liked Python. There's a lot of things
why I personally liked Python. There's a lot of things why I personally liked
Python. There's a lot of things why I personally liked Python. There's a lot of
things why I personally liked Python. There's a lot of things why I personally
liked Python.
<file_sep>/py/beginner-blog/requirements.txt
Django==1.6.2
Markdown==2.4
Pillow==2.3.1
Pygments==1.6
argparse==1.2.1
sorl-thumbnail==11.12
wsgiref==0.1.2
<file_sep>/js/f2e-web-toolkit/README.md
f2e-web-toolkit
===============
Front-end web toolkit with `nvm` and `iojs`
-------------------------------------------------------------------------------
Prerequisites
-------------
### `nvm`: ###
``` bash
# Install nvm:
$ wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.25.0/install.sh | bash
# Reload .bashrc:
$ . ~/.bashrc
```
### `iojs`: ###
``` bash
# Install iojs:
$ nvm install iojs
# Activate iojs:
$ nvm use iojs
```
-------------------------------------------------------------------------------
Usage
-----
### Install dependencies: ###
``` bash
$ npm install
```
### Run compiler and watcher: ###
``` bash
$ npm run start
```
### Run web server: ###
_Open another terminal (or tab, e.g.`ctrl+shft+t`)._
``` bash
$ cd dist/
$ python -m http.server
```
Then visit <http://localhost:8000>.
-------------------------------------------------------------------------------
License
-------
`f2e-web-toolkit` is licensed under [MIT].
[MIT]: ./LICENSE.md
-------------------------------------------------------------------------------
`Created: 2015 Feb`
<file_sep>/js/rw-test/README.md
rw-test
=======
A failed exam test with `react` and `webpack`
-------------------------------------------------------------------------------
<!-- markdown-toc start - Don't edit this section. Run M-x markdown-toc-generate-toc again -->
**Table of Contents**
- [rw-test](#rw-test)
- [Setup](#setup)
- [Install dependencies](#install-dependencies)
- [Usage](#usage)
- [Build `dist/`](#build-dist)
- [Run dev server](#run-dev-server)
<!-- markdown-toc end -->
-------------------------------------------------------------------------------
Setup
-----
### Install dependencies ###
``` bash
$ npm install
```
-------------------------------------------------------------------------------
Usage
-----
### Build `dist/` ###
``` bash
$ npm run build
```
### Run dev server ###
``` bash
$ npm run start
```
-------------------------------------------------------------------------------
`Created: 2017 Apr`
<file_sep>/py/wooji/README.md
wooji
=====
A small MVC web framework on top of `Bottle`
-------------------------------------------------------------------------------
Prerequisites
-------------
### `virtualenvwrapper`: ###
``` bash
# Install virtualenvwrapper:
$ sudo pip install virtualenvwrapper
# Update .bashrc:
$ echo '
export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=$HOME/Devel
source /usr/local/bin/virtualenvwrapper.sh
' >> ~/.bashrc
# Reload .bashrc:
. ~/.bashrc
# Create Devel directory:
$ mkdir -p ${PROJECT_HOME}
```
-------------------------------------------------------------------------------
Setup
-----
``` bash
# Create and switch to virtualenv:
$ mkproject -p /usr/bin/python2 wooji
# Clone repository in current directory:
$ git clone https://github.com/ejelome/wooji .
# Install packages:
$ pip install -r requirements.txt
```
-------------------------------------------------------------------------------
Run
---
``` bash
$ python wooji.py app run
```
Then visit <http://localhost:8080>.
-------------------------------------------------------------------------------
Documentation
-------------
See [homepage] for the complete documentation.
-------------------------------------------------------------------------------
License
-------
`wooji` is licensed under [MIT].
[homepage]: http://localhost:8080
[MIT]: ./LICENSE.md
-------------------------------------------------------------------------------
`Created: 2014 July`
<file_sep>/py/resume/models.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""models.py: Database tables and columns."""
from modules import db
db = db.DB()
# Users:
db.create(
'Users',
dict(
id='INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT NOT NULL',
email='TEXT UNIQUE NOT NULL',
password='<PASSWORD>',
token='TEXT NOT NULL',
verified='BOOLEAN NOT NULL DEFAULT False'
)
)
# Tokens:
db.create(
'Tokens',
dict(
id='INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT NOT NULL',
key='TEXT UNIQUE NOT NULL',
value='TEXT UNIQUE NOT NULL',
user_id='INTEGER UNIQUE NOT NULL'
)
)
# Profiles:
db.create(
'Profiles',
dict(
id='INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT NOT NULL',
summary='TEXT',
photo='TEXT',
given_name='TEXT',
additional_name='TEXT',
family_name='TEXT',
nickname='TEXT',
uri='TEXT',
tel='TEXT',
alt_email='TEXT',
user_id='INTEGER UNIQUE NOT NULL'
)
)
# Addresses:
db.create(
'Addresses',
dict(
id='INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT NOT NULL',
street='TEXT',
locality='TEXT',
region='TEXT',
postal_code='TEXT',
country='TEXT',
user_id='INTEGER UNIQUE NOT NULL'
)
)
# Educations:
db.create(
'Educations',
dict(
id='INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT NOT NULL',
degree='TEXT',
major='TEXT',
school='TEXT',
uri='TEXT',
start='INTEGER',
end='INTEGER',
user_id='INTEGER NOT NULL'
)
)
# Experiences:
db.create(
'Experiences',
dict(
id='INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT NOT NULL',
position='TEXT',
description='TEXT',
company='TEXT',
uri='TEXT',
start='INTEGER',
end='INTEGER',
user_id='INTEGER NOT NULL'
)
)
# Skills:
db.create(
'Skills',
dict(
id='INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT NOT NULL',
name='TEXT',
slug='TEXT',
url='TEXT',
user_id='INTEGER NOT NULL'
)
)
# Affiliations:
db.create(
'Affiliations',
dict(
id='INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT NOT NULL',
name='TEXT',
uri='TEXT',
user_id='INTEGER NOT NULL'
)
)
# Publications:
db.create(
'Publications',
dict(
id='INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT NOT NULL',
title='TEXT',
uri='TEXT',
user_id='INTEGER NOT NULL'
)
)
<file_sep>/py/wooji/wooji/dbmodels.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""dbmodels.py: Import each app's models submodule."""
import os
import config
import db
import helpers
dir_names = helpers.get_modules(config.DIR_APPS)
base_name = os.path.basename(config.DIR_APPS)
for dir_name in dir_names:
module_format = '{}.{}'.format(base_name, dir_name)
module = helpers.custom_import(module_format)
module_path = module.__path__[0]
if 'models.py' in os.listdir(module_path):
submodule_format = '{}.{}.models'.format(base_name, dir_name)
helpers.custom_import(submodule_format)
db.Base.metadata.create_all(db.engine)
<file_sep>/py/alchemified/app/pytest.ini
[pytest]
testpaths = app
python_files = *.py
<file_sep>/py/wooji/apps/test/views.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""views.py: File description."""
import controllers as ctrl
routes = [
('/', ctrl.Test, '/test/index.html'),
('/test<:re:/?>', ctrl.test, '/test/index.html'),
('/json<:re:/?>', ctrl.json)
]
<file_sep>/py/beginner-blog/apps/blog/admin.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""admin.py: Blog models to register to appear on admin page."""
from django.contrib import admin
from models import Post, Category, Tag, Author
class PostAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
class CategoryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Post, PostAdmin)
admin.site.register(Category, CategoryAdmin)
admin.site.register(Tag)
admin.site.register(Author)
<file_sep>/py/wooji/__init__.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""__init__.py: Make wooji accessible throughout the application."""
import wooji
<file_sep>/py/wooji/requirements.txt
appdirs==1.4.3
Beaker==1.6.4
bottle==0.12.7
decorator==4.0.11
infinity==1.4
intervals==0.8.0
Mako==1.0.6
markdown2==2.3.3
MarkupSafe==1.0
marshmallow==2.13.4
packaging==16.8
pyparsing==2.2.0
six==1.10.0
SQLAlchemy==1.1.6
SQLAlchemy-Utils==0.32.13
validators==0.11.2
WTForms==2.1
WTForms-Alchemy==0.16.2
WTForms-Components==0.10.3
<file_sep>/py/wooji/wooji/defaults.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""defaults.py: Publicly accessible variables for the views."""
import wooji
wooji.app.BaseTemplate.defaults['wooji'] = wooji
<file_sep>/py/template-blog/mysite/_filters/rel_nofollow.py
#!/usr/bin/python
# filename: rel_nofollow.py
import re
import blogofile_bf as bf
def run(content):
"""Return all external links with a rel-nofollow attribute."""
enabled = bf.config.filters.rel_nofollow.enabled
site_uri = bf.site.data['site']['uri']
urls = re.findall('href="(.+?)"', content)
old_external_urls = []
new_external_urls = []
rel = 'rel="nofollow"'
if enabled:
for url in urls:
if not re.search(r'^(/|#|%s)' % site_uri, url):
old_external_urls.append(url)
for old_url in old_external_urls:
existing_rel = re.search('<a href="%s".+?rel="(.+?)".+?>' %\
old_url, content)
if existing_rel is not None:
old_link = existing_rel.group()
new_link = old_link.replace('rel="', 'rel="nofollow ')
content = content.replace(old_link, new_link)
else:
content = content.replace('<a href="%s"' % old_url,
'<a href="%s" %s' % (old_url, rel))
# Make sure there are no duplicate rel values
rels = re.findall('<a.+?rel="(.+?)"', content)
for rel in rels:
old_rels = rel.split(' ')
new_rels = ' '.join(set(old_rels))
content = content.replace('rel="%s"' % rel,
'rel="%s"' % new_rels)
return content
<file_sep>/py/template-blog/mysite/_filters/minify_html.py
#!/usr/bin/python
# filename: minify_html.py
import re
import blogofile_bf as bf
def run(content):
"""Return a minified web page version."""
enabled = bf.config.filters.minify_html.enabled
inline_elements = [
'a', 'abbr', 'acronym',
'b', 'bdo', 'big', 'br',
'cite', 'code',
'dfn',
'em',
'i', 'img', 'input', 'ins',
'kbd',
'label',
'q',
's', 'samp', 'select', 'small', 'span', 'strike', 'strong',
'sub', 'sup',
'textarea',
'u',
'var'
]
html_fixes = [
('\n|\r|\t|\n\r', ' '),
('\s{2,}', ' '),
('\s{1,}/>', '/>'),
('>\W<', '><'),
]
if enabled:
for fix in html_fixes:
content = re.sub(r'%s' % fix[0], fix[1], content)
for i in inline_elements:
for j in inline_elements:
content = content.replace('/%s><%s' % (i, j), '/%s> <%s' %\
(i, j))
links = re.findall(r'(<a.+?>)(.+?)</', content)
for link in links:
(tag, value) = link
new_tag = tag.strip()
new_value = value.strip()
content = content.replace('%s%s</' % (tag, value),
'%s%s</' % (new_tag, new_value))
return content.strip()
<file_sep>/py/alchemified/app/app/scripts/initializedb.py
from importlib import import_module
from json import load
from os.path import basename, dirname, join
from sys import argv, exit
from pyramid.paster import get_appsettings, setup_logging
from pyramid.scripts.common import parse_vars
from transaction import manager
from app.fixtures import __file__ as fixture_base_dir
from app.helpers import TreeHelper
from app.models import __file__ as model_base_dir
from app.models import __name__ as models_qualname
from app.models import get_engine, get_session_factory, get_tm_session
from app.models.__meta__ import Base
def usage(argv):
cmd = basename(argv[0])
print('usage: {} <config_uri> [var=value]'.format(cmd))
print('(example: "{} development.ini"'.format(cmd))
exit(1)
def main(argv=argv):
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
setup_logging(config_uri)
options = parse_vars(argv[2:])
settings = get_appsettings(config_uri, options=options)
engine = get_engine(settings)
Base.metadata.create_all(engine)
fixture_dir = dirname(fixture_base_dir)
model_tree = TreeHelper(model_base_dir)
model_modules = model_tree.modules()
with manager:
session_factory = get_session_factory(engine)
dbsession = get_tm_session(session_factory, manager)
for module in model_modules:
package = '{}.{}'.format(models_qualname, module)
module_ = import_module(package)
class_name_prefix = module.title()
class_name_suffix = 'Model'
class_name = '{}{}'.format(class_name_prefix, class_name_suffix)
class_obj = getattr(module_, class_name)
fixture_ext = 'json'
fixture_name = '{}.{}'.format(module, fixture_ext)
fixture_path = join(fixture_dir, fixture_name)
with open(fixture_path) as file_:
fixtures = load(file_)
[dbsession.add(class_obj(**f)) for f in fixtures]
<file_sep>/py/prodev-calc/requirements.txt
appdirs==1.4.3
bottle==0.12.7
packaging==16.8
pyparsing==2.2.0
six==1.10.0
<file_sep>/py/prodev-calc/README.md
prodev-calc
===========
Project-Developer project price calculator
-------------------------------------------------------------------------------
Setup
-----
``` bash
# Create a virtualenv:
$ virtualenv venv
# Activate virtualenv:
$ source venv/bin/activate
# Install dependencies:
$ pip install -r requirements.txt
```
-------------------------------------------------------------------------------
Usage
-----
```
$ python server.py
```
Then visit <http://localhost:8080>.
Or <http://localhost:8080/data.json> for `JSON`.
-------------------------------------------------------------------------------
License
-------
`prodev-calc` is licensed under [MIT].
[MIT]: ./LICENSE.md
-------------------------------------------------------------------------------
`Created: 2015 Feb`
<file_sep>/sh/shell-site-generator/src/posts/about.md
About
=====
Hello, I'm `ejelome`.
<file_sep>/py/beginner-blog/reset.sh
# Warning: Running this script will do the following:
# * Remove the files specified in .gitignore
# * Sync the models w/ the default values specified in the fixtures
# * Run the application server
#
# To run this program, do:
# $ ./reset.sh
#
# If that doesn't work, make it executable first, do:
# $ chmod +x reset.sh
# Remove ignored files:
git clean -Xf
# Sync models with default fixtures:
for i in syncdb runserver;
do ./manage.py $i;
done
<file_sep>/py/template-blog/mysite/_config.py
# -*- coding: utf-8 -*-
import datetime
# Defaults:
site.url = '/' # e.g., http://ejelome.com
site.name = 'EJelome'
site.abbr = 'Emmanuel-Jelome'
site.description = 'A Blog for Python'
blog = plugins.blog
blog.enabled = True
blog.url = '/blog'
blog.path = blog.url
blog.name = site.name
blog.description = site.description
blog.category_dir = '/'
blog.tag_dir = '/tag'
blog.post.url = '/:title'
blog.posts_per_page = 5
blog.auto_permalink.enabled = True
blog.auto_permalink.path = blog.post.url
blog.googleanlytics_id = 'UA-XXXXX-X'
blog.template_path = '_templates/blog'
blog.timezone = 'US/Eastern'
blog.disqus.enabled = True
# Site (site-wide related data):
today = datetime.date.today()
today_iso = today.strftime('%Y%m%d')
site.data = {
'site': {
'uri': site.url,
'name': site.name,
'abbr': site.abbr,
'tagline': site.description,
'lang': 'en-US',
'mime': 'application/xhtml+xml',
'charset': 'UTF-8',
},
'blog': {
'uri': blog.url
},
'category': {
'uri': blog.category_dir
},
'tag': {
'uri': blog.tag_dir
},
'search': {
'uri': '/search'
},
'author': {
'summary': 'I\'m <NAME>. I\'m a Web \
designer, Web standards advocate, Python Programmer, and \
an Aspiring Front-end Web Software Engineer. I\'m a \
middle-brained guy (left: 60%, right: 40%) who\'s been \
passionately learning more about Web development since \
January of 2010.',
'honorific': {
'prefix': '',
'suffix': ''
},
'first_name': 'Emmanuel-Jelome',
'middle_name': 'Ducusin',
'last_name': 'Fonseca',
'nickname': 'Yagit',
'full_name': '<NAME>',
'display_name': 'Emmanuel-Jelome',
'address': {
'type': 'home',
'post_office_box': '',
'street_address': 'No. 116. Dr. Sixto Ave.',
'extended_address': '',
'locality': 'Rosario',
'region': 'Pasig City',
'postal_code': '1609',
'country': {
'name': 'Philippines',
'abbr': 'PH'
}
},
'email': {
'type': 'pref',
'value': '<EMAIL>'
},
'tel': {
'type': 'cell',
'value': '+63.927.233.3049'
},
'uri': 'http://ejelome.com',
'educations': [
{'degree': {
'name': 'Bachelor of Science in Information Technology',
'abbr': 'B.S.I.T'
},
'major': 'None (but did graphic designs most of the time via \
Photoshop CS3)',
'school': {
'name': 'Lorma Colleges',
'abbr': '',
'uri': 'http://lorma.com'
},
'date': {
'start': '2005',
'start_iso': '20050606',
'end': '2009',
'end_iso': '20090328'
}},
{'degree': {
'name': 'Higher School Certificate',
'abbr': 'H.S.C'
},
'major': 'None', # required (used as summary)
'school': {
'name': 'La Union National High School',
'abbr': 'LUNHS',
'uri': 'http://202.91.162.20/LaUnionNationalHigh'
},
'date': {
'start': '2001',
'start_iso': '20050604',
'end': '2005',
'end_iso': '20050401'
}},
],
'experiences': [
{'position': 'Junior Webmaster',
'description': 'Fix / update websites, implement SEO, and \
convert approved print designs to web pages.',
'company': {
'name': 'TrueLogic Online Solutions Inc.',
'abbr': '',
'uri': 'http://truelogic.com.ph'
},
'duration': {
'start': 'July 2012',
'start_iso': '20120716',
'end': 'Present',
'end_iso': today_iso,
'period': '3 months'
}},
{'position': 'Junior Web Designer',
'description': 'Assist in designing / conversion of approved \
print designs to web pages.',
'company': {
'name': 'Osbourne Technologies Inc.',
'abbr': '',
'uri': 'http://zeva.co.uk'
},
'duration': {
'start': 'September 2011',
'start_iso': '20110914',
'end': 'December 2011',
'end_iso': '20111226',
'period': '3 months'
}},
{'position': 'HTML Coder',
'description': 'Convert print designs to valid XHTML/CSS web \
pages.',
'company': {
'name': 'SimpleX Internet Philippines, Inc.',
'abbr': '',
'uri': 'http://simplexi.com'
},
'duration': {
'start': ' January 2011',
'start_iso': '20110131',
'end': 'May 2011 ',
'end_iso': '20110506',
'period': '3 months'
}},
],
'skills': [
{'name': 'eXtensible Hypertext Markup Language',
'abbr': 'XHTML',
'uri': 'http://en.wikipedia.org/wiki/Xhtml'},
{'name': 'Cascading Style Sheets',
'abbr': 'CSS',
'uri': 'http://en.wikipedia.org/wiki/Css'},
{'name': 'Microformats',
'abbr': 'µf',
'uri': 'http://en.wikipedia.org/wiki/Microformats'},
{'name': 'JavaScript',
'abbr': 'JS',
'uri': 'http://en.wikipedia.org/wiki/Javascript'},
{'name': 'Python',
'abbr': 'Py',
'uri': 'http://en.wikipedia.org/wiki/Python'},
{'name': 'Mako',
'abbr': '',
'uri': 'http://en.wikipedia.org/wiki/Mako_(template_engine)'}
],
'affiliations': [
{'name': '<NAME>',
'abbr': 'JELOM',
'uri': ''},
],
'publications': [
{'name': 'None',
'abbr': '',
'uri': ''}
],
'interests': [
'User Experience',
'Web standards',
'Semantics',
'Web usability',
'Information Architecture',
'Web accessibility',
'Web performance',
'Search Engine Optimization',
'Regular Expressions',
],
'links': [
{'name': 'Google+',
'abbr': '',
'title': 'Google+',
'url': 'http://profiles.google.com/ejelome'},
{'name': 'Facebook',
'abbr': '',
'title': 'Facebook',
'url': 'http://facebook.com/ejeome'},
{'name': 'YouTube',
'abbr': '',
'title': 'YouTube',
'url': 'http://youtube.com/ejelome'},
{'name': 'Twitter',
'abbr': '',
'title': '@ejelome',
'url': 'http://twitter.com/ejelome'},
{'name': 'LinkedIn',
'abbr': '',
'title': 'LinkedIn',
'url': 'http://linkedin.com/in/ejelome'},
{'name': 'Stack Overflow',
'abbr': '',
'title': 'Stack Overflow',
'url': 'http://stackoverflow.com/users/642922/ejelome'},
{'name': 'Stack Overflow Careers 2.0',
'abbr': '',
'title': 'Stack Overflow Careers 2.0',
'url': 'http://careers.stackoverflow.com/ejelome'}
]
},
'favicon': {
'rel': 'icon',
'url': '/img/favicon.ico',
'type': 'image/x-icon'
},
'style': {
'rel': 'stylesheet',
'url': '/css/style-0.1.css',
'type': 'text/css',
'media': 'screen'
},
'script': {
'url': '/js/script-0.1.js',
'type': 'text/javascript'
},
'logo': {
'src': '/img/logo.png',
'alt': site.name,
'width': 64,
'height': 64
},
'pages': [
{'name': 'Blog',
'abbr': '',
'slug': 'blog',
'uri': '/blog',
'desc': 'Published posts, categories, and archives',
'sub_pages': [],
'robots': '',
'description': '',
'keywords': ''},
{'name': 'About',
'abbr': '',
'slug': 'about',
'uri': '/about',
'desc': 'Website and Author details',
'sub_pages': [
{'name': 'Website',
'abbr': '',
'slug': 'website',
'url': '/about/website',
'desc': 'Why this website was created'},
{'name': 'Author',
'abbr': '',
'slug': 'author',
'url': '/about/author',
'desc': 'Author\'s biography'}
],
'robots': '',
'description': '',
'keywords': ''},
{'name': 'Contact',
'abbr': '',
'slug': 'contact',
'uri': '/contact',
'desc': 'Author contact details',
'sub_pages': [],
'robots': '',
'description': '',
'keywords': ''},
{'name': 'Sitemap',
'abbr': '',
'slug': 'sitemap',
'uri': '/sitemap',
'desc': 'Complete list of pages and posts',
'sub_pages': [],
'robots': '',
'description': '',
'keywords': ''},
],
'kontactr': {
'username': 'ejelome',
'user_id': 148870
},
'disqus': {
'enabled': blog.disqus.enabled
}
}
# Miscellaneous (non-site specific data):
site.misc = {
'social_bookmarks': [
{'name': 'google+',
'enabled': True,
'url': 'http://profiles.google.com/ejelome',
'title': 'Google+ Profile',
'src': '/img/google-plus.png',
'alt': 'Google+',
'width': 32,
'height': 32},
{'name': 'facebook',
'enabled': True,
'url': 'http://facebook.com/ejelome',
'title': 'Facebook Profile',
'src': '/img/facebook.png',
'alt': 'Facebook',
'width': 32,
'height': 32},
{'name': 'twitter',
'enabled': True,
'url': 'http://twitter.com/ejelome',
'title': 'Twitter Profile',
'src': '/img/twitter.png',
'alt': 'Twitter',
'width': 32,
'height': 32},
{'name': 'linkedin',
'enabled': True,
'url': 'http://linkedin.com/in/ejelome',
'title': 'LinkedIn Profile',
'src': '/img/linkedin.png',
'alt': 'LinkedIn',
'width': 32,
'height': 32},
{'name': 'youtube',
'enabled': True,
'url': 'http://youtube.com/ejelome',
'title': 'YouTube Channel',
'src': '/img/youtube.png',
'alt': 'YouTube',
'width': 32,
'height': 32},
{'name': 'news-feed',
'enabled': True,
'url': '/feed',
'title': 'News feed',
'src': '/img/news-feed.png',
'alt': 'RSS',
'width': 32,
'height': 32},
],
'social_badges': [
{'enabled': True,
'url': 'http://stackoverflow.com/users/642922/ejelome',
'title': 'Stack Overflow Profile',
'src': 'http://stackoverflow.com/users/flair/642922.png',
'alt': 'Stack Overflow',
'width': 208,
'height': 58}
],
'creative_commons': {
'url': 'http://creativecommons.org/licenses/by-nc-sa/3.0',
'title': 'This work is licensed under a Creative Commons \
Attribution-NonCommercial-ShareAlike 3.0 Unported License.'
},
'validations': [
{'name': 'eXtensible HyperText Markup Language',
'abbr': 'XHTML',
'title': 'Validate Markup',
'url': 'http://validator.w3.org/check?verbose=1&uri='},
{'name': 'Cascading Style Sheets',
'abbr': 'CSS',
'title': 'Validate Style Sheets',
'url': 'http://jigsaw.w3.org/css-validator/validator?profile=css3\
&warning=0&uri='},
{'name': 'Microformats',
'abbr': 'µF',
'title': 'Validate Microformats',
'url': 'http://microformatique.com/optimus/?format=validate&\
uri='},
{'name': 'HTML version of vCard',
'abbr': 'hCard',
'title': 'Validate hCard',
'url': 'http://hcard.geekhood.net/?url='},
{'name': 'Section 508',
'abbr': '508',
'title': 'Validate Section 508 (Accessibility)',
'url': 'http://wave.webaim.org/report?url='},
{'name': 'Links',
'abbr': '',
'title': 'Check for broken links',
'url': 'http://validator.w3.org/checklink?check=Check&hide_type\
=all&summary=on&uri='},
{'name': 'Really Simple Syndication',
'abbr': 'RSS',
'title': 'Validate News feed',
'url': 'http://validator.w3.org/feed/check.cgi?url='}
],
'tools': [
{'name': 'Python',
'src': '/img/python.png',
'width': 48,
'height': 48,
'title': 'Python: programming language'},
{'name': 'Mako',
'src': '/img/mako.png',
'width': 104,
'height': 48,
'title': 'Mako: web templating engine'},
{'name': 'Python-Markdown',
'src': '/img/python-markdown.png',
'width': 48,
'height': 48,
'title': 'Python-Markdown: text-to-HTML converter'},
{'name': 'Disqus',
'src': '/img/disqus.jpg',
'width': 156,
'height': 48,
'title': 'Disqus: global comment system'},
{'name': 'Git',
'src': '/img/git.png',
'width': 115,
'height': 48,
'title': 'Git: distributed version control system'}
]
}
# Native filters:
# Markdown:
filters.markdown.extensions.abbr.enabled = True
filters.markdown.extensions.def_list.enabled = True
filters.markdown.extensions.fenced_code.enabled = True
filters.markdown.extensions.footnotes.enabled = True
filters.markdown.extensions.headerid.enabled = False
filters.markdown.extensions.tables.enabled = True
# Custom filters:
filters.hide_html5.enabled = True
filters.minify_html.enabled = True
filters.pseudo_markdown.enabled = True
filters.rel_nofollow.enabled = True
filters.trailing_slash.enabled = True
<file_sep>/py/ragnashop/reset.sh
#!/bin/bash
# This will do the following:
# * Delete files on .gitignore
# * Start the server
git clean -Xf
python server.py
# To run the file, just do:
# /reset.sh
#
# Or to make this file executable, just do:
# chmod +x reset.sh
<file_sep>/html-css/my-career-path/README.md
my-career-path
==============
Planned skill sets for the future
-------------------------------------------------------------------------------
Usage
-----
``` bash
$ google-chrome ./index.html
```
-------------------------------------------------------------------------------
`Created: 2010 July`
<file_sep>/py/alchemified/app/app/forms/setting.py
from colander import Int, Schema, SchemaNode, SequenceSchema, Str, drop
from deform.widget import HiddenWidget
from pyramid_deform import CSRFSchema
class Setting(Schema):
id = SchemaNode(Int(), missing=drop, widget=HiddenWidget())
key = SchemaNode(Str())
value = SchemaNode(Str(), missing='')
class Settings(SequenceSchema):
setting = Setting()
class SettingsFormUpdate(CSRFSchema, Schema):
settings = Settings()
<file_sep>/py/wooji/wooji/helpers.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""helper.py: Functions to handle specific code block or callback."""
import inspect
import os
import shutil
import app
import config
import server
def console_command(args, command_signal):
if len(args) < 3:
return False
command_signal_, command = args[1:3]
params = args[3:]
kwargs = get_kwargs(params, ':')
if command_signal == command_signal_:
if command == 'run':
server.run(**kwargs)
elif command == 'create':
for param in params:
create_app(param)
elif command == 'rename':
if len(params[:2]) == 2:
rename_app(*params[:2])
elif command == 'delete':
for param in params:
delete_app(param)
def create_app(dir_name):
app_file_names = [
'/controllers.py',
'/forms.py',
'/__init__.py',
'/models.py',
'/serializers.py',
'/views.py'
]
view_file_names = ['/index.html']
app_file_content = (
'#!/usr/bin/python2.7\n'
'# -*- coding: utf-8 -*-\n\n'
'"""{file_name}: File description."""\n\n'
)
create_tree(app_file_names, dir_name, config.DIR_APPS)
create_tree(view_file_names, dir_name, config.DIR_VIEWS)
write_tree(app_file_names, dir_name, config.DIR_APPS, app_file_content)
def create_tree(file_names, dir_name, root):
if not isinstance(file_names, list):
file_names = [file_names]
dir_name = dir_name.strip('/')
dir_path = os.path.join(root, dir_name)
if not (os.path.isdir(dir_path) or os.path.exists(dir_path)):
os.makedirs(dir_path)
else:
print '{} already exists.'.format(dir_path)
for file_name in file_names:
file_name = file_name.strip('/')
file_path = os.path.join(dir_path, file_name)
if not (os.path.isfile(file_path) and os.path.exists(file_path)):
if not os.path.isfile(file_path):
with open(file_path, 'a') as f:
pass # no need to close, with automatically does it
else:
print '{} already exists.'.format(file_path)
def custom_import(name):
module = __import__(name)
components = name.split('.')[1:]
for component in components:
module = getattr(module, component)
return module
def delete_app(dir_name):
roots = [config.DIR_APPS, config.DIR_VIEWS]
for root in roots:
delete_tree(dir_name, root)
def delete_tree(dir_name, root):
dir_name = dir_name.strip('/')
dir_path = os.path.join(root, dir_name)
if os.path.isdir(dir_path) and os.path.exists(dir_path):
shutil.rmtree(dir_path)
else:
print '{} does not exist.'.format(dir_path)
def get_kwargs(args, separator):
kwargs = {}
for arg in args:
if separator in arg:
k, v = arg.split(separator)
try:
v = int(v)
except:
if v in ['True', 'False']:
v = True if v == 'True' else False
kwargs.update({k:v})
return kwargs
def get_methods(class_):
methods = []
class_methods = dir(class_)
for method in class_methods:
if not (method.startswith('__') or method.endswith('__')):
methods.append(method)
return methods
def get_modules(path):
dir_names = os.listdir(path)
modules = []
for dir_name in dir_names:
dir_full_path = os.path.join(path, dir_name)
if os.path.isdir(dir_full_path):
modules.append(dir_name)
return modules
def is_primitive(object_):
object_type = type(object_)
primitives = [str, int, float, dict, list, tuple, bool, None]
return True if object_type in primitives else False
def rename_app(old_path, new_path):
old_path = old_path.strip('/')
new_path = new_path.strip('/')
apps_root = config.DIR_APPS
views_root = config.DIR_VIEWS
old_app_path = os.path.join(apps_root, old_path)
old_view_path = os.path.join(views_root, old_path)
new_app_path = os.path.join(apps_root, new_path)
new_view_path = os.path.join(views_root, new_path)
paths = [
(old_app_path, new_app_path),
(old_view_path, new_view_path)
]
for old_path, new_path in paths:
if not (os.path.isdir(old_path) or os.path.exists(old_path)):
print '{} does not exist'.format(old_path)
elif os.path.isdir(new_path) or os.path.exists(new_path):
print '{} already exists'.format(new_path)
else:
os.rename(old_path, new_path)
def to_func(callback, method):
if not inspect.isclass(callback):
return callback
return getattr(callback(), method)
def to_json(data, key=None):
key = key or 'data'
if not isinstance(data, dict):
data = dict({key:data})
for k, v in data.items():
if not is_primitive(v):
if type(v) is None:
data[k] = ''
else:
data[k] = str(v)
query = app.request.query.callback
if query:
app.response.content_type = 'application/javascript'
return '{}({})'.format(query, data)
return data
def write_tree(file_names, dir_name, root, message):
dir_name = dir_name.strip('/')
dir_path = os.path.join(root, dir_name)
for file_name in file_names:
file_name = file_name.strip('/')
file_path = os.path.join(dir_path, file_name)
if os.path.isfile(file_path) and os.path.exists(file_path):
mode = 'w'
if os.stat(file_path).st_size:
mode = 'a'
with open(file_path, mode) as f:
f.write(message.format(**locals()))
<file_sep>/py/beginner-blog/project/urls.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""urls.py: Base URL configuration and patterns."""
from django.conf import settings
from django.conf.urls import include, patterns, url
from django.contrib import admin
from django.views.generic import TemplateView
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name='index.html')),
url(r'^blog/', include('apps.blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(
r'^media/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}
),
)
<file_sep>/py/alchemified/app/app/views/setting.py
from deform import Form, ValidationFailure
from pyramid.httpexceptions import HTTPFound
from pyramid.view import view_config
from app.forms.setting import SettingsFormUpdate
from app.models.setting import SettingModel
class SettingView(object):
pt = 'app:templates/setting/{}.pt'
def __init__(self, request):
settings = request.dbsession.query(SettingModel).all()
appstruct = [s.as_dict() for s in settings]
form_schema = SettingsFormUpdate().bind(request=request)
form_appstruct = {'settings': appstruct}
form_action = request.route_path('settings')
form_buttons = ('update', )
form = Form(form_schema,
appstruct=form_appstruct,
action=form_action,
buttons=form_buttons)
self.request = request
self.settings = settings
self.form_action = form_action
self.form = form
@view_config(route_name='settings',
request_method='GET',
permission='admin',
renderer=pt.format('index'))
def index(self):
form = self.form
return {'form': form}
@view_config(route_name='settings',
request_method='POST',
request_param='update',
permission='admin',
renderer=pt.format('index'))
def update(self):
request = self.request
settings = self.settings
form = self.form
redirect_path = self.form_action
try:
form_controls = request.POST.items()
validate_appstruct = form.validate(form_controls)
settings_appstruct = validate_appstruct.get('settings')
model_ids = [s.id for s in settings]
form_ids = [sa.get('id') for sa in settings_appstruct]
update_ids = list(set(model_ids) & set(form_ids))
if update_ids:
for setting in settings:
if setting.id in update_ids:
appstruct = {sa.get('id'): sa
for sa in settings_appstruct
if sa.get('id') in update_ids}
[setattr(setting, k, v)
for k, v in appstruct.get(setting.id).items()]
delete_ids = list(set(model_ids) - set(form_ids))
if delete_ids:
[request.dbsession.delete(setting)
for setting in settings if setting.id in delete_ids]
new_appstruct = [sa
for sa in settings_appstruct
if 'id' not in sa.keys()]
new_settings = [SettingModel(**na) for na in new_appstruct]
request.dbsession.add_all(new_settings)
message = 'Update successful!'
request.session.flash(message)
return HTTPFound(location=redirect_path)
except ValidationFailure as form_error:
return {'form': form_error}
<file_sep>/py/template-blog/mysite/_posts/001 - installing-python.markdown
---
draft: False
title: Installing Python
summary: Python is easy to install and setup. If you are using Linux, it's
there by default.
author: EJelome
date: 2012/10/07 10:35:00
updated: 2012/10/07 10:35:00
featured_image: /img/python.png
categories: Python
tags: python, programming, os
---
Installing on Linux:
--------------------
It's there! ^^,
<file_sep>/sh/gitbookwrapper/.gbwrc
#!/bin/bash
# .gbwrc default vars:
GBW_HOME=
GBW_TRASH=
GBW_LABEL_USAGE=
GBW_LABEL_EXAMPLE=
GBW_LABEL_OPTIONS=
GBW_LABEL_FAILED=
GBW_LABEL_SUCCESS=
<file_sep>/py/alchemified/app/app/__init__.py
from pyramid.config import Configurator
from pyramid_beaker import session_factory_from_settings
from .helpers.setting import gsettings
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
config = Configurator(settings=settings)
cache_max_age = int(global_config.get('cache.max_age'))
config.add_static_view('static', 'static', cache_max_age=cache_max_age)
public_dir = global_config.get('public.dir')
public_files = global_config.get('public.files').split()
config.add_asset_views(public_dir, filenames=public_files)
config.add_request_method(gsettings, 'gsettings', reify=True)
session_factory = session_factory_from_settings(settings)
config.set_session_factory(session_factory)
config.set_default_csrf_options(require_csrf=True)
config.scan()
return config.make_wsgi_app()
<file_sep>/py/ragnashop/config.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""config.py: TODO"""
import os
import bottle as app
# Paths:
ROOT = os.path.abspath(os.path.dirname(__file__))
STATIC = '{base}/static'.format(base=ROOT)
DATABASE = os.path.join(ROOT, 'db.sqlite3')
SESSION = os.path.join(ROOT, 'cache')
# URIs:
BASE_URI = 'http://mydomain.tld'
# Session:
SESSION_TYPE = 'file'
SESSION_AUTO = True
# Server:
SERVER = 'wsgiref'
HOST = 'mydomain.tld'
PORT = 8080
DEBUG = True
RELOADER = True
# OAuth Keys:
FB_APP_ID = ''
FB_APP_SECRET = ''
# Selections:
LIST_TYPES = {
'0': 'Selling',
'1': 'Buying',
'2': 'Trading'
}
# CDNs:
CDN = 'http://ro-db.com/img/items/small_fro/{id}.png'
<file_sep>/py/prodev-calc/server.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import bottle as app
@app.route('/<:re:(|data.json)>', method=['GET', 'POST'])
def index():
dollar_rate = float(app.request.forms.get('dollar_rate') or 50.0)
hours_per_day = int(app.request.forms.get('hours_per_day') or 2)
days_to_work = int(app.request.forms.get('days_to_work') or 20)
base_salary = float(app.request.forms.get('base_salary') or 20000.0)
days_of_work = int(app.request.forms.get('days_of_work') or 5)
weeks_of_work = int(app.request.forms.get('weeks_of_work') or 4)
hours_of_work = int(app.request.forms.get('hours_of_work') or 8)
domain = float(app.request.forms.get('domain') or 10.0) / 12
hosting = float(app.request.forms.get('hosting') or 5.0)
license = float(app.request.forms.get('license') or 0.0)
submit = app.request.forms.get('submit')
project_hours = hours_per_day * days_to_work
hourly_rate = base_salary / (days_of_work * weeks_of_work) / hours_of_work
overhead = hourly_rate * 0.25
dev_hourly_rate = sum([hourly_rate, overhead])
dev_project_rate = dev_hourly_rate * project_hours
materials = sum([domain, hosting, license]) * dollar_rate
total = sum([dev_project_rate, materials])
if app.request.path == '/data.json':
return locals()
return app.template('index', **locals())
app.run(reloader=True)
<file_sep>/py/collect-cdn/README.md
collect-cdn
===========
Download CDN files and move them to a directory
-------------------------------------------------------------------------------
Prerequisites
-------------
### `python3-dev`, `libxml2-dev` and libxslt-dev ###
``` bash
$ sudo apt-get install python3-dev libxml2-dev libxslt-dev
```
-------------------------------------------------------------------------------
Setup
-----
```
# Create a virtualenv:
$ virtualenv venv
# Activate virtualenv:
$ source venv/bin/activate
# Install dependencies:
$ pip install -r requirements.txt
```
-------------------------------------------------------------------------------
Usage
-----
Edit `collect.ini` then run `collect.py`s:
``` bash
$ python collect.py
```
-------------------------------------------------------------------------------
License
-------
`collect-cdn` is licensed under [MIT].
[MIT]: ./LICENSE.md
-------------------------------------------------------------------------------
`Created: 2015 Feb`
<file_sep>/py/resume/modules/form.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""form.py: Handler for template forms."""
import bottle as app
class Form:
"""TODO: Class docstring."""
def __init__(self, request=app.request):
"""TODO: Method docstring."""
self.request = request
def field(self, name):
"""TODO: Method docstring."""
value = self.request.forms.get(name)
try:
value = int(value)
except:
pass
try:
value = value.strip()
except:
pass
return value or ''
def param(self, name):
"""TODO: Method docstring."""
return self.request.params.get(name) or ''
def file(self, name):
"""TODO: Method docstring."""
return self.request.files.get(name)
<file_sep>/sh/gitbookwrapper/README.md
gitbookwrapper
==============
The [GitBook] cli commands to manage books
-------------------------------------------------------------------------------
Table of Contents
-----------------
* [Setup](#setup)
* [Usage](#usage)
* [Commands](#commands)
* [License](#license)
-------------------------------------------------------------------------------
Setup
-----
``` bash
# Copy scripts to home directory:
$ cp .* ~
# Add main script path to .bashrc:
$ echo '. ${HOME}/.gitbookwrapper' >> ~/.bashrc
# Reload .bashrc:
$ . ~/.bashrc
```
### Note: ###
_The `.gbwrc` contains the variables to determine `.gitbookwrapper` paths and labels._
-------------------------------------------------------------------------------
Usage
-----
``` bash
# List all book commands:
$ gitbookwraper
# Create and switch to a new book:
$ mkbook mynewbook
# Display all available books:
$ bookon
# Switch to a book:
$ bookon mynewbook
# Remove and exit from a book:
$ rmbook mynewbook
```
-------------------------------------------------------------------------------
Commands
-----
| Command | Description |
| :------------------- | :--------------------------------- |
| `gitbookwrapper` | List all book commands |
| `mkbook <BOOK_NAME>` | Create and switch to `<BOOK_NAME>` |
| `bookon` | Display all available books |
| `bookon <BOOK_NAME>` | Switch to `<BOOK_NAME>` |
| `rmbook <BOOK_NAME>` | Remove and exit from `<BOOK_NAME>` |
-------------------------------------------------------------------------------
License
-------
`gitbookwrapper` is licensed under [MIT].
[GitBook]: https://www.gitbook.com
[MIT]: ./LICENSE.md
-------------------------------------------------------------------------------
`Created: 2016 June`
<file_sep>/html-css/laptop-tm/README.md
laptop-tm
=========
Prelim web design during college
-------------------------------------------------------------------------------
Usage
-----
``` bash
$ google-chrome ./index.html
```
-------------------------------------------------------------------------------
`Created: 2007 Oct`
<file_sep>/py/alchemified/app/app/views/oauth.py
from authomatic import Authomatic
from authomatic.adapters import WebObAdapter
from authomatic.providers.oauth2 import Facebook
from pyramid.httpexceptions import HTTPFound
from pyramid.response import Response
from pyramid.security import authenticated_userid, forget, remember
from pyramid.view import view_config
from app.models.user import UserModel
class OAuthView(object):
pt = 'app:templates/oauth/{}.pt'
def __init__(self, request):
settings = request.registry.settings
facebook_consumer_key = settings.get('facebook.consumer_key')
facebook_consumer_secret = settings.get('facebook.consumer_secret')
facebook_scope = settings.get('facebook.scope').split('\n')
facebook_secret = settings.get('facebook.secret')
facebook_config = {
'class_': Facebook,
'consumer_key': facebook_consumer_key,
'consumer_secret': facebook_consumer_secret,
'scope': facebook_scope
}
authomatic_config = {'facebook': facebook_config}
authomatic_secret = settings.get('authomatic.secret')
authomatic = Authomatic(config=authomatic_config,
secret=authomatic_secret)
self.request = request
self.authomatic = authomatic
@view_config(route_name='oauth',
request_method='GET',
permission='read',
renderer=pt.format('index'))
def index(self):
request = self.request
user = request.user
if user:
redirect_path = request.params.get('came_from')
if not redirect_path:
redirect_path = request.route_path('home')
return HTTPFound(location=redirect_path)
return {}
@view_config(route_name='login',
request_method='GET',
permission='read',
renderer='string')
def login(self):
request = self.request
authomatic = self.authomatic
response = Response()
provider = request.matchdict.get('provider')
adapter = WebObAdapter(request, response)
result = authomatic.login(adapter, provider)
if result:
if result.user:
result.user.update()
userid = result.user.id
fields = ','.join(['name', 'email'])
url = 'https://graph.facebook.com/{}?fields={}'
me = url.format(userid, fields)
response_ = result.provider.access(me)
if response_.status == 200:
email = response_.data.get('email')
if email:
query = request.dbsession.query(UserModel)
user = query.filter_by(email=email).first()
if not user:
new_user = UserModel(email=email)
request.dbsession.add(new_user)
query = request.dbsession.query(UserModel)
user = query.filter_by(email=email).first()
name = response_.data.get('name')
message = 'Welcome {}!'.format(name)
request.session.flash(message)
redirect_path = request.params.get('came_from')
if not redirect_path:
redirect_path = request.route_path('home')
userid_ = user.id
headers = remember(request, userid_)
return HTTPFound(location=redirect_path,
headers=headers)
return response
@view_config(route_name='logout',
request_method='GET',
permission='add',
renderer='string')
def logout(self):
request = self.request
message = 'Log out successful!'
request.session.flash(message)
redirect_path = request.route_path('home')
headers = forget(request)
return HTTPFound(location=redirect_path, headers=headers)
<file_sep>/py/wooji/wooji.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""wooji.py: Application runner. Execute this file to run the program."""
import sys
import wooji
if __name__ == '__main__':
wooji.helpers.console_command(sys.argv, 'app')
<file_sep>/js/f2e-web-toolkit/gulpfile.js
'use strict';
var gulp = require('gulp'),
plumber = require('gulp-plumber'),
colors = require('gulp-util'),
size = require('gulp-size'),
del = require('del'),
sass = require('gulp-sass'),
browserify = require('browserify'),
watchify = require('watchify'),
babelify = require('babelify'),
buffer = require('vinyl-buffer'),
source = require('vinyl-source-stream'),
packageJson = require('./package.json'),
globals = Object.keys(packageJson.dependencies);
gulp.task('clean', function (callback) {
del('./dist/');
});
gulp.task('build:css', function () {
gulp
.src('./src/sass/styles.scss')
.pipe(plumber())
.pipe(sass())
.pipe(gulp.dest('./dist/css/'))
.pipe(buffer())
.pipe(size());
});
gulp.task('build:js', function () {
browserify('./src/jsx/index.jsx')
.external(globals)
.bundle()
.on('error', colors.log)
.pipe(source('scripts.js'))
.pipe(gulp.dest('./dist/js/'))
.pipe(buffer())
.pipe(size());
});
gulp.task('copy:html', function () {
gulp
.src('./src/index.html')
.pipe(gulp.dest('./dist/'));
});
gulp.task('copy:img', function () {
gulp
.src('./src/static/img/**', {
base: './src/static/'
})
.pipe(gulp.dest('./dist/'));
});
gulp.task('copy:fonts', function () {
gulp
.src('./src/static/fonts/**', {
base: './src/static/'
})
.pipe(gulp.dest('./dist/'));
});
gulp.task('copy:css', function () {
gulp
.src('./bower_components/materialize/dist/css/materialize.css')
.pipe(gulp.dest('./dist/css/'));
});
gulp.task('copy:js', function () {
gulp
.src([
'./bower_components/react/react-with-addons.js',
'./bower_components/jquery/dist/jquery.js',
'./bower_components/materialize/dist/js/materialize.js'
])
.pipe(gulp.dest('./dist/js/'));
});
gulp.task('copy:fonts', function () {
gulp
.src('./bower_components/materialize/dist/font/**', {
base: './bower_components/materialize/dist/font/'
})
.pipe(gulp.dest('./dist/font/'));
});
gulp.task('watch:html', function () {
gulp.watch('./src/index.html', ['copy:html']);
});
gulp.task('watch:css', function () {
gulp.watch('./src/static/sass/styles.scss', ['build:css']);
});
gulp.task('watch:js', function () {
var rebundler = function rebundler(watch) {
var bundler = watchify(browserify({
entries: './src/jsx/index.jsx'
}).external(globals));
var rebundle = function rebundle() {
bundler
.bundle()
.on('error', function (error) {
colors.log(error);
this.emit('end');
})
.pipe(source('scripts.js'))
.pipe(gulp.dest('./dist/js/'))
.pipe(buffer())
.pipe(size());
};
if (watch) {
bundler.on('update', function () {
rebundle();
colors.log(colors.colors.green('Re-bundling complete!'));
});
}
rebundle();
};
rebundler(true);
});
gulp.task('build', [
'build:css',
'build:js'
]);
gulp.task('copy', [
'copy:html',
'copy:img',
'copy:css',
'copy:js',
'copy:fonts'
]);
gulp.task('watch', [
'watch:html',
'watch:css',
'watch:js'
]);
gulp.task('default', [
'build',
'watch',
'copy'
]);
<file_sep>/js/f2e-web-boilerplate/js/scripts.jsx
React.render(
<h1>Hello World!</h1>,
document.getElementsByTagName('body')[0]
);
<file_sep>/py/wooji/apps/test/serializers.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""serializers.py: File description."""
import marshmallow as serial
class TestSerializer(serial.Schema):
id = serial.fields.Number()
name = serial.fields.String()
message = serial.fields.String()
<file_sep>/py/alchemified/app/app/models/setting.py
from sqlalchemy import Column, Integer, Text
from .__meta__ import Base
class SettingModel(Base):
__tablename__ = 'settings'
id = Column(Integer, primary_key=True)
key = Column(Text, unique=True, nullable=False)
value = Column(Text)
def as_dict(self):
return {'id': self.id, 'key': self.key, 'value': self.value}
<file_sep>/py/beginner-blog/apps/blog/views.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""views.py: Blog template views handler."""
from django.shortcuts import render_to_response
from models import Post, Category, Tag
def index(request):
posts = Post.objects.filter(state=1).all()
categories = Category.objects.all()
tags = Tag.objects.all()
return render_to_response('blog/index.html', {
'posts': posts,
'categories': categories,
'tags': tags
})
def post(request, post_slug):
post = Post.objects.get(slug=post_slug, state=1)
return render_to_response('blog/post.html', {'post': post})
def category(request, category_slug):
category = Category.objects.get(slug=category_slug)
posts = Post.objects.filter(category__slug=category_slug, state=1)
return render_to_response('blog/category.html', {
'category': category,
'posts': posts
})
def tag(request, tag_name):
tag = Tag.objects.get(name=tag_name)
posts = Post.objects.filter(tags__in=[tag.id], state=1)
return render_to_response('blog/tag.html', {
'tag': tag,
'posts': posts
})
<file_sep>/py/alchemified/app/app/views/__init__.py
from pyramid.httpexceptions import HTTPFound
from pyramid.view import forbidden_view_config, notfound_view_config
class HTTPErrorView(object):
pt = 'app:public/{}.pt'
def __init__(self, request):
self.request = request
@notfound_view_config(request_method='GET', renderer=pt.format('404'))
def notfound(self):
return {}
@forbidden_view_config(request_method='GET', renderer='string')
def forbidden(self):
request = self.request
route_name = 'oauth'
redirect_path = request.route_path(route_name)
return HTTPFound(location=redirect_path)
<file_sep>/py/wooji/wooji/app.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""app.py: Get all the submodules of bottle web framework."""
from bottle import *
<file_sep>/py/resume/modules/function.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""function.py: Re-usable functions for commonly used code blocks."""
import json
import pprint
import smtplib
import bottle as app
from email.mime.text import MIMEText
from PIL import Image
import config
from form import Form
def image_info(path, base=config.ASSETS):
"""TODO: Function docstring."""
full_path = '{base}/{path}'.format(base=base, path=path.lstrip('/'))
image = Image.open(full_path)
width, height = image.size
return dict(path=path, full_path=full_path, width=width, height=height)
def send_mail(sender, recipients, subject, message):
"""TODO: Function docstring."""
to = sender['email']
from_ = [recipient['email'] for recipient in recipients]
message = MIMEText(message)
message['Subject'] = subject
message['From'] = '"{name}" <{email}>'.format(
name=sender['name'],
email=sender['email']
)
message['To'] = ', '.join([
'"{name}" <{email}>'.format(
name=recipient['name'],
email=recipient['email']
) for recipient in recipients
])
mailbox = smtplib.SMTP_SSL(config.SMTP_SERVER)
try:
mailbox.login(config.SMTP_USERNAME, config.SMTP_PASSWORD)
mailbox.sendmail(to, from_, message.as_string())
print 'Success: E-mail sent'
return True
except smtplib.SMTPException:
print 'Error: E-mail not sent'
return False
def set_field(dict_, exclude_keys=['id', 'user_id'], empty_values=False):
"""TODO: Function docstring."""
form = Form()
return {
key: '' if empty_values else form.field(key) or dict_[key]
for key in dict_.keys() if key not in exclude_keys
}
def set_fieldset(dict_, ordered_keys, empty_values=False):
"""TODO: Function docstring."""
form = Form()
return {
key: dict(
name=key,
order=index,
title=key.replace('_', ' ').title(),
slug=key.replace('_', '-'),
value='' if empty_values else form.field(key) or dict_[key]
) for index, key in enumerate(ordered_keys)
}
def filter_non_dict_values(dict_):
"""TODO: Function docstring."""
return {
key : value for key, value in dict_.items()
if isinstance(value, dict)
}
def console_log(title, value, indent=4):
"""TODO: Function docstring."""
pp = pprint.PrettyPrinter(indent=indent)
try:
log = json.dumps(value, indent=indent)
except:
log = pp.pformat(value)
if not config.DEBUG:
return ''
print '{title}: {log}'.format(title=title, log=log)
return '{title}: {log}'.format(title=title, log=log)
<file_sep>/py/wooji/apps/_media/controllers.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""controllers.py: Media files handler."""
import os
import wooji
def media(dir_name, file_name):
root = os.path.join(wooji.config.DIR_MEDIA, dir_name)
return wooji.app.static_file(file_name, root=root)
<file_sep>/py/beginner-blog/apps/blog/tests.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""tests.py: Blog test cases."""
<file_sep>/py/resume/modules/upload.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""upload.py: Handler for template file uploads."""
import os
import slugify
from PIL import Image
import config
import function
class Upload:
"""TODO: Class docstring."""
def __init__(self, base=config.ASSETS):
"""TODO: Method docstring."""
self.base = base
self.info = {}
self.errors = []
def image(self, object_, path='/img'):
"""TODO: Method docstring."""
new_base = '{base}/{path}'.format(
base=self.base,
path=path.lstrip('/')
)
contents = object_.file.read()
extension = object_.filename.split('.')[-1]
slug = slugify.slugify(u'{filename}'.format(filename=object_.filename))
name = slug.replace('_', '-')[:-len(extension)]
new_name = '{name}.{extension}'.format(
name=name,
extension=extension
)
if not len(contents):
self.errors.append('The uploaded image is empty')
elif len(contents) > config.UPLOAD_MAX_SIZE:
self.errors.append(
'Exceeded allowed image size: Only {max_size}MB is '
'allowed'.format(
max_size=int(config.UPLOAD_MAX_SIZE / (1024 * 1024))
)
)
elif '.' in object_.filename \
and extension not in config.UPLOAD_ALLOWED_EXTENSIONS:
self.errors.append(
'Only {extensions} and {extension} extensions are '
'allowed'.format(
extensions=', '.join(config.UPLOAD_ALLOWED_EXTENSIONS[:-1]),
extension=config.UPLOAD_ALLOWED_EXTENSIONS[-1]
)
)
elif object_.type not in config.UPLOAD_ALLOWED_MIME_TYPES:
self.errors.append(
'Only {mime_types} and {mime_type} MIME types are '
'allowed'.format(
mime_types=', '.join(config.UPLOAD_ALLOWED_MIME_TYPES[:-1]),
mime_type=config.UPLOAD_ALLOWED_MIME_TYPES[-1]
)
)
else:
file_path = '{path}/{new_name}'.format(path=path, new_name=new_name)
abs_file_path = '{new_base}/{new_name}'.format(
new_base=new_base,
new_name=new_name
)
if not os.path.exists(new_base):
os.makedirs(new_base)
with open(abs_file_path, 'w') as file_:
file_.write(contents)
try:
image = Image.open(abs_file_path)
self.info = function.image_info(file_path)
except:
if os.path.exists(abs_file_path):
os.remove(abs_file_path)
self.errors.append('The image is corrupted')
return True if self.info else False
<file_sep>/html-css/web-design/drafts/blog-name/README.md
blog-name
==========
-------------------------------------------------------------------------------
Transcript
----------
> TOP 10 BLOG USABILITY REQUIREMENTS:
> Source:
>> http://www.useit.com/alertbox/weblogs.html
>
> (checked) 1. Author Biographies
>> * [about]
>> * (who are they dealing with?)
>
> (checked) 2. Author Photo
>> * [img]
>> * (what do they look like?)
>
> (checked) 3. Descriptive Post Titles
>> * [h2]
>> * (what is the content all about?)
>> !Avoid using all caps for titles
>> !ALL CAPS implies shouting
>> !Readers' reading speed is reduced by 10%
>
> (checked) 4. Links Should Convey Its Destination
>> * [a title]
>> * (where does the link goes and what is the link all about?)
>> !Don't put titles on every link
>> !It's only for supplementary information
>
> (n/a) 5. Don't Bury Important Valuable Posts In Archive
>> // N/A
>> // Applicable only for the person using the blogsite
>> * For information's sake,
>> !Don't assume your readers to have been with you from the beginning
>> !Link previously posted postings sometimes in newer posts
>
> (n/a) 6. Don't Use Calendar As The Only Navigation For Post Archives
>> // N/A
>> // Applicable only for the person using the blogsite
>> * For information's sake,
>> !Ten to twenty posts per categories will be sufficient
>> !Avoid long titles for each categories, keep it short but descriptive
>
> (n/a) 7. Publish Frequency
>> // N/A
>> // Applicable only for the person using the blogsite
>> * For information's sake,
>> !Don't post when you have nothing to say
>> !Avoid polluting the cyberspace with needless posts
>> !Only post when you have wrote the writing properly
>
> (n/a) 8. Don't Mix Topics
>> // N/A
>> // Applicable only for the person using the blogsite
>> * For information's sake,
>> !Consistency is the key for effective info distribution
>> !Have an aim in the purpose of your blog (or posts)
>
> (n/a) 9. Be Careful On Making Posts
>> // N/A
>> // Applicable only for the person using the blogsite
>> * For information's sake,
>> !Imagine 5 or 10 years from now,
>> some boss or employer will hire you,
>> and finds out some offending and unmannered posts you have posted in the past.
>> !Think as many times as you can before posting any reaction or information,
>> it will surely have some adverse effect on your life and/or career
>
> (n/a) 10. As Much As Possible, Don't Be In A Domain Owned By Another Web Service Blog
>> // N/A
>> // Applicable only for the person using the blogsite
>> * For information's sake,
>> !Letting someone own your blog posts owns your destiny in blogging
>> !They can do as much as they want,
>> e.g. degrade the services, make and/or increase blogging prices, etc
>> !They can include annoying stuffs in your blogosphere,
>> e.g. pop-ups, blinking ads, text pollutions in your posts,
>> making your own blogspace rather useless and uncomfortable
-------------------------------------------------------------------------------
`Created: 2010 July`
<file_sep>/html-css/the-ultimate-reference/README.md
the-ultimate-reference
======================
Read e-books inside the browser
-------------------------------------------------------------------------------
Usage
-----
``` bash
$ google-chrome ./index.html
```
-------------------------------------------------------------------------------
`Created: 2010 Mar`
<file_sep>/py/beginner-blog/project/views.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""views.py: Base template views handler."""
from django.shortcuts import render_to_response
def index():
return render_to_response('index.html')
<file_sep>/clj/todo-clj/resources/sql/task.sql
-- name: create-task-table!
-- Create the Task table.
CREATE TABLE IF NOT EXISTS Task(
id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
description TEXT
)
-- name: show-tasks
-- Show all tasks.
SELECT *
FROM Task
-- name: create-task!
-- Create a new task.
INSERT
INTO Task (
title,
description
)
VALUES (
:title,
:description
)
-- name: show-task
-- Show a task based on :id.
SELECT *
FROM Task
WHERE id = :id
-- name: update-task!
-- Update a task based on :id.
UPDATE Task
SET
title = :title,
description = :description
WHERE id = :id
-- name: delete-task!
-- Delete a task based on :id.
DELETE
FROM Task
WHERE id = :id
-- name: delete-tasks!
-- Delete all tasks.
DELETE
FROM Task
<file_sep>/sh/shell-site-generator/src/posts/index.md
Hello World!
============
This is the homepage! :)
<file_sep>/sh/virtualenvwrapper-rm/README.md
virtualenvwrapper-rm
====================
The missing `rmproject` of [virtualenvwrapper]
-------------------------------------------------------------------------------
Table of Contents
-----------------
* [Setup](#setup)
* [Usage](#usage)
* [License](#license)
-------------------------------------------------------------------------------
Setup
--------
``` bash
# Copy script to home directory:
$ cp .virtualenvwrapper-rm ~
# Add script path to .bashrc:
$ echo '. ${HOME}/.virtualenvwrapper-rm' >> ~/.bashrc
# Reload .bashrc:
$ . ~/.bashrc
```
-------------------------------------------------------------------------------
Usage
-----
``` bash
$ rmproject <DEST_DIR>
```
*Where `<DEST_DIR>` is the name of the project, e.g. `myawesomeproject`.*
-------------------------------------------------------------------------------
License
-------
`virtualenvwrapper-rm` is licensed under [MIT].
[virtualenvwrapper]: https://virtualenvwrapper.readthedocs.org
[MIT]: ./LICENSE.md
-------------------------------------------------------------------------------
`Created: 2016 June`
<file_sep>/py/resume/templates/pages/site/header.html
## /site/header.html
## TODO: Put a logo
## TODO: Put the site name and the tagline
<div class="header">
## Header:
## Holds the branding of the website and tells the web visitor what is the
## name and purpose (via the tagline) of the site.
## NOTE(s):
## * The alt attribute of the logo should just contain the name of the site
## * The tagline should not exceed 8 words, briefly describing the website
## * Do not use generic taglines but tell the web visitor what the site does
</div>
<file_sep>/py/resume/templates/pages/chunk/skip.html
## /chunk/skip.html
<% import re %>
% if 'auth_id' in session and session['auth_id']:
% if meta['slug'] != 'home' or re.search(r'^/resume', meta['path']):
<% results = [v for v in result.values() if v] %>
% if not results and meta['slug'] not in ['profile', 'address']:
<div class="skip">
<span class="wrap-start">[</span>
<a href="#content"
title="Skip navigation links and jump directly to the content">Skip to content</a>
<span class="pointer">↓</span>
<span class="wrap-end">]</span>
</div>
% endif
% endif
% endif
<file_sep>/html-css/web-design/drafts/ragnashop/bump.html
<style type="text/css">
body {
color: #ccc;
font-size: 0.8em;
}
</style>
<p>
Good day guys! <br />
Pa [b][color="#FFFF00"]BUMP[/color][/b] ulit! :dance2: <br />
[color="#FFFF00"][b]RELATED LINKS:[/b][/color] <br />
* [url="http://ragnaboards.levelupgames.ph/index.php?showtopic=189846&hl="]Ragnashop [b]Guidelines[/b][/url] <br />
* [url="http://ragnaboards.levelupgames.ph/index.php?showtopic=189847&hl="]How to use [b]Chat Roll[/b][/url] [i]( the chat room)[/i] <br />
* [url="http://ragnaboards.levelupgames.ph/index.php?showtopic=188218&st=0&p=4656445&#entry4656445"][b]Discussion Forum[/b][/url] <br />
* [url="#"]Visit [b]Ragnashop[/b][/url] <br />
</p>
<file_sep>/html-css/hresume/README.md
hresume
=======
Microformatted homepage resume
-------------------------------------------------------------------------------
Usage
-----
``` bash
$ google-chrome ./index.html
```
-------------------------------------------------------------------------------
`Created: 2010 May`
<file_sep>/py/alchemified/app/app/helpers/setting.py
from app.models.setting import SettingModel
def gsettings(request):
settings = request.dbsession.query(SettingModel).all()
if settings:
settings_ = [s.as_dict() for s in settings]
settings__ = {s.get('key'): s.get('value') for s in settings_}
return {**settings__}
return {}
<file_sep>/py/alchemified/app/app/models/user.py
from sqlalchemy import Column, Integer, Text
from .__meta__ import Base
class UserModel(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
email = Column(Text, unique=True, nullable=False)
group = Column(Text, default='author', nullable=False)
def as_dict(self):
return {'id': self.id, 'email': self.email, 'group': self.group}
<file_sep>/py/wooji/wooji/config.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""config.py: Application's default settings."""
import os
# Paths:
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
# Directories:
DIR_APPS = os.path.join(ROOT, 'apps')
DIR_VIEWS = os.path.join(ROOT, 'views')
DIR_STATIC = os.path.join(ROOT, 'static')
DIR_MEDIA = os.path.join(ROOT, 'media')
# Server:
SERVER_WSGI = 'wsgiref'
SERVER_HOST = 'localhost'
SERVER_PORT = 8080
SERVER_DEBUG = True
SERVER_RELOADER = True
SERVER_INTERVAL = 1
SERVER_QUIET = False
# Session:
SESSION_PATH = os.path.join(ROOT, 'cache')
SESSION_TYPE = 'file'
SESSION_AUTO = True
# Template:
TEMPLATE_RENDERER = 'mako'
# Database:
DB_PATH = os.path.join(ROOT, 'db.sqlite3')
DB_DEST = '////' # 4 slash: absolute, 3 slash: relative, 2 slash: for non-SQLite
DB_TYPE = 'sqlite'
<file_sep>/py/alchemified/app/app/routes/oauth.py
oauth_routes = [
('oauth', '/login'),
('login', '/login/{provider}'),
('logout', '/logout'),
]
<file_sep>/py/beginner-blog/README.md
beginner-blog
=============
An introduction to `Django` using a blog structure
-------------------------------------------------------------------------------
Introduction
-------------
`Beginner Blog` is a simple introduction for people who are interested to dive into Django using a plain blog structure as the approach.
This application tries its best to use Django in the most minimal and easiest way possible — removing any clever techniques that might get in the way to learn Django quickly.
It is licensed under [MIT] which means you are free to do anything with it in the hope that you learn, improve, and share upon its use.
-------------------------------------------------------------------------------
Notable tools
-------------
* `The Django Template Language` as the *Templating Engine*
* `SQLite3` as the *Database Engine*
* `Django` (v1.6) as the *Web Framework*
* `Markdown` as the *Plain Text to HTML Converter*
Notable packages
----------------
* `markdown` for handling the *plain text to html conversions*
* `pillow` for handling *images* (this is required to process images)
* `pygments` for handling *syntax highlighting*
* `sorl-thumbnail` for handling the image *thumbnails*
-------------------------------------------------------------------------------
Prerequisites
-------------
### for System: ###
* `python-setuptools`
* `python-dev`
* `git` (for versioning, repository)
### for Python: ###
* `python-setuptools` (installs `easy_install` command)
* `python-dev` (for Python headers, necessary to install `pillow`)
* `pip` (to install Python packages)
* `virtualenvwrapper` (to manage `virtualenv`)
### for Django: ###
* `markdown`
* `pillow`
* `pygments`
* `sorl-thumbnail`
-------------------------------------------------------------------------------
Install prerequisites
---------------------
```bash
# System packages:
$ sudo apt-get install git python-setuptools python-dev
# pip:
$ sudo easy_install pip
# virtualenvwrapper:
$ sudo pip install virtualenvwrapper
# Update .bashrc:
$ echo '
export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=$HOME/Devel
source /usr/local/bin/virtualenvwrapper.sh
' >> ~/.bashrc
# Reload .bashrc:
. ~/.bashrc
# Create Devel directory:
$ mkdir -p ${PROJECT_HOME}
```
-------------------------------------------------------------------------------
Set up project
--------------
``` bash
# Create and switch to virtualenv:
$ mkproject -p /usr/bin/python2 beginner-blog
# Clone repository in current directory:
$ git clone https://github.com/ejelome/beginner-blog .
# Install packages:
$ pip install -r requirements.txt
```
-------------------------------------------------------------------------------
Run project
-----------
```bash
# Sync models with default fixtures:
$ ./manage.py syncdb
# Run web server:
$ ./manage.py runserver
```
Then visit <http://localhost:8000/blog>
or login to <http://localhost:8000/admin>.
-------------------------------------------------------------------------------
Reset project
-------------
``` bash
$ ./reset.sh
```
-------------------------------------------------------------------------------
License
-------
`beginner-blog` is licensed under [MIT].
[MIT]: ./LICENSE.md
-------------------------------------------------------------------------------
`Created: 2014 Jan`
<file_sep>/py/collect-cdn/requirements.txt
lxml==3.4.1
requests==2.5.0
<file_sep>/py/wooji/wooji/routes.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""routes.py: Import each app's views submodule."""
import inspect
import os
import app
import config
import filters
import helpers
keys = ['path', 'callback', 'template', 'method', 'apply']
dir_names = helpers.get_modules(config.DIR_APPS)
base_name = os.path.basename(config.DIR_APPS)
for dir_name in dir_names:
module_format = '{}.{}'.format(base_name, dir_name)
module = helpers.custom_import(module_format)
module_path = module.__path__[0]
routes = []
if 'views.py' in os.listdir(module_path):
submodule_format = '{}.{}.views'.format(base_name, dir_name)
submodule = helpers.custom_import(submodule_format)
if 'routes' in dir(submodule):
routes = submodule.routes
for route in routes:
set_ = {}
for k, v in zip(keys, route):
set_.update({k: v})
path = set_.get('path')
template = set_.get('template')
callback = set_.get('callback')
method = set_.get('method')
apply_ = set_.get('apply')
if not isinstance(method, list):
method = filter(None, [method]) or ['GET', 'POST', 'PUT', 'DELETE']
if not isinstance(apply_, list):
apply_ = filter(None, [apply_])
if template:
template = template.strip('/')
renderer_format = '{}_view'.format(config.TEMPLATE_RENDERER)
renderer = getattr(app, renderer_format)
apply_.append(renderer(template))
filters_ = helpers.get_methods(filters)
for filter_ in filters_:
method_ = getattr(filters, filter_)
apply_.append(method_)
set_['apply'] = apply_
for method_ in method:
if inspect.isclass(callback):
methods = helpers.get_methods(callback)
if method_ in methods:
set_['callback'] = helpers.to_func(
callback,
method_.upper()
)
set_['method'] = method_
getattr(app, method_.lower())(**set_)
<file_sep>/py/resume/modules/db.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""db.py: Database wrapper."""
import sqlite3
import config
import function
class DB:
"""TODO: Class docstring."""
def __init__(self, file_=config.DATABASE):
"""TODO: Method docstring."""
self.connect = sqlite3.connect(file_)
self.connect.row_factory = sqlite3.Row
self.cursor = self.connect.cursor()
def create(self, table, columns):
"""TODO: Method docstring."""
columns = ', '.join([
'{column} {property}'.format(
column=column,
property=property_.upper()
) for column, property_ in columns.items()
])
query = "CREATE TABLE IF NOT EXISTS {table}({columns});".format(
table=table,
columns=columns
)
function.console_log('query', query)
self.cursor.execute(query)
self.connect.commit()
def read(self, table, columns=['*'], conditions=None, connector='AND'):
"""TODO: Method docstring."""
columns = ', '.join(columns)
query = "SELECT {columns} FROM {table}".format(
columns=columns,
table=table
)
if conditions:
conditions = ' {connector} '.join([
'{0} {1} "{2}"'.format(*condition) for condition in conditions
]).format(connector=connector.upper())
query += " WHERE {conditions}".format(conditions=conditions)
query += ";"
function.console_log('query', query)
self.cursor.execute(query)
results = self.cursor.fetchall()
function.console_log('query results', results)
# New results to filter None types to an empty string:
new_results = [
{
key: result[key] or '' for key in result.keys()
} for result in results
]
# return results
return new_results
def read_all(self, primary_table, foreign_tables, key_relation,
conditions=None, connector='AND'):
"""TODO: Method docstring."""
foreign_table_joins = [
"""
INNER JOIN {foreign_table}
ON {primary_table}.{pk} = {foreign_table}.{fk}
""".format(
foreign_table=foreign_table,
primary_table=primary_table,
pk=key_relation['pk'],
fk=key_relation['fk']
) for foreign_table in foreign_tables
]
query = """
SELECT
*
FROM
{primary_table}
{foreign_table_joins}
WHERE
{primary_table}.{pk} = {pk_value}
""".format(
primary_table=primary_table,
foreign_table_joins=' '.join(foreign_table_joins),
pk=key_relation['pk'],
pk_value=key_relation['pk_value']
)
if conditions:
conditions = ' {connector} '.join([
'{0} {1} "{2}"'.format(*condition) for condition in conditions
]).format(connector=connector.upper())
query += " {connector} {conditions}".format(
connector=connector,
conditions=conditions
)
query += ";"
function.console_log('query', query)
self.cursor.execute(query)
results = self.cursor.fetchall()
function.console_log('query results', results)
# New results to filter None types to an empty string:
new_results = [
{
key: result[key] or '' for key in result.keys()
} for result in results
]
# return results
return new_results
def insert(self, table, columns):
"""TODO: Method docstring."""
column_keys = ', '.join(columns.keys())
param_keys = ', '.join([
':{column_key}'.format(
column_key=column_key
) for column_key in columns.keys()
])
query = """
INSERT OR REPLACE INTO
{table}({column_keys})
VALUES
({param_keys});
""".format(
table=table,
column_keys=column_keys,
param_keys=param_keys
)
function.console_log('query', query)
self.cursor.execute(query, columns)
self.connect.commit()
def update(self, table, columns, conditions=None, connector='AND'):
"""TODO: Method docstring."""
param_keys = ', '.join([
'{column_key} = :{column_key}'.format(
column_key=column_key
) for column_key in columns.keys()
])
query = """
UPDATE
{table}
SET
{param_keys}
""".format(
table=table,
param_keys=param_keys
)
if conditions:
conditions = ' {connector} '.join([
'{0} {1} "{2}"'.format(*condition) for condition in conditions
]).format(connector=connector.upper())
query += " WHERE {conditions}".format(conditions=conditions)
query += ";"
function.console_log('query', query)
self.connect.execute(query, columns)
self.connect.commit()
def remove(self, table, conditions=None, connector='AND'):
"""TODO: Method docstring."""
query = """
DELETE FROM
{table}
""".format(table=table)
if conditions:
conditions = ' {connector} '.join([
'{0} {1} "{2}"'.format(*condition) for condition in conditions
]).format(connector=connector.upper())
query += " WHERE {conditions}".format(conditions=conditions)
query += ";"
function.console_log('query', query)
self.connect.execute(query)
self.connect.commit()
<file_sep>/html-css/web-design/drafts/photo-shoot/contact-us.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://microformats.org/profile/specs/">
<title>Contact Us | Photo Shoot</title>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<link rel="stylesheet" type="text/css" href="css/global.css" />
<link rel="alternative stylesheet" type="text/css" href="css/alternate.css" title="Alternative Style Sheet" />
<!--[if lte IE 6]>
<link rel="stylesheet" type="text/css" href="css/old-ies.css" />
<![endif]-->
<body id="contact-us">
<?php
/* legend:
b## - begin Usability Division
e## - end Usability Division
b// - begin Page Division
e// - end Page Division
*/
?>
<!-- b// header -->
<h1>
<!-- b## Site ID -->
<a href="#">
<img src="logo.gif" height="64" alt="Company Logo" />Photo Shoot
</a>v1.2
<!-- e## end Site ID -->
<!-- b## tagline -->
<span id="tagline">Catching your eyes' attention.</span>
<!-- e## tagline -->
</h1>
<!-- e// header -->
<!-- b## Search -->
<form action="path/file.php" method="get">
<ul id="search">
<li>
<label for="search_field">Search for:</label>
<input type="text" name="search_field" id="search_field" />
</li>
<li>
<label for="search_category">Select:</label>
<select name="search_category" id="search_category">
<option>Category</option>
</select>
</li>
<li>
<input type="submit" name="search_submit" id="search_submit" value="Go" />
</li>
</ul>
</form>
<!-- e## Search -->
<!-- b// navigation -->
<!-- b## Section -->
<!-- b// navigation-main -->
<ul id="nav-main">
<li>
<a href="index.html">Home</a>
</li>
<li>
<a href="photography.html">Photography</a>
</li>
<li>
<a href="contact-us.html">Contact Us</a>
</li>
<li>
<a href="about-us.html">About Us</a>
</li>
</ul>
<!-- e// navigation-main -->
<!-- b// navigation-sub -->
<!--
<ul id="nav-sub">
<li>
<a href="#">Subsection 1</a>
</li>
<li>
<a href="#">Subsection 2</a>
</li>
<li>
<a href="#">Subsection 3</a>
</li>
<li>
<a href="#">Subsection 4</a>
</li>
<li>
<a href="#">Subsection 5</a>
</li>
<li>
<a href="#">Subsection 6</a>
</li>
</ul>
-->
<!-- e// navigation-sub -->
<!-- e## Section -->
<!-- e// navigation -->
<!-- b// content -->
<div id="content-wrapper">
<div id="content">
<!-- b## Page Name -->
<h2>Content Title</h2>
<!-- e## Page Name -->
<p>
I am a content, I am a content, I am a content, I am a content, I am a content, I am a content, I am a content, I am a content,
I am a content, I am a content, I am a content, I am a content, I am a content, I am a content, I am a content, I am a content,
I am a content, I am a content, I am a content, I am a content, I am a content, I am a content, I am a content, I am a content,
I am a content, I am a content, I am a content, I am a content, I am a content, I am a content, I am a content, I am a content,
I am a content, I am a content, I am a content, I am a content, I am a content, I am a content, I am a content, I am a content,
I am a content, I am a content, I am a content, I am a content, I am a content, I am a content, I am a content, I am a content,
I am a content, I am a content, I am a content, I am a content, I am a content, I am a content, I am a content, I am a content,
I am a content, I am a content, I am a content, I am a content, I am a content, I am a content, I am a content, I am a content,
I am a content, I am a content, I am a content, I am a content, I am a content, I am a content, I am a content, I am a content,
</p>
</div>
<!-- b## Local Navigation -->
<div id="nav-local">
<h3>Local Navigation</h3>
<ul>
<li>
<a href="#">Local Navigation 1</a>
</li>
<li>
<a href="#">Local Navigation 2</a>
</li>
<li>
<a href="#">Local Navigation 3</a>
</li>
<li>
<a href="#">Local Navigation 4</a>
</li>
</ul>
</div>
<!-- e## Local Navigation -->
<!-- b// External Links -->
<div id="nav-external">
<h4>External Links</h4>
<ul>
<li>
<a href="#">External Link 1</a>
</li>
<li>
<a href="#">External Link 2</a>
</li>
<li>
<a href="#">External Link 3</a>
</li>
<li>
<a href="#">External Link 4</a>
</li>
</ul>
<h4>External Links</h4>
<ul>
<li>
<a href="#">External Link 1</a>
</li>
<li>
<a href="#">External Link 2</a>
</li>
<li>
<a href="#">External Link 3</a>
</li>
<li>
<a href="#">External Link 4</a>
</li>
</ul>
<h4>External Links</h4>
<ul>
<li>
<a href="#">External Link 1</a>
</li>
<li>
<a href="#">External Link 2</a>
</li>
<li>
<a href="#">External Link 3</a>
</li>
<li>
<a href="#">External Link 4</a>
</li>
</ul>
</div>
<!-- e// External Links -->
</div>
<!-- e// content -->
<!-- b// footer -->
<div id="footer">
<ul id="validate">
<li>
<a href="http://validator.w3.org/check?uri=">
<abbr title="eXtensible HyperText Markup Language">xhtml</abbr>
</a>
</li>
<li>
<a href="http://jigsaw.w3.org/css-validator/validator?uri=">
<abbr title="Cascading Style Sheets">css</abbr>
</a>
</li>
<li>
<a href="http://www.totalvalidator.com/validator/Revalidate?revalidate=true">
<abbr title="Web Content Accessibility Guidelines">wcag</abbr>
</a>
</li>
<li>
<a href="http://www.section508.info/check_this.cfm?URLtest=/&s508=1&CheckURL=0">
<abbr title="Section 508">508</abbr>
</a>
</li>
<li>
<a href="http://www.cynthiasays.com/mynewtester/cynthia.exe?rptmode=-1&url1=">
<abbr title="Cynthia Tested">cynthia</abbr>
</a>
</li>
<li>
<a href="http://creativecommons.org/licenses/by-nc-nd/3.0/ph/" rel="license">
<abbr title="Creative Commons">cc</abbr>
</a>
</li>
</ul>
<p id="copyright">
Copyright © 2009 - 2010.
<a href="#">NoobSociety.com</a>. All rights reserved.
</p>
</div>
<!-- e// footer -->
</body>
</html>
<file_sep>/py/template-blog/mysite/_filters/trailing_slash.py
#!/usr/bin/python
# filename: trailing_slash.py
import re
import blogofile_bf as bf
from bs4 import BeautifulSoup
def run(content):
"""Return all links with a trailing slash (/), excluding files."""
enabled = bf.config.filters.trailing_slash.enabled
soup = BeautifulSoup(content)
hrefs = soup.find_all(['a', 'link'])
actions = soup.find_all(['form'])
old_links = []
new_links = []
file_exts = [
'htm', 'html', 'xhtml', 'xml',
'css',
'js',
'txt',
'bmp', 'ico', 'gif', 'jpeg', 'jpg', 'png', 'tiff',
'flv', 'mpeg', 'mpg', 'mp4', '3gp', 'xvid', 'avi'
]
ignore_links = ['wikipedia.org']
if enabled:
for anchor in hrefs:
href = anchor['href']
if not re.search(r'(^mailto:|/$|#.+?$)', href):
for ignore_href in ignore_links:
if not re.search(r'%s' % ignore_href, href):
href += '/'
old_links.append(anchor['href'])
new_links.append(href)
for i in range(len(old_links)):
content = re.sub('href="%s"' % old_links[i],
'href="%s"' % new_links[i], content)
for form in actions:
action = form['action']
if not re.search(r'/$|@', action):
content = content.replace(action, '%s/' % action)
# Remove trailing slash for file paths
for ext in file_exts:
content = re.sub(r'%s/$' % ext, ext, content)
return content
<file_sep>/py/ragnashop/models.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""models.py TODO"""
import sqlalchemy as orm
from sqlalchemy.ext.declarative import declarative_base
import config
class SetTextFactory(orm.interfaces.PoolListener):
def connect(self, dbapi_con, con_record):
dbapi_con.text_factory = str
engine = orm.create_engine(
'sqlite:///{db}'.format(db=config.DATABASE),
echo=True if config.DEBUG else False,
listeners=[SetTextFactory()]
)
engine.connect().connection.connection.text_factory = str
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = orm.Column(orm.Integer, primary_key=True)
uid = orm.Column(orm.Integer)
email = orm.Column(orm.String)
name = orm.Column(orm.String)
slug = orm.Column(orm.String, unique=True)
shop = orm.orm.relationship('Shop', uselist=False, backref='users')
def __repr__(self):
return (
'<User('
'id="{id}",'
'uid="{uid},'
'email="{email},'
'name="{name}",'
'slug="{slug}",'
'shop="{shop}"'
')>'
).format(
id=self.id,
uid=self.uid,
email=self.email,
name=self.name,
slug=self.slug,
shop=self.shop
)
class Shop(Base):
__tablename__ = 'shops'
id = orm.Column(orm.Integer, primary_key=True)
name = orm.Column(orm.String)
server = orm.Column(orm.String)
ingame = orm.Column(orm.String)
email = orm.Column(orm.String)
mobile = orm.Column(orm.String)
items = orm.orm.relationship('Item', backref='shops')
user_id = orm.Column(orm.Integer, orm.ForeignKey('users.id'), unique=True)
def __repr__(self):
return (
'<User('
'id="{id}",'
'name="{name}",'
'server="{server}",'
'items="{items}",'
'user_id="{user_id}"'
')>'
).format(
id=self.id,
name=self.name,
server=self.server,
items=self.items,
user_id=self.user_id
)
class Item(Base):
__tablename__ = 'items'
id = orm.Column(orm.Integer, primary_key=True)
icon_id = orm.Column(orm.String)
name = orm.Column(orm.String)
price = orm.Column(orm.String)
trade = orm.Column(orm.String)
amount = orm.Column(orm.String)
list_type = orm.Column(orm.Integer)
created = orm.Column(orm.DateTime)
modified = orm.Column(orm.DateTime)
shop_id = orm.Column(orm.Integer, orm.ForeignKey('shops.id'))
def __repr__(self):
return (
'<User('
'id="{id}",'
'name="{name}",'
'price="{price}",'
'trade="{trade}",'
'amount="{amount}",'
'list_type="{list_type}",'
'created="{created}",'
'modified="{modified}",'
'shop_id="{shop_id}"'
')>'
).format(
id=self.id,
name=self.name,
price=self.price,
trade=self.trade,
amount=self.amount,
list_type=self.list_type,
created=self.created,
modified=self.modified,
shop_id=self.shop_id
)
Base.metadata.create_all(engine)
Session = orm.orm.sessionmaker(bind=engine)
session = Session()
<file_sep>/js/f2e-web-boilerplate/README.md
f2e-web-boilerplate
===================
Front-end web boilerplate with `bower`
-------------------------------------------------------------------------------
Prerequisites
-------------
### `bower`: ###
``` bash
# Install bower:
$ npm install -g bower
```
-------------------------------------------------------------------------------
Usage
-----
### Install components: ###
``` bash
$ bower install
```
### Run web server: ###
``` bash
$ python -m http.server
```
Then visit <http://localhost:8000>.
-------------------------------------------------------------------------------
License
-------
`f2e-web-boilerplate` is licensed under [MIT]
[MIT]: ./LICENSE.md
-------------------------------------------------------------------------------
`Created: 2014 Nov`
<file_sep>/py/alchemified/app/app/securities/authentication.py
from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.security import Authenticated, Everyone
from app.models.user import UserModel
class CustomAuthenticationPolicy(AuthTktAuthenticationPolicy):
def authenticated_userid(self, request):
user = request.user
if user:
userid = user.id
return userid
def effective_principals(self, request):
principals = [Everyone]
user = request.user
if user:
principal = Authenticated
userid = user.id
group = user.group
group_ = '{}:{}'.format('group', group)
ACE = (principal, userid, group_)
[principals.append(ep) for ep in ACE]
return principals
def get_user(request):
userid = request.unauthenticated_userid
if userid:
query = request.dbsession.query(UserModel)
user = query.filter_by(id=userid).first()
return user
<file_sep>/py/wooji/wooji/filters.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""filters.py: Wrappers to modify the result of each callbacks."""
def pop_self(callback):
def wrapper(*args, **kwargs):
data = callback(*args, **kwargs)
if isinstance(data, dict):
data.pop('self', None)
return data
return wrapper
<file_sep>/py/wooji/apps/_static/views.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""views.py: Static files routes."""
import controllers as ctrl
routes = [
('/<dir_name:re:.{0}><file_name:re:favicon.ico>', ctrl.static),
('/static/<dir_name>/<file_name>', ctrl.static)
]
<file_sep>/py/wooji/apps/test/__init__.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""__init__.py: File description."""
<file_sep>/README.md
archaic
=======
Nostalgic pet projects
-------------------------------------------------------------------------------
<!-- markdown-toc start - Don't edit this section. Run M-x markdown-toc-generate-toc again -->
**Table of Contents**
- [archaic](#archaic)
- [Languages](#languages)
- [HTML / CSS](#html--css)
- [JavaScript](#javascript)
- [Python](#python)
- [Bash](#bash)
- [Clojure](#clojure)
- [License](#license)
- [Disclaimer](#disclaimer)
<!-- markdown-toc end -->
-------------------------------------------------------------------------------
Languages
---------
### HTML / CSS ###
| Name | Description | Created |
| :----------------------- | :--------------------------------- | :-------- |
| [Laptop ™] | Prelim web design during college | 2007 Oct |
| [The Ultimate Reference] | Read e-books inside the browser | 2010 Mar |
| [hResume] | Microformatted homepage resume | 2010 May |
| [myCareerPath] | Planned skill sets for the future | 2010 July |
| [Web design] | Beginner web design experiments | 2010 Aug |
-------------------------------------------------------------------------------
### JavaScript ###
| Name | Description | Created |
| :----------------------- | :-------------------------------------------- | :-------- |
| [f2e-web-boilerplate] | Front-end web boilerplate with `bower` | 2014 Nov |
| [f2e-web-toolkit] | Front-end web toolkit with `nvm` and `iojs` | 2015 Feb |
| [rw-test] | A failed exam test with `react` and `webpack` | 2017 Apr |
-------------------------------------------------------------------------------
### Python ###
| Name | Description | Created |
| :--------------- | :------------------------------------------------- | :-------- |
| [Template Blog] | Static site generated blog using `Blogofile` | 2012 Sept |
| [Resume] | A simple web application powered by `Bottle` | 2013 Nov |
| [Beginner Blog] | An introduction to `Django` using a blog structure | 2014 Jan |
| [Ragnashop] | Shopping zone for Ragnarok Online gamers | 2014 Apr |
| [Wooji] | A small MVC web framework on top of `Bottle` | 2014 July |
| [Collect CDN] | Download CDN files and move them to a directory | 2015 Feb |
| [ProDev Calc] | Project-Developer project price calculator | 2015 Feb |
| [Alchemified] | The `alchemy` scaffold alternative for `Pyramid` | 2016 June |
-------------------------------------------------------------------------------
### Bash ###
| Name | Description | Created |
| :---------------------------- | :--------------------------------------------- | :-------- |
| [virtualenvwrapper-rm] | The missing `rmproject` of `virtualenvwrapper` | 2016 June |
| [gitbookwrapper] | The `GitBook` cli commands to manage books | 2016 June |
| [shell-site-generator] | Static site generator with `Bash` | 2016 Dec |
-------------------------------------------------------------------------------
### Clojure ###
| Name | Description | Created |
| :--------- | :--------------------------------------------------------- | :-------- |
| [todo-clj] | CRUD example with `Clojure` and `PostgreSQL` using `Yesql` | 2017 Feb |
| [limi] | `Liberator` examples with `Midje` tests | 2017 Mar |
-------------------------------------------------------------------------------
License
-------
`archaic` is licensed under [MIT].
-------------------------------------------------------------------------------
Disclaimer
----------
For the images, their copyright belongs to their respective owners.
[Laptop ™]: ./html-css/laptop-tm
[The Ultimate Reference]: ./html-css/the-ultimate-reference
[hResume]: ./html-css/hresume
[myCareerPath]: ./html-css/my-career-path
[Web design]: ./html-css/web-design
[f2e-web-boilerplate]: ./js/f2e-web-boilerplate
[f2e-web-toolkit]: ./js/f2e-web-toolkit
[rw-test]: ./js/rw-test
[Template Blog]: ./py/template-blog
[Resume]: ./py/resume
[Beginner Blog]: ./py/beginner-blog
[Ragnashop]: ./py/ragnashop
[Wooji]: ./py/wooji
[Collect CDN]: ./py/collect-cdn
[ProDev Calc]: ./py/prodev-calc
[Alchemified]: ./py/alchemified
[virtualenvwrapper-rm]: ./sh/virtualenvwrapper-rm
[gitbookwrapper]: ./sh/gitbookwrapper
[shell-site-generator]: ./sh/shell-site-generator
[todo-clj]: ./clj/todo-clj
[limi]: ./clj/limi
[MIT]: ./LICENSE.md
<file_sep>/py/template-blog/mysite/_filters/hide_html5.py
#!/usr/bin/python
# filename: hide_html5.py
import re
import blogofile_bf as bf
def run(content):
"""Return an HTML5-free (no HTML5 elements and attributes) web page.
"""
enabled = bf.config.filters.hide_html5.enabled
elements = []
attributes = ['placeholder']
if enabled:
for attr in attributes:
content = re.sub(r'%s="(.+?)"\s?' % attr, '', content)
return content
<file_sep>/py/wooji/apps/_static/controllers.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""controllers.py: Static files handler."""
import os
import wooji
def static(dir_name, file_name):
root = os.path.join(wooji.config.DIR_STATIC, dir_name)
return wooji.app.static_file(file_name, root=root)
<file_sep>/py/beginner-blog/apps/blog/models.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""models.py: Blog database tables and columns."""
import os
from datetime import datetime
from django.conf import settings
from django.db import models
from django.utils.text import slugify
from markdown import markdown
class Category(models.Model):
title = models.CharField(max_length=70)
slug = models.SlugField(max_length=70)
description = models.TextField(blank=True)
class Meta:
ordering = 'title',
verbose_name_plural = 'Categories'
def __unicode__(self):
return self.title
class Tag(models.Model):
name = models.SlugField(max_length=70)
description = models.TextField(blank=True)
class Meta:
ordering = 'name',
def __unicode__(self):
return self.name
class Author(models.Model):
nickname = models.SlugField()
class Meta:
ordering = 'nickname',
def __unicode__(self):
return self.nickname
class Post(models.Model):
# Foreign Keys:
UNCATEGORIZED = 1
TAGGED = 1
ADMINISTRATOR = 1
# Post States:
DRAFT = 0
PUBLISHED = 1
CHOICES = (
(DRAFT, 'Draft'),
(PUBLISHED, 'Published'),
)
# Image Paths:
IMAGE_UPLOAD_PATH = lambda instance, image: '{path}/{image}'.format(
path=instance.category.slug,
image='{name}.{extension}'.format(
name=slugify(os.path.splitext(image)[0]).replace('_', ''),
extension=image.split('.')[-1].lower()
)
)
# Fields:
title = models.CharField(max_length=70)
slug = models.SlugField(max_length=70)
image = models.ImageField(upload_to=IMAGE_UPLOAD_PATH, blank=True)
summary = models.TextField()
content = models.TextField()
content_html = models.TextField(editable=False)
category = models.ForeignKey(Category, default=UNCATEGORIZED)
tags = models.ManyToManyField(Tag, default=[TAGGED])
author = models.ForeignKey(Author, default=ADMINISTRATOR)
state = models.IntegerField(choices=CHOICES, default=DRAFT)
published = models.DateField(default=datetime.now, blank=True)
modified = models.DateField(blank=True, null=True)
class Meta:
ordering = 'published',
def save(self):
self.content_html = markdown(self.content, ['codehilite'])
self.modified = datetime.now()
if not self.id:
self.published = self.modified
super(Post, self).save()
def __unicode__(self):
return self.title
<file_sep>/js/rw-test/src/app.jsx
require('./app.scss');
import React from 'react';
import ReactDOM from 'react-dom';
import Header from './components/header.jsx';
import Content from './components/content.jsx';
import Footer from './components/footer.jsx';
ReactDOM.render(
<div className="wrapper">
<Header />
<Content />
<Footer />
</div>,
document.getElementById('app')
);
<file_sep>/py/template-blog/mysite/_filters/pseudo_markdown.py
#!/usr/bin/python
# filename: pseudo_markdown.py
import re
import blogofile_bf as bf
def run(content):
"""Return processed 'unofficial' Markdown pattern that allows to add any
HTML attributes and attribute values on any elements that can use
Markdown's title attribute.
Formats:
"title !|attribute='value'|"
"title !|attribute='value', attribute='value'|"
"!|attribute='value'|"
"!|attribute='value', attribute='value'|"
Examples:
Adding a width and height on <img />:
* Inline:

* Referenced:
![alt][id]
[id]: /img/logo.png "title !|width='150', height='150'|"
"""
enabled = bf.config.filters.pseudo_markdown.enabled
titles = re.findall(r'title=(".+?")', content)
pattern = '!\|.+?\|'
for title in titles:
old_attr = title
new_attr = ''
if re.search(r'%s' % pattern, old_attr):
title = re.sub(r'%s|^"|\s*"$' % pattern, '', old_attr).strip()
attr = re.sub(r'^.+?!\||\|.+?', '', old_attr)
attrs = attr.replace('\'', '"')
attrs = ' '.join(attrs.split(','))
new_attr = '"%s" %s' % (title, attrs)
content = content.replace(old_attr, new_attr)
# Remove title attributes with empty values
empty_titles = re.findall(r'<.+?title="".+?>', content)
for empty_title in empty_titles:
content = content.replace('title=""', '')
return content
<file_sep>/py/beginner-blog/apps/blog/urls.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""urls.py: Blog URL configuration and patterns."""
from django.conf.urls import patterns
urlpatterns = patterns(
'',
(r'^$', 'apps.blog.views.index'),
(r'^(?P<post_slug>[-\w]+)$', 'apps.blog.views.post'),
(r'^category/(?P<category_slug>[-\w]+)$', 'apps.blog.views.category'),
(r'^tag/(?P<tag_name>[-\w]+)$', 'apps.blog.views.tag'),
)
<file_sep>/py/ragnashop/README.md
ragnashop
=========
Shopping zone for Ragnarok Online gamers
-------------------------------------------------------------------------------
Prerequisites
-------------
### `virtualenvwrapper`: ###
``` bash
# Install virtualenvwrapper:
$ sudo pip install virtualenvwrapper
# Update .bashrc:
$ echo '
export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=$HOME/Devel
source /usr/local/bin/virtualenvwrapper.sh
' >> ~/.bashrc
# Reload .bashrc:
. ~/.bashrc
# Create Devel directory:
$ mkdir -p ${PROJECT_HOME}
```
-------------------------------------------------------------------------------
Set up project
--------------
### Virtualenv: ###
``` bash
# Create and switch to virtualenv:
$ mkproject -p /usr/bin/python2 ragnashop
# Clone repository in current directory:
$ git clone https://github.com/ejelome/ragnashop .
# Install packages:
$ pip install -r requirements.txt
```
### Localhost alias: ###
``` text
# Switch to root account:
$ sudo su
# Append new localhost alias:
$ echo '127.0.0.1 mydomain.tld' >> /etc/hosts
# Exit root account:
$ exit
```
### Facebook OAuth keys: ###
Open `config.py` and update the following with a Facebook app's OAuth keys:
``` text
FB_APP_ID = ''
FB_APP_SECRET = ''
```
-------------------------------------------------------------------------------
How-tos
-------
First, log in to [facebook for developers] then do the following:
_(Register if not yet registered)_.
### Create Facebook app: ###
1. Click `Create a New App`
2. Enter `Ragnashop` on `Display Name`
3. Select `Apps for Pages` from `Category`'s `Choose a Category`
4. Click `Create App ID`
5. Complete `Security Check`
6. You'll be redirected once successful
### Obtain OAuth keys: ###
1. Click `Dashboard`
2. Click `Show` to show `App Secret`
#### Note: ####
* The `App ID` is the corresponding `FB_APP_ID`
* The `App Secret` is the corresponding `FB_APP_SECRET`
### Register app domain: ###
1. Click `Settings`
2. Enter `mydomain.tld` on `App Domains`
3. Scroll down then click `Add Platform`
4. Click `Website`
5. Enter `http://mydomain.tld` on `Site URL`
6. Click `Save Changes`
### Enable app on public: ###
1. Click `App Review`
2. Click switch under `Make Ragnashop public?`
3. Click `Confirm`
-------------------------------------------------------------------------------
Run project
-----------
```bash
$ python server.py
```
Then visit <http://mydomain.tld:8080>.
-------------------------------------------------------------------------------
Reset project
-------------
``` bash
$ ./reset.sh
```
-------------------------------------------------------------------------------
License
-------
`ragnashop` is licensed under [MIT].
[facebook for developers]: https://developers.facebook.com/apps
[MIT]: ./LICENSE.md
-------------------------------------------------------------------------------
`Created: 2014 Apr`
<file_sep>/py/alchemified/README.md
alchemified
===========
The `alchemy` scaffold alternative for [Pyramid]
Table of Contents
-----------------
* [Introduction](#introduction)
* [Dependencies](#dependencies)
* [How the scaffold was created](#how-the-scaffold-was-created)
1. [Create a remote repo](#create-a-remote-repo)
2. [Setup a local repo](#setup-a-local-repo)
3. [Create an scaffold](#create-an-scaffold)
4. [Refactor the scaffold](#refactor-the-scaffold)
5. [Update the remote repo](#update-the-remote-repo)
* [Setting up OAuth Login](#setting-up-oauth-login)
1. [Add a domain alias](#add-a-domain-alias)
2. [Create a Facebook app](#create-a-facebook-app)
3. [Obtain the OAuth keys](#obtain-the-oauth-keys)
4. [Register app domain](#register-app-domain)
5. [Enable app on public](#enable-app-on-public)
* [Running the scaffold](#running-the-scaffold)
1. [Move to project](#move-to-project)
2. [Provide the keys](#provide-the-keys)
3. [Test the scaffold](#test-the-scaffold)
4. [Run the scaffold](#run-the-scaffold)
5. [Visit the homepage](#visit-the-homepage)
* [Structure](#structure)
* [Workflow](#workflow)
* [License](#license)
-------------------------------------------------------------------------------
Introduction
------------
The `Pyramid` web framework, while simple and flexible, can be overwhelming on both documentation and scaffold structure.
The `Alchemified` scaffold, while being a personal recommendation, can serve as a simpler alternative and a saner introduction to gradually learn the `Pyramid` web framework.
-------------------------------------------------------------------------------
Dependencies
------------
| Name | Type |
|:------------------- |:---------------------- |
| [git] | Version control system |
| [GitHub] | Git hosting service |
| [pip] | Package manager |
| [pyenv] | Version manager |
| [pyenv-virtualenv] | Virtual environment |
| [virtualenvwrapper] | Virtualenv manager |
| [Python] `3.5.1+` | Programming language |
| [Pyramid] `1.7+` | Web framework |
| <hr /> | <hr /> |
-------------------------------------------------------------------------------
How the scaffold was created
----------------------------
### Create a remote repo: ###
_`remote` implies that it is located **outside** your machine._
1. Visit [GitHub]'s [Create a new repository] page
2. Create a repo and name it `alchemified`
### Setup a local repo: ###
_`local` implies that it is located **inside** your machine._
``` bash
# Create and move to virtualenv:
$ mkproject alchemified && deactivate
# Trivia: "deactivate" disables the virtualenv
# Clone the remote repo:
$ git clone https://github.com/ejelome/alchemified .
# Trivia: "." clones the remote repo on the current directory
# Install a Python version:
$ pyenv install 3.5.1
# Trivia: Use "pyenv install -l" to see all available versions
# Create a virtualenv:
$ pyenv virtualenv 3.5.1 1.7-3.5.1
# Trivia: "1.7-3.5.1" means "PyramidVersion-PythonVersion"
# Register the `virtualenv`:
$ pyenv local 1.7-3.5.1
# Trivia: "local" sets the "virtualenv-name" in ".python-version" file
# Comment out .python-version:
$ sed -i 's/.python-version/# .python-version/g' .gitignore
```
### Create an scaffold: ###
``` bash
# Upgrade pip:
$ pip install -U pip
# Install Pyramid:
$ pip install pyramid
# Create an alchemy scaffold:
$ pcreate -s alchemy app
# Trivia: "alchemy" is an scaffold for "SQLAlchemy" and "URL dispatch"
```
### Refactor the scaffold: ###
``` bash
# Install isort:
$ pip install isort
# Sort Python imports:
$ echo app/app/*.py app/app/*/*.py | xargs -n 1 isort -ns __init__.py
# Trivia: "isort -rc ." won't work with "-ns" parameter
# Remove untracked files:
$ git clean -Xdf
```
### Update the remote repo: ###
``` bash
# Add all files:
$ git add -A
# Record changes:
$ git commit -m 'Add and refactor alchemy scaffold'
# Update remote refs:
$ git push -u origin master
# Trivia: "-u" makes "git push" to now point to "origin/master"
```
-------------------------------------------------------------------------------
Setting up OAuth Login
----------------------
### Add a domain alias: ###
``` bash
# Switch to root account:
$ sudo su
# Append new localhost alias:
$ echo '127.0.0.1 mydomain.tld' >> /etc/hosts
# Exit root account:
$ exit
```
### Create a Facebook app: ###
1. Click `Create a New App`
2. Enter `Alchemified` on `Display Name`
3. Select `Apps for Pages` from `Category`'s `Choose a Category`
4. Click `Create App ID`
5. Complete `Security Check`
6. You'll be redirected once successful
### Obtain the OAuth keys: ###
1. Click `Dashboard`
2. Click `Show` to show `App Secret`
#### Note: ####
* The `App ID` is the corresponding `facebook.consumer_key`
* The `App Secret` is the corresponding `facebook.consumer_secret`
### Register app domain: ###
1. Click `Settings`
2. Enter `mydomain.tld` on `App Domains`
3. Scroll down then click `Add Platform`
4. Click `Website`
5. Enter `http://mydomain.tld` on `Site URL`
6. Click `Save Changes`
### Enable app on public: ###
1. Click `App Review`
2. Click switch under `Make Alchemified public?`
3. Click `Confirm`
-------------------------------------------------------------------------------
Running the scaffold
--------------------
### Move to project: ###
``` bash
$ workon alchemified && deactivate
```
### Provide the keys: ###
_Supply the necessary keys in `*.ini` (e.g. `development.ini`)._
``` bash
...
session.secret =
...
authentication.secret =
...
authomatic.secret =
facebook.consumer_key =
facebook.consumer_secret =
```
#### Note: ####
_`session.secret`, `authentication.secret`, and `authomatic.secret` are your own arbitrary keys._
### Test the scaffold: ###
``` bash
# Install dependencies:
$ pip install -e app/[testing]
# Trivia: "[testing]" corresponds to "setup.py#extras_require"
# Start the test:
$ py.test --cov=app/ -q
# Trivia: "-q" limits the verbose output to dots "..."
```
#### Test configuration files: ####
* `pytest.ini`
* `.coveragerc`
### Run the scaffold: ###
``` bash
# Install the scaffold:
$ pip install -e app/
# Trivia: "-e" creates an editable install
# Create the database:
$ initialize_app_db app/development.ini
" Trivia: "initialize_app_db" corresponds to "setup.py#entry_points"
# Start the server:
$ pserve app/development.ini --reload
# Trivia: "--reload" auto reloads the server on file update
```
#### Application configuration files: ####
* `development.ini`
* `production.ini`
### Visit the homepage: ###
#### Page URLs: ####
| Page | URL |
| :------- | :---------------------------------- |
| Homepage | <http://mydomain.tld:8080> |
| Log In | <http://mydomain.tld:8080/login> |
| Log Out | <http://mydomain.tld:8080/logout> |
| Settings | <http://mydomain.tld:8080/settings> |
| | |
-------------------------------------------------------------------------------
Structure
---------
_Example: `setting` as the `resource`._
``` bash
app/
├── models/
│ ├── __init__.py
│ ├── __meta__.py
│ └── setting.py
├── fixtures/
│ ├── __init__.py
│ └── setting.json
├── scripts/
│ ├── __init__.py
│ └── initializedb.py
├── views/
│ ├── __init__.py
│ └── setting.py
├── forms/
│ ├── __init__.py
│ └── setting.py
├── templates/
│ ├── setting/
│ │ ├── index.pt
│ │ ├── add.pt
│ │ ├── read.pt
│ │ └── edit.pt
│ └── base.pt
├── routes/
│ ├── __init__.py
│ └── setting.py
├── securities/
│ ├── __init__.py
│ ├── authentication.py
│ └── authorization.py
├── helpers/
│ ├── __init__.py
│ └── setting.py
├── tests/
│ ├── __init__.py
│ └── setting.py
├── public/
│ ├── 404.pt
│ ├── robots.txt
│ ├── favicon.ico
│ └── apple-touch-icon.png
├── static/
│ ├── img/
│ │ ├── logo.png
│ │ └── logo.min.png
│ ├── css/
│ │ ├── vendor/
│ │ │ └── deform.min.css
│ │ ├── styles.css
│ │ └── styles-x.y.z.min.css
│ ├── js/
│ │ ├── vendor/
│ │ │ └── deform.min.js
│ │ ├── scripts.js
│ │ └── scripts-x.y.z.min.js
│ └── fonts/
│ ├── Name-Weight.eot
│ ├── Name-Weight.ttf
│ ├── Name-Weight.woff
│ └── Name-Weight.woff2
└── media/
└── user-slug/
└── photo.png
```
-------------------------------------------------------------------------------
Workflow
--------
| Step | Description | Location | Purpose |
|:---- |:------------------------------- |:------------------------- |:----------------------- |
| 1 | Create a model | `models/` | Data blueprint |
| 2 | Create a model fixture | `fixtures/` | Initial data |
| 3 | Create a controller | `views/` | Data logic |
| 4 | Create a controller helper | `helpers/` | Reusable logic shortcut |
| 5 | Create a route | `routes/` | URLs to access data |
| 6 | Create a view | `templates/` | Data representation |
| 7 | Create a view form | `forms/` | Reusable data forms |
| 8 | Create a test case | `tests/` | Verify data accuracy |
-------------------------------------------------------------------------------
License
-------
`alchemified` is licensed under [MIT].
[GitHub]: https://github.com
[git]: https://git-scm.com
[pip]: https://pip.pypa.io
[pyenv]: https://github.com/yyuu/pyenv
[pyenv-virtualenv]: https://github.com/yyuu/pyenv-virtualenv
[virtualenvwrapper]: http://virtualenvwrapper.readthedocs.io
[Python]: https://www.python.org
[Pyramid]: http://www.pylonsproject.org
[Create a new repository]: https://github.com/new
[MIT]: ./LICENSE.md
-------------------------------------------------------------------------------
`Created: 2016 June`
<file_sep>/py/resume/modules/logger.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""logger.py: Handler for logging."""
import datetime
import logging
import os
import config
class Logger:
"""TODO: Class docstring."""
def __init__(self, name=__name__, base=config.LOGS, db=config.DATABASE,
file_=None, format_=None, time_format='%Y-%m-%d %I:%M:%S %p',
file_level=logging.INFO, handler_level=logging.WARNING):
"""TODO: Method docstring."""
if not os.path.exists(base):
os.makedirs(base)
if not file_:
file_ = '{date}.log'.format(
date=datetime.datetime.today().strftime('%Y-%m-%d')
)
if not format_:
format_= '[%(asctime)s][{db}] %(name)s:{file} %(levelname)s: ' \
'%(message)s'.format(
db=os.path.basename(db),
file=os.path.basename(__file__)
)
name = '{name}'.format(name=name)
file_path = '{base}/{file}'.format(base=base, file=file_)
logger = logging.getLogger(name)
handler = logging.FileHandler(file_path)
formatter = logging.Formatter(format_, time_format)
logger.setLevel(file_level)
logger.addHandler(handler)
handler.setLevel(handler_level)
handler.setFormatter(formatter)
self.logger = logger
def log(self):
"""TODO: Method docstring."""
return self.logger
<file_sep>/py/wooji/wooji/server.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""server.py: Handle application's run command and its parameters."""
import app
import config
import session
def run(**kwargs):
info = dict(
server=config.SERVER_WSGI,
host=config.SERVER_HOST,
port=config.SERVER_PORT,
debug=config.SERVER_DEBUG,
reloader=config.SERVER_RELOADER,
interval=config.SERVER_INTERVAL,
quiet=config.SERVER_QUIET
)
info.update(kwargs)
app.run(app=session.session, **info)
<file_sep>/sh/gitbookwrapper/.gitbookwrapper
#!/bin/bash
# .gbwrc file path:
GBW_RC=${HOME}/.gbwrc
# Load .gbwrc to overwrite default vars:
[[ -f ${GBW_RC} ]] && . ${GBW_RC}
# gitbookwrapper default vars:
GBW_SCRIPT='gitbookwrapper'
GBW_HELP_DESC='-h, --help \t Show this help message.'
[[ -z ${GBW_HOME} ]] && GBW_HOME=${HOME}/GitBooks
[[ -z ${GBW_TRASH} ]] && GBW_TRASH=${HOME}/.local/share/Trash/files
[[ -z ${GBW_LABEL_USAGE} ]] && GBW_LABEL_USAGE='Usage:\n\t'
[[ -z ${GBW_LABEL_EXAMPLE} ]] && GBW_LABEL_EXAMPLE='Example:\n\t'
[[ -z ${GBW_LABEL_OPTIONS} ]] && GBW_LABEL_OPTIONS='Options:\n\t'
[[ -z ${GBW_LABEL_FAILED} ]] && GBW_LABEL_FAILED="failed:\n\t"
[[ -z ${GBW_LABEL_SUCCESS} ]] && GBW_LABEL_SUCCESS="successful!\n\t"
# Create GBW_HOME directory if not existing:
[[ ! -d ${GBW_HOME} ]] && mkdir -p ${GBW_HOME}
# Create GBW_TRASH directory if not existing:
[[ ! -d ${GBW_TRASH} ]] && mkdir -p ${GBW_TRASH}
# gitbookwrapper auto-complete:
_gitbookwrapper_completion() {
COMPREPLY=($(compgen -W "$(ls ${GBW_HOME})" -- ${COMP_WORDS[COMP_CWORD]}))
}
complete -o nospace -F _gitbookwrapper_completion bookon rmbook
function gitbookwrapper() {
# gitbookwrapper is a set of commands to manage GitBook directories.
#
# Usage:
# mkbook BOOK_NAME
# bookon
# bookon BOOK_NAME
# rmbook BOOK_NAME
#
# Example:
# mkbook myawesomebook
# bookon
# bookon myawesomebook
# rmbook myawesomebook
DOC="https://github.com/ejelome/${GBW_SCRIPT}/blob/master/README.md"
echo -e "${GBW_SCRIPT} is a set of commands to manage GitBook directories.\n"
echo -e "See documentation for more info:\n\n\t${DOC}\n"
echo -e 'List of available commands:\n'
echo -e '\tmkbook:\n\t\tCreate and move to the new BOOK_NAME.\n'
echo -e '\tbookon:\n\t\tDisplay all existing BOOK_NAMEs or move to a BOOK_NAME.\n'
echo -e '\trmbook:\n\t\tRemove and move from an existing BOOK_NAME.'
}
function mkbook() {
# Create and move to the new BOOK_NAME.
#
# Usage:
# mkbook BOOK_NAME
#
# Example:
# mkbook myawesomebook
#
# Options:
# -h, --help Show this help message.
BOOK_PATH=${GBW_HOME}/${1}
if [[ ${#} < 1 || ${1} =~ ^-h$|^--help$ ]]; then
if [[ ${1} =~ ^-h$|^--help$ ]]; then
echo -e 'Create and move to the new BOOK_NAME.\n'
else
echo -e 'You must provide a BOOK_NAME.\n'
fi
echo -e "${GBW_LABEL_USAGE} mkbook BOOK_NAME\n"
echo -e "${GBW_LABEL_EXAMPLE} mkbook myawesomebook\n"
echo -e "${GBW_LABEL_OPTIONS} ${GBW_HELP_DESC}"
elif [[ ${#} > 1 ]]; then
echo -e "${GBW_SCRIPT} ${GBW_LABEL_FAILED} The BOOK_NAME can only be a single argument."
elif [[ ${1} =~ [^a-zA-Z0-9_-] ]]; then
echo -e "${GBW_SCRIPT} ${GBW_LABEL_FAILED} The BOOK_NAME can only contain letters, numbers, hyphens, and underscores."
elif [[ ${1} =~ ^-|-$ ]]; then
echo -e "${GBW_SCRIPT} ${GBW_LABEL_FAILED} The BOOK_NAME cannot begin or end with a hyphen."
elif [[ -d ${BOOK_PATH} ]]; then
echo -e "${GBW_SCRIPT} ${GBW_LABEL_FAILED} The BOOK_NAME '${1}' already exists."
else
mkdir -p ${BOOK_PATH} && cd ${BOOK_PATH}
echo -e "${GBW_SCRIPT} ${GBW_LABEL_SUCCESS} Creating '${BOOK_PATH}'\n"
echo "The BOOK_NAME '${1}' was successfully created."
fi
}
function bookon() {
# Display all existing BOOK_NAMEs or move to a BOOK_NAME.
#
# Usage:
# bookon
# bookon BOOK_NAME
#
# Example:
# bookon
# bookon myawesomebook
#
# Options:
# -h, --help Show this help message.
BOOK_PATH=${GBW_HOME}/${1}
if [[ ${#} < 1 || ${1} =~ ^-h$|^--help$ ]]; then
if [[ ${1} =~ ^-h$|^--help$ ]]; then
echo -e 'Display all existing BOOK_NAMEs or move to a BOOK_NAME.\n'
echo -e "${GBW_LABEL_USAGE} bookon \n\t bookon BOOK_NAME\n"
echo -e "${GBW_LABEL_EXAMPLE} bookon \n\t bookon myawesomebook\n"
echo -e "${GBW_LABEL_OPTIONS} ${GBW_HELP_DESC}"
else
for book in $(ls ${GBW_HOME[@]}); do
echo ${book}
done
fi
elif [[ ${#} > 1 ]]; then
echo -e "${GBW_SCRIPT} ${GBW_LABEL_FAILED} The BOOK_NAME can only be a single argument."
elif [[ ! -d ${BOOK_PATH} ]]; then
echo -e "${GBW_SCRIPT} ${GBW_LABEL_FAILED} The BOOK_NAME '${1}' does not exists."
else
cd ${BOOK_PATH}
fi
}
function rmbook() {
# Remove and move from an existing BOOK_NAME.
#
# Usage:
# rmbook BOOK_NAME
#
# Example:
# rmbook myawesomebook
#
# Options:
# -h, --help Show this help message.
BOOK_PATH=${GBW_HOME}/${1}
if [[ ${#} < 1 || ${1} =~ ^-h$|^--help$ ]]; then
if [[ ${1} =~ ^-h$|^--help$ ]]; then
echo -e 'Remove and move from an existing BOOK_NAME.\n'
else
echo -e 'You must provide a BOOK_NAME.\n'
fi
echo -e "${GBW_LABEL_USAGE} rmbook BOOK_NAME\n"
echo -e "${GBW_LABEL_EXAMPLE} rmbook myawesomebook\n"
echo -e "${GBW_LABEL_OPTIONS} ${GBW_HELP_DESC}"
elif [[ ${#} > 1 ]]; then
echo -e "${GBW_SCRIPT} ${GBW_LABEL_FAILED} The BOOK_NAME can only be a single argument."
elif [[ ! -d ${BOOK_PATH} ]]; then
echo -e "${GBW_SCRIPT} ${GBW_LABEL_FAILED} The BOOK_NAME '${1}' does not exists."
else
mv ${BOOK_PATH} -fv --backup=numbered -t ${GBW_TRASH} && cd ${GBW_HOME}
echo -e "\n${GBW_SCRIPT} ${GBW_LABEL_SUCCESS} Removing '${BOOK_PATH}'\n"
echo "The BOOK_NAME '${1}' was successfully removed."
fi
}
<file_sep>/py/wooji/apps/test/controllers.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""controllers.py: File description."""
import os
import forms
import models
import serializers
import wooji
class Test:
def GET(self):
messages = wooji.db.session.query(models.Test).all()
method = wooji.app.request.method
request = getattr(wooji.app.request, method)
form = forms.TestForm(request)
return locals()
def POST(self):
method = wooji.app.request.method
request = getattr(wooji.app.request, method)
form = forms.TestForm(request)
if form.validate():
message = {field.name: field.data for field in form}
task = models.Test(**message)
wooji.db.session.add(task)
wooji.db.session.commit()
messages = wooji.db.session.query(models.Test).all()
return locals()
def test():
method = wooji.app.request.method
request = getattr(wooji.app.request, method)
form = forms.TestForm(request)
if method == 'POST' and form.validate():
message = {field.name: field.data for field in form}
task = models.Test(**message)
wooji.db.session.add(task)
wooji.db.session.commit()
messages = wooji.db.session.query(models.Test).all()
return locals()
def json():
model = wooji.db.session.query(models.Test)
messages = serializers.TestSerializer(model, many=True).data
return wooji.helpers.to_json(locals())
<file_sep>/sh/shell-site-generator/README.md
shell-site-generator
====================
Static site generator with `Bash`
-------------------------------------------------------------------------------
Prerequisites
-------------
### `marked`: ###
```
$ npm install -g marked
```
-------------------------------------------------------------------------------
Usage
-----
Create and/or edit `*.md` files on `src/posts/`, then do:
``` bash
$ bash convrt
# Or make the script self-executable:
$ chmod +x convrt
$ ./convrt
```
Then just copy and paste the contents of `public/` on your host.
-------------------------------------------------------------------------------
Preview
-------
To view what the generated pages look like:
``` bash
# Go to public/
$ cd public/
# Run a web server:
$ python -m http.sever
```
Then visit <http://localhost:8000>.
-------------------------------------------------------------------------------
Structure
---------
| Variable | Default Path | Description |
| :--------- | :-------------------------- | :------------------------------------------ |
| `header` | `src/templates/header.html` | The generic header layout of generated html |
| `footer` | `src/templates/footer.html` | The generic footer layout of generated html |
| `static` | `src/static/` | The static assets used by the layout |
| `posts` | `src/posts/` | The markdown files to be converted |
| `dest` | `public/` | The destination of generated pages |
-------------------------------------------------------------------------------
License
-------
`shell-site-generator` is licensed under [MIT].
[MIT]: ./LICENSE.md
-------------------------------------------------------------------------------
`Created: 2016 Dec`
<file_sep>/py/wooji/apps/test/models.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""models.py: File description."""
import sqlalchemy as orm
import wooji
class Test(wooji.db.Base):
__tablename__ = 'home'
id = orm.Column(orm.Integer, primary_key=True)
name = orm.Column(orm.String, nullable=False)
message = orm.Column(orm.String, nullable=False)
def __repr__(self):
return '<User(id="{id}", name="{name}", message="{message}")>'.format(
**locals()
)
<file_sep>/py/collect-cdn/collect.ini
# collect.py configuration
# https://github.com/ejelome/collect-cdn
[cdn]
path = https://cdnjs.com/libraries
file =
modernizr
jquery
foundation
react
normalize
web-starter-kit/h5bp
dojo
url =
https://raw.githubusercontent.com/h5bp/html5-boilerplate/master/src/js/plugins.js
https://ajax.googleapis.com/ajax/libs/dojo/1.3.2/dijit/dijit.js
[option]
xpath =
//div[@class="assets panel panel-primary active"]
/div/table/tbody/tr/td/p/text()
extension = .min.(cs|j)s$
dot_length = 2
subdir = vendor
<file_sep>/py/alchemified/app/app/views/home.py
from pyramid.view import view_config
class HomeView(object):
pt = 'app:templates/home/{}.pt'
def __init__(self, request):
self.request = request
@view_config(route_name='home',
request_method='GET',
permission='read',
renderer=pt.format('index'))
def index(self):
return {}
<file_sep>/py/wooji/apps/test/forms.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""forms.py: File description."""
import wtforms
import wtforms_alchemy
import models
import wooji
class TestForm(wtforms_alchemy.ModelForm):
class Meta:
model = models.Test
field_args = dict(
name=dict(label='Name:'),
message=dict(label='Mesage:', widget=wtforms.widgets.TextArea())
)
@classmethod
def get_session(cls):
return wooji.db.session
<file_sep>/py/alchemified/app/app/helpers/__init__.py
from os import listdir
from os.path import basename, dirname, isfile, join
class TreeHelper(object):
def __init__(self, base_dir):
self.base_dir = dirname(base_dir)
def modules(self, exclusions=None):
exclusions = exclusions or ['__init__.py', '__meta__.py']
modules = [
basename(module.split('.')[0])
for module in listdir(self.base_dir)
if isfile(join(self.base_dir, module)) and module not in exclusions
]
return modules
<file_sep>/py/resume/assets/js/script-0.1.js
/* Warning prompt for the Remove button */
input = document.getElementsByTagName('input');
for (var i = 0; i < input.length; i += 1) {
if (input[i].name === 'remove') {
input[i].onclick = function () {
if (!confirm('Warning! This cannot be undone.\n\nContinue?')) {
return false;
}
};
}
}
<file_sep>/clj/todo-clj/README.md
todo-clj
========
CRUD example with `Clojure` and `PostgreSQL` using `Yesql`
-------------------------------------------------------------------------------
Setup
-----
1. [Install and setup clj/cljs development environment]
2. [Install and setup PostgreSQL]
3. Download repo:
``` bash
$ git clone https://github.com/ejelome/todo-clj.git
```
4. Create database then exit:
``` bash
$ sudo -u postgres -i
[postgres@computername ~]$ createuser -s -P todouser
Enter password for new role: <PASSWORD>
Enter it again: todopass
[postgres@computername ~]$ createdb -U todouser tododb
[postgres@computername ~]$ exit
```
-------------------------------------------------------------------------------
Usage
-----
Run:
```
$ lein run
```
-------------------------------------------------------------------------------
License
-------
`todo-clj` is licensed under [MIT].
[Install and setup clj/cljs development environment]: https://ejelome.com/install-and-setup-clj-cljs-development-environment
[Install and setup PostgreSQL]: https://ejelome.com/install-and-setup-postgresql
[MIT]: ./LICENSE.md
-------------------------------------------------------------------------------
`Created: 2017 Feb`
<file_sep>/py/ragnashop/html.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""html.py: TODO"""
lang = 'en-US'
charset = 'utf-8'
robots = 'noydir, noodp'
site = 'Ragnashop'
title = site
description = 'Get more customers by having an online game shop for free.'
tagline = 'Online Shop for Ragnarok Online Gamers'
document_title = '{main} - {sub}'.format(main=title, sub=tagline)
icon_url = '/favicon.ico'
style_url = '/css/style-0.1.css'
script_url = '/js/script-0.1.js'
body_class = 'home'
current_class = body_class
<file_sep>/py/ragnashop/requirements.txt
Beaker==1.6.4
SQLAlchemy==0.9.4
argparse==1.2.1
bottle==0.12.7
rauth==0.7.0
requests==2.3.0
wsgiref==0.1.2
<file_sep>/js/rw-test/src/components/content.jsx
import React, {Component} from 'react';
import update from 'immutability-helper';
class Review extends Component {
constructor() {
super();
this.state = {
votes: {
positive: 0,
negative: 0
}
};
this.voteIncrement = this.voteIncrement.bind(this);
this.voteDecrement = this.voteDecrement.bind(this);
}
componentDidMount() {
fetch('/data/reviews.json')
.then((response) => {
return response.json();
}).then((json) => {
let newState = update(this.state, {
votes: {$set: json.votes}
});
this.setState(newState);
});
}
voteIncrement() {
let newState = update(this.state, {
votes: {
positive: {$set: this.state.votes.positive + 1}
}
});
this.setState(newState);
}
voteDecrement() {
let newState = update(this.state, {
votes: {
negative: {$set: this.state.votes.negative - 1}
}
});
this.setState(newState);
}
render() {
return (
<div className="review">
<div className="positive-review">
<div className="vote-count">{this.state.votes.positive}</div>
<button className="vote-increase"
onClick={this.voteIncrement}>+ Positive</button>
</div>
<div className="negative-review">
<div className="vote-count">{this.state.votes.negative}</div>
<button className="vote-decrease"
onClick={this.voteDecrement}>- Negative</button>
</div>
</div>
);
}
}
const Shop = (props) => {
return (
<div className="shop">
<img className="logo"
src={props.logo}
width={200}
height={100}
alt={props.name} />
<h2 className="name">{props.name}</h2>
<div className="location">{props.location}</div>
<div className="distance">{props.distance}km</div>
<button className="feedback">Feedback</button>
</div>
)
}
export default class Content extends Component {
constructor() {
super();
this.state = {
logo: "",
name: "",
location: "",
distance: 0,
}
}
componentDidMount() {
fetch('/data/reviews.json')
.then((response) => {
return response.json();
}).then((json) => {
this.setState(json);
});
}
render() {
return (
<main>
<Review />
<Shop {...this.state} />
</main>
);
}
}
<file_sep>/py/wooji/wooji/db.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""db.py: Database handler to communicate with the ORM."""
import os
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
import config
import helpers
class SetTextFactory(sqlalchemy.interfaces.PoolListener):
def connect(self, db_api_conn, conn_record):
db_api_conn.text_factory = str
db_path = '{}:{}{}'.format(config.DB_TYPE, config.DB_DEST, config.DB_PATH)
listeners = [SetTextFactory()]
engine = sqlalchemy.create_engine(db_path, listeners=listeners)
engine.connect().connection.connection.text_factory = str
Base = declarative_base()
models = helpers.get_modules(config.DIR_APPS)
session = sqlalchemy.orm.sessionmaker(bind=engine)()
<file_sep>/py/template-blog/README.md
template-blog
=============
Static site generated blog using `Blogofile`
-------------------------------------------------------------------------------
Prerequisites
-------------
### `virtualenv`: ###
``` bash
$ \
pip install virtualenv # install virtualenv
virtualenv -p /usr/bin/python2 venv # create a virtualenv
source venv/bin/activate # switch to virtualenv
# deactivate # deactivate virtualenv
```
### `Blogofile` dependencies: ###
``` bash
$ pip install blogofile blogofile_blog bs4
```
-------------------------------------------------------------------------------
Usage
-----
### Build pages: ###
``` bash
$ blogofile build -s mysite
```
### Serve pages: ###
``` bash
$ blogofile serve -s mysite
```
Then visit <http://localhost:8080>.
-------------------------------------------------------------------------------
Transcript 1
------------
> \#\# Some non-obvious and/or non-existing features in Blogofile:
> * Can't put categories on Homepage
> * Can't put subcategories
> * Can't dynamically generate tag pages (only posts, categories, and dates)
> * Can't provide search functionality (it's ok, there's Google Custom Search)
> * Can't create pagination (paging---stucked at prev/next)
>
> \#\# Some usual site and/or blog design conventions not applicable in Blogofile:
> * Local Navigation
> * No Tagging (or tags---if there is, then it's not working)
-------------------------------------------------------------------------------
Transcript 2
------------
``` text
|-- Room for improvements:
|-- |-- About (website)
|-- |-- Search (Google Custom Search)
|-- |-- /blog/chronological.mako (comments)
|-- |-- /blog/post.mako (comments)
|-- Create 404 page
|-- Ask how to make a mako file for:
|-- |-- /blog/archive/yyyy/mm
|-- |-- /blog/archive/yyyy/mm/d
|-- |-- Add Disqus 'count' for each posts (No comments, 1 comment, 10 comments)
|-- Use Unobtrusive JavaScript to the following:
|-- |-- Include Social Buttons:
|-- |-- |-- Facebook Like
|-- |-- |-- Twitter Follow
|-- |-- |-- Google +1
|-- |-- |-- LinkedIn Share
|-- |-- Include Social Widgets:
|-- |-- |-- Twitter Tweets (5 recent tweets)--- only for the homepage
|-- |-- |-- |-- NOTE: Use jQuery if necessary (js files only in homepage)
|-- |-- |-- |-- Facebook Like Box? Not good, I'm not a company
|-- |-- Include Disqus
|-- |-- |-- Make a 'counter' (both on listings and actual posts)
|-- Mako invalid XHTML as JavaScript code
|-- Design Pattern:
|-- |-- Content
|-- |-- SEO
|-- |-- Web Usability
|-- |-- Web Accessbility
|-- |-- Web Performance
```
-------------------------------------------------------------------------------
`Created: 2012 Sept`
<file_sep>/clj/limi/README.md
limi
====
[Liberator] examples with [Midje] tests
-------------------------------------------------------------------------------
Setup
-----
1. [Install and setup clj/cljs development environment]
2. Download repo:
```
$ git clone https://github.com/ejelome/limi.git
```
3. Install dependencies:
``` bash
$ lein deps
```
-------------------------------------------------------------------------------
(Auto)test
----------
``` bash
# Manual test:
$ lein midje
# or autotest:
$ lein midje :autotest
# or autotest with REPL:
$ lein repl
user=> (use 'midje.repl)
user=> (autotest)
```
-------------------------------------------------------------------------------
Lint
----
``` bash
$ lein eastwood
```
-------------------------------------------------------------------------------
Compile to `jar`
----------------
``` bash
$ lein ring uberjar
```
-------------------------------------------------------------------------------
Run web server
--------------
``` bash
# Development:
$ lein ring server
# or production:
$ java -jar target/*standalone.jar
```
Then visit <http://localhost:3000>.
-------------------------------------------------------------------------------
Examples
--------
| Topic | File: `src/` | File: `test/` | Method | Resource |
| :--------------------- | :------------------------- | :------------------------------ | :----- | ----------------------------------------- |
| `*` | [core.clj] | [core_test.clj] | `*` | |
| [Quickstart] | [quickstart.clj] | [quickstart_test.clj] | `GET` | [/quickstart] |
| [Getting Started] | [getting_started.clj] | [getting_started_test.clj] | `GET` | [/getting-started/resource] |
| `^` | `^` | `^` | `GET` | [/getting-started/foo-1] |
| `^` | `^` | `^` | `GET` | [/getting-started/foo-2] |
| `^` | `^` | `^` | `GET` | [/getting-started/counter-1] |
| `^` | `^` | `^` | `GET` | [/getting-started/counter-2] |
| `^` | `^` | `^` | `GET` | [/getting-started/example] |
| `^` | `^` | `^` | `GET` | [/getting-started/bar/hello] |
| `^` | `^` | `^` | `PUT` | [/getting-started/bar/hello] |
| [Decision Graph] | [decision_graph.clj] | [decision_graph_test.clj] | `GET` | [/decision-graph/secret?word=tiger] |
| `^` | `^` | `^` | `GET` | [/decision-graph/secret?word=wrong-tiger] |
| `^` | `^` | `^` | `GET` | [/decision-graph/choice?choice=1] |
| `^` | `^` | `^` | `GET` | [/decision-graph/choice?choice=4] |
| [Debugging] | [debugging.clj] | [debugging_test.clj] | `GET` | [/debugging/dbg-counter] |
| `^` | `^` | `^` | `POST` | [/debugging/dbg-counter] |
| [Content Negotiation] | [content_negotiation.clj] | [content_negotiation_test.clj] | `GET` | [/content-negotiation/babel] |
| [Conditional Requests] | [conditional_requests.clj] | [conditional_requests_test.clj] | `GET` | [/conditional-requests/timehop] |
| `^` | `^` | `^` | `GET` | [/conditional-requests/changetag] |
| [Handling POST] | [handling_post.clj] | [handling_post_test.clj] | `POST` | [/handling-post/postbox] |
| `^` | `^` | `^` | `GET` | [/handling-post/postbox/1] |
| `^` | `^` | `^` | `PATCH` | [/handling-post/patchbox] |
| [Putting it all together] | [all_together.clj] | [all_together_test.clj] | `GET` | [/all-together/collection] |
| `^` | `^` | `^` | `GET` | [/all-together/collection/1] |
-------------------------------------------------------------------------------
Template
--------
The project template was generated with:
``` bash
$ lein new midje limi --to-dir . --force
```
-------------------------------------------------------------------------------
License
-------
`limi` is licensed under [MIT].
[Liberator]: https://clojure-liberator.github.io
[Midje]: https://github.com/marick/Midje
[Install and setup clj/cljs development environment]: https://ejelome.com/install-and-setup-clj-cljs-development-environment
[core.clj]: ./src/limi/core.clj
[core_test.clj]: ./test/limi/core_test.clj
[Quickstart]: https://clojure-liberator.github.io/liberator/#quickstart
[quickstart.clj]: ./src/limi/quickstart.clj
[quickstart_test.clj]: ./test/limi/quickstart_test.clj
[/quickstart]: http://localhost:3000/quickstart
[Getting Started]: https://clojure-liberator.github.io/liberator/tutorial/getting-started.html
[getting_started.clj]: ./src/limi/getting_started.clj
[getting_started_test.clj]: ./test/limi/getting_started_test.clj
[/getting-started/resource]: http://localhost:3000/getting-started/resource
[/getting-started/foo-1]: http://localhost:3000/getting-started/foo-1
[/getting-started/foo-2]: http://localhost:3000/getting-started/foo-2
[/getting-started/counter-1]: http://localhost:3000/getting-started/counter-1
[/getting-started/counter-2]: http://localhost:3000/getting-started/counter-2
[/getting-started/example]: http://localhost:3000/getting-started/example
[/getting-started/bar/hello]: http://localhost:3000/getting-started/bar/hello
[/getting-started/bar/hello]: http://localhost:3000/getting-started/bar/hello
[Decision Graph]: https://clojure-liberator.github.io/liberator/tutorial/decision-graph.html
[decision_graph.clj]: ./src/limi/decision_graph.clj
[decision_graph_test.clj]: ./test/limi/decision_graph_test.clj
[/decision-graph/secret?word=tiger]: http://localhost:3000/decision-graph/secret?word=tiger
[/decision-graph/secret?word=wrong-tiger]: http://localhost:3000/decision-graph/secret?word=wrong-tiger
[/decision-graph/choice?choice=1]: http://localhost:3000/decision-graph/choice?choice=1
[/decision-graph/choice?choice=4]: http://localhost:3000/decision-graph/choice?choice=4
[Debugging]: https://clojure-liberator.github.io/liberator/tutorial/debugging.html
[debugging.clj]: ./src/limi/debugging.clj
[debugging_test.clj]: ./test/limi/debugging_test.clj
[/debugging/dbg-counter]: http://localhost:3000/debugging/dbg-count
[Content Negotiation]: https://clojure-liberator.github.io/liberator/tutorial/conneg.html
[content_negotiation.clj]: ./src/limi/content_negotiation.clj
[content_negotiation_test.clj]: ./test/limi/content_negotiation_test.clj
[/content-negotiation/babel]: http://localhost:3000/content-negotiation/babel
[Conditional Requests]: https://clojure-liberator.github.io/liberator/tutorial/conditional.html
[conditional_requests.clj]: ./src/limi/conditional_requests.clj
[conditional_requests_test.clj]: ./test/limi/conditional_requests_test.clj
[/conditional-requests/timehop]: http://localhost:3000/conditional-requests/timehop
[/conditional-requests/changetag]: http://localhost:3000/conditional-requests/changetag
[Handling POST]: https://clojure-liberator.github.io/liberator/tutorial/post-et-al.html
[handling_post.clj]: ./src/limi/handling_post.clj
[handling_post_test.clj]: ./test/limi/handling_post_test.clj
[/handling-post/postbox]: http://localhost:3000/handling-post/postbox
[/handling-post/postbox/1]: http://localhost:3000/handling-post/postbox/1
[/handling-post/patchbox]: http://localhost:3000/handling-post/patchbox
[Putting it all together]: https://clojure-liberator.github.io/liberator/tutorial/all-together.html
[all_together.clj]: ./src/limi/all_together.clj
[all_together_test.clj]: ./test/limi/all_together_test.clj
[/all-together/collection]: http://localhost:3000/all-together/collection
[/all-together/collection/1]: http://localhost:3000/all-together/collection/1
[MIT]: ./LICENSE.md
<file_sep>/py/resume/requirements.txt
appdirs==1.4.3
Beaker==1.6.4
bottle==0.11.6
Mako==0.9.1
Markdown==2.3.1
MarkupSafe==1.0
packaging==16.8
Pillow==2.3.0
py-bcrypt==0.4
pyparsing==2.2.0
six==1.10.0
slugify==0.0.1
<file_sep>/py/wooji/views/test/helpers.html
<%!
import re
import markdown2
%>
<%def name="markdown(content)">
<%
pattern = r'<!--\s*markdown-extras\s*:\s*(.+?)\s*-->'
match = re.search(pattern, content)
extras = []
if match:
content = content.replace(match.group(), '')
string, = match.groups()
extras = [extra.strip() for extra in string.split(',')]
return markdown2.markdown(content, extras=extras)
%>
</%def>
<%def name="custom_markdown(content)">
<%
pattern = r'\|(.+?)\|'
content = re.sub(pattern, r'<\1>', content)
return content
%>
</%def>
<%def name="repair_nesting(content)">
<%
fixes = [
(r'(<p>)<div(.*)>', r'<div\2>'),
('(</div>)(</p>)', '</div>')
]
for fix in fixes:
old, new = fix
content = re.sub(old, new, content)
return content
%>
</%def>
<file_sep>/py/resume/README.md
resume
======
A simple web application powered by `Bottle`
-------------------------------------------------------------------------------
Introduction
------------
The resume web application aims to demonstrate how a simple web app is built using Python via the HTTP framework `Bottle`.
It's focuses on the "learning" and avoids any of the highly abstracted tools (e.g. ORM, CSS frameworks, JS Libraries, etc.) to better understand Python and HTTP (via `Bottle`) when doing web development.
It is licensed under [MIT] which means you are free to do "everything" to it.
-------------------------------------------------------------------------------
Notable tools used
------------------
* `Mako` as the templating engine
* `SQLite3` as the database engine
* `Bottle` as the HTTP framework (WSGI-compliant)
* `HTML5` as the doctype (don't worry, no HTML5 tags, just the doctype)
* `Markdown` as the Plain Text to HTML converter
Notable packages
----------------
* `Cookie` for handling cookies
* `Beaker` for handling sessions
* `bcrypt` for handling encryption
* `Pillow` for handling images (this is still `PIL`)
* `slugify` for handling file names (can also be used for seo-friendly urls)
* `email` for handling e-mail to be sent
* `smtplib` for sending e-mail
* `logging` for debugging
* `json.dumps` and `pprint.pprint` for more readable printing
-------------------------------------------------------------------------------
Prerequisites
-------------
### for System: ###
* `python-setuptools`
* `pip`
* `virtualenv`
* for `Pillow` (an updated fork of `PIL`, Python package):
* `libjpeg8`
* `libjpeg62-dev`
* `libfreetype6`
* `libfreetype6-dev`
* for `bcrypt` (another Python package):
* `python-dev`
* `libffi-dev`
### for Bottle: ###
* `Beaker`
* `Mako`
* `Markdown`
* `Pillow`
* `bcrypt`
* `slugify`
### for 3rd party: ###
* Mailbox to handle the change e-mail functionality (via `SMTP`)
-------------------------------------------------------------------------------
Install prerequisites
---------------------
``` bash
# System packages:
$ sudo apt-get install python-setuptools \
libjpeg8 libjpeg62-dev libfreetype6 libfreetype6-dev python-dev libffi-dev
# pip:
$ sudo easy_install pip
# virtualenv:
$ sudo pip install virtualenv
```
-------------------------------------------------------------------------------
Setup project
-------------
``` bash
# Clone repository:
$ git clone https://github.com/ejelome/resume
# Go to directory:
$ cd resume/
# Create a virtualenv:
$ virtualenv -p /usr/bin/python2 venv
# Activate virtualenv:
$ source venv/bin/activate
# Install packages:
$ pip install -r requirements.txt
```
-------------------------------------------------------------------------------
Run project
-----------
``` bash
$ python server.py
```
Then visit <http://localhost:8080>.
Register to use the app and enjoy! ^^,
-------------------------------------------------------------------------------
Configure Mailbox
-----------------
To be able to use the change e-mail functionality, a mailbox is needed.
Depending on the host provider you've registered into, you'll simply be needing 3 things:
* *URI* of the SMTP connection
* *E-mail* of the mailbox
* *Username* of the mailbox
* *Password* of the mailbox
Once you have done setting up your mailbox, open the `config.py` file and provide the details on the following variables:
``` text
# Mailbox:
SMTP_SERVER # e.g. 'smtp.webfaction.com'
SMTP_EMAIL # e.g. '<EMAIL>'
SMTP_USERNAME # e.g. 'foobar'
SMTP_PASSWORD # e.g. '<PASSWORD>'
```
-------------------------------------------------------------------------------
Notes
-----
* A big thanks to [Free Favicons] for the free [snake favicon]
* If you've decided to host in WebFaction, then I'd be grateful if you [register as my referral] :)
* There are a lot to be improved in this program since only the vital ones were done
* Challenge yourself and see if you can add the following functionalities:
* **Forgot Password** (along with the necessary templates)
* **TODO**s included in the `/templates` directory
* Coding convention is based on PEP 8
* Happy learning and coding! ^^,
License
-------
`resume` is licensed under [MIT].
[Free Favicons]: http://freefavicons.org
[snake favicon]: http://freefavicons.org/download/snake
[register as my referral]: http://www.webfaction.com/signup?affiliate=ejelome
[MIT]: ./LICENSE.md
-------------------------------------------------------------------------------
`Created: 2013 Nov`
<file_sep>/py/resume/server.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""server.py: Main executable file."""
import Cookie
import re
import subprocess
import uuid
import bottle as app
import bcrypt
from beaker.middleware import SessionMiddleware
from mako.template import Template
from mako.lookup import TemplateLookup
import config
import models
from modules import function
from modules.form import Form
from modules.thumbnail import Thumbnail
from modules.upload import Upload
from modules.logger import Logger
# Global variables (for all the templates):
meta = dict(
site_name=config.SITE_NAME,
site_uri=config.SITE_URI,
site_tagline=config.SITE_TAGLINE,
license_url=config.LICENSE_URL,
favicon=config.FAVICON,
css=config.CSS,
js=config.JS
)
# Global variables (for all the routes):
form = Form()
log = Logger().log()
templates = TemplateLookup(directories=[config.PAGES])
session = SessionMiddleware(app.app(), {
'session.data_dir': config.SESSION,
'session.type': config.SESSION_TYPE,
'session.auto': config.SESSION_AUTO
})
cookie = Cookie.SimpleCookie()
cookie['id'], cookie['token'], auth_id = '', '', ''
# Global functions (for all the routes)
def authenticate(func):
"""TODO: Function docstring."""
def logged_in(*args, **kwargs):
if 'id' in cookie and 'token' in cookie:
cookie_id = cookie['id'].value
cookie_token = cookie['token'].value
if all(cookie.values()):
results = models.db.read('Tokens', ['*'], [
('key', '=', cookie_id),
('value', '=', cookie_token)
])
if results:
app.request.session['auth_id'] = results[0]['user_id']
return func(*args, **kwargs)
if 'auth_id' in app.request.session and app.request.session['auth_id']:
return func(*args, **kwargs)
app.redirect('/login')
return logged_in
@app.hook('before_request')
def global_session():
results = models.db.read('Users', ['id'])
if not results and '.' not in app.request.fullpath:
if not '/setup' in app.request.fullpath:
app.redirect('/setup')
app.request.session = app.request.environ.get('beaker.session')
@app.route('/setup', method=['GET', 'POST'])
def setup():
results = models.db.read('Users', ['*'])
if results:
app.redirect('/')
tpl = '{base}/core/setup.html'.format(base=config.PAGES)
meta = globals()['meta']
field = dict(
email=form.field('email'),
password=form.field('<PASSWORD>'),
confirm_password=form.field('<PASSWORD>_<PASSWORD>')
)
submit = dict(register=form.field('register'))
result = dict(successes=[], errors=[])
db_update = {}
# Default values:
meta['path'] = app.request.fullpath
meta['slug'] = meta['path'].split('/')[-1]
meta['slugs'] = [path for path in meta['path'].split('/') if path]
meta['title'] = meta['slug'].title()
meta['document_title'] = '{title} - {site_name}'.format(
site_name=meta['site_name'],
title=meta['title']
)
meta['description'] = '{title} information'.format(
title=meta['title']
)
if submit['register']:
field['email'] = field['email'].lower()
if not all(field.values()):
result['errors'].append('All fields are required')
if not re.search(r'^(\w+(-|.)\w+)@(\w+(-|.)\w+)(\.\w+){1,2}$',
field['email'], re.IGNORECASE):
result['errors'].append('Invalid e-mail format')
else:
db_update['email'] = field['email']
if field['password']:
if not len(field['password']) >= 6:
result['errors'].append('Password is too short: must be '
'atleast 6 characters')
if not field['confirm_password']:
result['errors'].append('Confirm password is required')
elif field['password'] != field['confirm_password']:
result['errors'].append('Passwords didn\'t match')
elif field['confirm_password'] and not field['password']:
result['errors'].append('Password is required')
if not result['errors']:
if field['password'] and field['confirm_password']:
db_update['password'] = bcrypt.hashpw(field['password'],
bcrypt.gensalt())
if not result['errors'] and db_update:
db_update.update(
token=uuid.uuid4().hex,
verified=True
)
models.db.insert('Users', db_update)
results = models.db.read('Users', ['id'], [
('email', '=', field['email'])
])
if results:
user_id = dict(user_id=results[0]['id'])
tables = [
'Profiles',
'Addresses',
'Educations',
'Experiences',
'Skills',
'Affiliations',
'Publications'
]
for table in tables:
models.db.insert(table, user_id)
result['successes'].append('Registration successful')
# Filter non-dict values:
dict_locals = function.filter_non_dict_values(locals())
dict_locals['session'] = dict(auth_id=auth_id)
dict_locals['cookie'] = cookie
log.info(function.console_log('dict_locals', dict_locals))
return Template(filename=tpl, lookup=templates).render(**dict_locals)
@app.route('/')
def index():
id_ = models.db.read('Users', ['id'])[0]['id']
tpl = '{base}/index.html'.format(base=config.PAGES)
meta = globals()['meta']
user_info = models.db.read_all(
'Users',
[
'Profiles',
'Addresses'
],
dict(pk='id', pk_value=id_, fk='user_id')
)[0]
result = dict(successes=[], errors=[])
misc = {}
for table in ['Educations', 'Experiences', 'Skills', 'Affiliations',
'Publications']:
user_info[table.lower()] = models.db.read(table, ['*'], [
('user_id', '=', id_)
])
# Default values:
meta['path'] = app.request.fullpath
meta['slug'] = 'home'
meta['slugs'] = ['home']
meta['title'] = meta['site_name']
meta['document_title'] = '{site_name} - {site_tagline}'.format(
site_name=meta['site_name'],
site_tagline=meta['site_tagline']
)
meta['description'] = config.SITE_DESCRIPTION
user_info['photo'] = user_info['photo'] or config.PHOTO
user_info['nickname'] = user_info['nickname'] \
or user_info['email'].split('@')[0].title()
misc['photo_info'] = function.image_info(user_info['photo'])
misc['photo_info']['alt'] = 'Photo of {nickname}'.format(
nickname=user_info['nickname']
)
# Filter non-dict values:
dict_locals = function.filter_non_dict_values(locals())
dict_locals['session'] = app.request.session
dict_locals['cookie'] = cookie
log.info(function.console_log('dict_locals', dict_locals))
return Template(filename=tpl, lookup=templates).render(**dict_locals)
@app.route('/login', method=['GET', 'POST'])
def login():
if 'auth_id' in app.request.session and app.request.session['auth_id']:
app.redirect('/resume')
tpl = '{base}/core/login.html'.format(base=config.PAGES)
meta = globals()['meta']
field = dict(
email=form.field('email'),
password=form.field('<PASSWORD>'),
keep_me_logged=form.field('keep_logged_in')
)
submit = dict(login=form.field('login'))
result = dict(successes=[], errors=[])
db_update = {}
misc = {}
# Default values:
meta['path'] = app.request.fullpath
meta['slug'] = meta['path'].split('/')[-1]
meta['slugs'] = [path for path in meta['path'].split('/') if path]
meta['title'] = meta['slug'].title()
meta['document_title'] = '{title} - {site_name}'.format(
site_name=meta['site_name'],
title=meta['title']
)
meta['description'] = 'Log in to use access the {site_name}'.format(
title=meta['title'].lower(),
site_name=meta['site_name']
)
if submit['login']:
field['email'] = field['email'].lower()
if not (field['email'] or field['password']):
result['errors'].append('E-mail and Password are required')
else:
results = models.db.read('Users', ['id', 'email', 'password'], [
('email', '=', field['email'])
])
password = <PASSWORD>
if results:
user_id = results[0]['id']
password = str(results[0]['password'])
if not results or bcrypt.hashpw(field['password'],
password) != password:
result['errors'].append('Invalid E-mail and/or Password')
else:
# Session:
app.request.session['auth_id'] = user_id
if field['keep_me_logged']:
# Cookie:
cookie['id'] = uuid.uuid4().hex
cookie['token'] = bcrypt.hashpw(
'{id}{email}{cookie_id}'.format(
id=user_id,
email=field['email'],
cookie_id=cookie['id']
), bcrypt.gensalt()
)
auth_id = user_id
# Add cookie morsel objects:
for key in ['id', 'token']:
cookie[key]['max-age'] = config.COOKIE_MAX_AGE
cookie[key].update(
dict(
path=config.COOKIE,
domain=meta['site_uri'],
expires=config.COOKIE_EXPIRES,
httponly=config.COOKIE_HTTP_ONLY,
comment=config.COOKIE_COMMENT,
secure=config.COOKIE_SECURE,
version=config.COOKIE_VERSION
)
)
db_update.update(
key=cookie['id'].value,
value=cookie['token'].value,
user_id=user_id
)
models.db.insert('Tokens', db_update)
app.redirect('/resume')
# Filter non-dict values:
dict_locals = function.filter_non_dict_values(locals())
dict_locals['session'] = app.request.session
dict_locals['cookie'] = cookie
log.info(function.console_log('dict_locals', dict_locals))
return Template(filename=tpl, lookup=templates).render(**dict_locals)
@app.route('/resume<:re:/?>')
def edit():
app.redirect('/resume/profile')
@app.route('/account<:re:(|/verify)/?>', method=['GET', 'POST'])
@authenticate
def account():
id_ = auth_id or app.request.session['auth_id']
tpl = '{base}/edit.html'.format(base=config.PAGES)
user = models.db.read('Users', ['email', 'token'], [('id', '=', id_)])[0]
meta = globals()['meta']
field = dict(
email=form.field('email'),
new_password=form.field('<PASSWORD>'),
confirm_password=form.field('<PASSWORD>')
)
param = dict(
token=form.param('token'),
old_email=form.param('old_email'),
new_email=form.param('new_email')
)
submit = dict(update=form.field('update'))
result = dict(successes=[], errors=[])
db_update = {}
misc = {}
# Default values:
meta['path'] = app.request.fullpath
meta['slug'] = meta['path'].split('/')[-1]
meta['slugs'] = [path for path in meta['path'].split('/') if path]
meta['title'] = meta['slug'].title()
meta['document_title'] = '{title} - {site_name}'.format(
site_name=meta['site_name'],
title=meta['title']
)
meta['description'] = 'Edit {title} information'.format(
title=meta['title'].lower()
)
field['email'] = field['email'].lower() or user['email']
misc['tpl'] ='/edit/account.html'
if submit['update']:
if not re.search(r'^(\w+(-|.)\w+)@(\w+(-|.)\w+)(\.\w+){1,2}$',
field['email'], re.IGNORECASE):
result['errors'].append('Invalid e-mail format')
if field['new_password']:
if not len(field['new_password']) >= 6:
result['errors'].append('New Password is too short: must be '
'atleast 6 characters')
if not field['confirm_password']:
result['errors'].append('Confirm password is required')
elif field['new_password'] != field['confirm_password']:
result['errors'].append('Passwords didn\'t match')
elif field['confirm_password'] and not field['new_password']:
result['errors'].append('New Password is required')
if not result['errors']:
if field['new_password'] and field['confirm_password']:
db_update['password'] = <PASSWORD>(field['new_password'],
<PASSWORD>.gensalt())
field['new_password'] = ''
field['confirm_password'] = ''
result['successes'].append('Password change successful')
results = models.db.read('Users', ['id'], [
('email', '=', field['email'])
])
if results:
if id_ != results[0]['id']:
result['errors'].append(
'{email} is already used'.format(email=field['email'])
)
else:
# Create a verification url:
misc['token'] = user['token']
misc['old_email'] = user['email']
misc['new_email'] = field['email']
misc['verify_url'] = (
'{base}/account/verify?old_email={old_email}&'
'new_email={new_email}&token={token}'.format(
base=meta['site_uri'],
old_email=misc['old_email'],
new_email=misc['new_email'],
token=misc['token']
)
)
# Send an e-mail verification:
misc['sender'] = dict(
name=meta['site_name'],
email=config.SMTP_EMAIL
)
misc['recipients'] = [
dict(
name=field['email'],
email=field['email']
)
]
misc['subject'] = 'Change E-mail Verification'
file_ = open('{base}/change_email.txt'.format(
base=config.EMAILS), 'rb'
)
misc['message'] = file_.read().format(
email=field['email'],
verify_url=misc['verify_url'],
site_name=meta['site_name']
)
file_.close()
send_mail = function.send_mail(
misc['sender'],
misc['recipients'],
misc['subject'],
misc['message']
)
if (send_mail):
result['successes'].append(
'A verification url has been sent to '
'{email}'.format(email=field['email'])
)
else:
log.warning('Failed to send verification url to '
'{email}. Please check the SMTP settings in '
'config.py file'.format(email=field['email']))
if not submit['update'] and '/verify' in app.request.fullpath:
meta['title'] = app.request.fullpath.strip('/').split('/')[0].title()
results = models.db.read('Users', ['id'], [
('email', '=', param['old_email']),
('token', '=', param['token'])
])
if not results:
result['errors'].append('Invalid e-mail verification')
else:
existing_users = models.db.read('Users', ['id'], [
('email', '=', param['new_email'])
])
if existing_users:
result['errors'].append('E-mail is already in use')
else:
db_update.update(
email=param['new_email'],
token=uuid.uuid4().hex
)
result['successes'].append('Change e-mail successful')
if not result['errors'] and db_update:
models.db.update('Users', db_update, [('id', '=', id_)])
# Filter non-dict values:
dict_locals = function.filter_non_dict_values(locals())
dict_locals['session'] = app.request.session
dict_locals['cookie'] = cookie
log.info(function.console_log('dict_locals', dict_locals))
return Template(filename=tpl, lookup=templates).render(**dict_locals)
@app.route('/resume/profile<:re:/?>', method=['GET', 'POST'])
@authenticate
def profile():
id_ = auth_id or app.request.session['auth_id']
tpl = '{base}/edit.html'.format(base=config.PAGES)
user = models.db.read('Users', ['*'], [('id', '=', id_)])[0]
profile = models.db.read('Profiles', ['*'], [('user_id', '=', id_)])[0]
meta = globals()['meta']
file_ = dict(photo=form.file('photo'))
field = function.set_field(profile, ['id', 'photo', 'user_id'])
submit = dict(upload=form.field('upload'), update=form.field('update'))
result = dict(successes=[], errors=[])
db_update = {}
fieldset = {}
misc = {}
# Default values:
meta['path'] = app.request.fullpath
meta['slug'] = meta['path'].split('/')[-1]
meta['slugs'] = [path for path in meta['path'].split('/') if path]
meta['title'] = meta['slug'].title()
meta['document_title'] = '{title} - {site_name}'.format(
site_name=meta['site_name'],
title=meta['title']
)
meta['description'] = 'Edit {title} information'.format(
title=meta['title'].lower()
)
field['alt_email'] = field['alt_email'] or user['email']
field['nickname'] = field['nickname'] \
or user['email'].split('@')[0].title()
profile['photo'] = profile['photo'] or config.PHOTO
misc['tpl'] = '/edit/{slug}.html'.format(slug=meta['slug'])
misc['photo_info'] = function.image_info(profile['photo'])
misc['photo_info']['alt'] = 'Photo of {nickname}'.format(
nickname=field['nickname']
)
if submit['upload'] and not file_['photo']:
result['errors'].append('There was no image to upload')
if any(submit.values()) and file_['photo']:
upload_file = Upload()
if (upload_file.image(file_['photo'])):
thumbnail = Thumbnail()
if (thumbnail.create(upload_file.info['path'])):
misc['photo_info'].update(thumbnail.info)
db_update['photo'] = misc['photo_info']['path']
else:
result['errors'].extend(thumbnail.errors)
else:
result['errors'].extend(upload_file.errors)
if submit['update']:
if field['alt_email'] \
and not re.search(r'^(\w+(-|.)\w+)@(\w+(-|.)\w+)(\.\w+){1,2}$',
field['alt_email'], re.IGNORECASE):
result['errors'].append('Invalid e-mail format')
if field['uri'] \
and not re.search(r'^(http[s]?://)?(www\.)?(\w+(-|.)?\w+)'
'(\.\w+){1,2}\/?$', field['uri'], re.IGNORECASE):
result['errors'].append('Invalid URI format')
if any(submit.values()):
field['alt_email'] = field['alt_email'].lower()
field['uri'] = field['uri'].lower()
db_update.update(field)
if not result['errors'] and db_update:
models.db.update('Profiles', db_update, [('user_id', '=', id_)])
result['successes'].append('{title} successfully updated'.format(
title=meta['title'])
)
# Update field with ordered key-value pairs:
fieldset.update(
function.set_fieldset(field, [
'alt_email',
'given_name',
'additional_name',
'family_name',
'nickname',
'uri',
'tel',
'summary'
])
)
# Filter non-dict values:
dict_locals = function.filter_non_dict_values(locals())
dict_locals['session'] = app.request.session
dict_locals['cookie'] = cookie
# Remove the following dict since it might contain heavy object upon upload
del dict_locals['file_']
log.info(function.console_log('dict_locals', dict_locals))
return Template(filename=tpl, lookup=templates).render(**dict_locals)
@app.route('/resume/address<:re:/?>', method=['GET', 'POST'])
@authenticate
def address():
id_ = auth_id or app.request.session['auth_id']
tpl = '{base}/edit.html'.format(base=config.PAGES)
address = models.db.read('Addresses', ['*'], [('id', '=', id_)])[0]
meta = globals()['meta']
field = function.set_field(address)
submit = dict(update=form.field('update'))
result = dict(successes=[], errors=[])
db_update = {}
fieldset = {}
misc = {}
# Default values:
meta['path'] = app.request.fullpath
meta['slug'] = meta['path'].split('/')[-1]
meta['slugs'] = [path for path in meta['path'].split('/') if path]
meta['title'] = meta['slug'].title()
meta['document_title'] = '{title} - {site_name}'.format(
site_name=meta['site_name'],
title=meta['title']
)
meta['description'] = 'Edit {title} information'.format(
title=meta['title'].lower()
)
misc['tpl'] = '/edit/{slug}.html'.format(slug=meta['slug'])
if submit['update']:
db_update.update(field)
if not result['errors'] and db_update:
models.db.update('Addresses', db_update, [('user_id', '=', id_)])
result['successes'].append('{title} successfully updated'.format(
title=meta['title'])
)
# Update field with ordered key-value pairs:
fieldset.update(
function.set_fieldset(field, [
'street',
'locality',
'region',
'postal_code',
'country'
])
)
# Filter non-dict values:
dict_locals = function.filter_non_dict_values(locals())
dict_locals['session'] = app.request.session
dict_locals['cookie'] = cookie
log.info(function.console_log('dict_locals', dict_locals))
return Template(filename=tpl, lookup=templates).render(**dict_locals)
@app.route('/resume/<path:re:(education|experience)><:re:/?>',
method=['GET', 'POST'])
@authenticate
def education_experience(path):
id_ = auth_id or app.request.session['auth_id']
tpl = '{base}/edit.html'.format(base=config.PAGES)
table = '{path}s'.format(path=path.title())
table_rows = models.db.read(table, ['*'], [('user_id', '=', id_)])
meta = globals()['meta']
submit = dict(
add=form.field('add'),
remove=form.field('remove'),
update=form.field('update')
)
result = dict(successes=[], errors=[])
db_update = {}
fieldsets = []
misc = {}
form_id = form.field('id')
# Default values:
meta['path'] = app.request.fullpath
meta['slug'] = meta['path'].split('/')[-1]
meta['slugs'] = [path for path in meta['path'].split('/') if path]
meta['title'] = meta['slug'].title()
meta['document_title'] = '{title} - {site_name}'.format(
site_name=meta['site_name'],
title=meta['title']
)
meta['description'] = 'Edit {title} information'.format(
title=meta['title'].lower()
)
misc['tpl'] = '/edit/generic_education_experience.html'
if submit['add']:
db_update.update(user_id=id_)
models.db.insert(table, db_update)
result['successes'].append('New form successfully added')
elif submit['remove']:
if len(table_rows) == 1:
result['errors'].append('Cannot remove last available form')
else:
models.db.remove(table, [
('id', '=', form_id),
('user_id', '=', id_)
])
result['successes'].append('Form successfully removed')
elif submit['update']:
table_rows = models.db.read(table, ['*'], [
('id', '=', form_id),
('user_id', '=', id_)
])
if table_rows:
pattern = r'\d{4}-\d{2}-\d{2}'
for key in ['start', 'end']:
field = str(form.field(key))
if key == 'end':
pattern = r'({pattern}|present)'.format(pattern=pattern)
if field and not re.search(pattern, field, re.IGNORECASE):
error_message = 'Invalid {title} date: should be YYYY-MM-DD'
if key == 'end':
error_message += ' or present'
result['errors'].append(
error_message.format(title=key.title())
)
if form.field('uri') \
and not re.search(r'^(http[s]?://)?(www\.)?(\w+(-|.)?\w+)'
'(\.\w+){1,2}\/?$', form.field('uri'),
re.IGNORECASE):
result['errors'].append('Invalid URI format')
if not result['errors']:
field = function.set_field(table_rows[0])
field['uri'] = field['uri'].lower()
db_update.update(field)
models.db.update(table, db_update, [
('id', '=', form_id),
('user_id', '=', id_)
])
result['successes'].append(
'{title} successfully updated'.format(title=meta['title'])
)
# Update fields with ordered key-value pairs:
if path == 'education':
ordered_keys = [
'id',
'degree',
'major',
'school',
'uri',
'start',
'end'
]
elif path == 'experience':
ordered_keys = [
'id',
'position',
'description',
'company',
'uri',
'start',
'end'
]
for table_row in table_rows:
fieldsets.append(
function.set_fieldset(table_row, ordered_keys)
)
# Filter non-dict values:
dict_locals = function.filter_non_dict_values(locals())
dict_locals['fieldsets'] = fieldsets
dict_locals['session'] = app.request.session
dict_locals['cookie'] = cookie
log.info(function.console_log('dict_locals', dict_locals))
return Template(filename=tpl, lookup=templates).render(**dict_locals)
@app.route('/resume/<path:re:(skill|affiliation|publication)><:re:/?>',
method=['GET', 'POST'])
@authenticate
def skill_affiliation_publication(path):
id_ = auth_id or app.request.session['auth_id']
tpl = '{base}/edit.html'.format(base=config.PAGES)
table = '{path}s'.format(path=path.title())
table_rows = models.db.read(table, ['*'], [('user_id', '=', id_)])
meta = globals()['meta']
submit = dict(
add=form.field('add'),
remove=form.field('remove'),
update=form.field('update')
)
result = dict(successes=[], errors=[])
db_update = {}
fieldsets = []
misc = {}
form_id = form.field('id')
# Default values:
meta['path'] = app.request.fullpath
meta['slug'] = meta['path'].split('/')[-1]
meta['slugs'] = [path for path in meta['path'].split('/') if path]
meta['title'] = meta['slug'].title()
meta['document_title'] = '{title} - {site_name}'.format(
site_name=meta['site_name'],
title=meta['title']
)
meta['description'] = 'Edit {title} information'.format(
title=meta['title'].lower()
)
misc['tpl'] = '/edit/generic_skill_affiliation_publication.html'
if submit['add']:
db_update.update(user_id=id_)
models.db.insert(table, db_update)
result['successes'].append('New form successfully added')
elif submit['remove']:
if len(table_rows) == 1:
result['errors'].append('Cannot remove last available form')
else:
models.db.remove(table, [
('id', '=', form_id),
('user_id', '=', id_)
])
result['successes'].append('Form successfully removed')
elif submit['update']:
table_rows = models.db.read(table, ['*'], [
('id', '=', form_id),
('user_id', '=', id_)
])
if table_rows:
field = function.set_field(table_rows[0])
if 'slug' in field.keys():
field['name'] = field['name'].lower()
field['slug'] = field['name']
for key in ['uri', 'url']:
if key in field.keys():
field[key] = field[key].lower()
if field[key] \
and not re.search(r'^(http[s]?://)?(www\.)?(\w+(-|.)?\w+)'
'(\.\w+){1,2}(\/\w+(-|_)?\w+)*\/?$',
field[key], re.IGNORECASE):
result['errors'].append('Invalid URL format')
if not result['errors']:
db_update.update(field)
models.db.update(table, db_update, [
('id', '=', form_id),
('user_id', '=', id_)
])
result['successes'].append(
'{title} successfully updated'.format(title=meta['title'])
)
# Update fields with ordered key-value pairs:
if path == 'skill':
ordered_keys = [
'id',
'name',
'url'
]
elif path == 'affiliation':
ordered_keys = [
'id',
'name',
'uri'
]
elif path == 'publication':
ordered_keys = [
'id',
'title',
'uri'
]
for table_row in table_rows:
fieldsets.append(
function.set_fieldset(table_row, ordered_keys)
)
# Filter non-dict values:
dict_locals = function.filter_non_dict_values(locals())
dict_locals['fieldsets'] = fieldsets
dict_locals['session'] = app.request.session
dict_locals['cookie'] = cookie
log.info(function.console_log('dict_locals', dict_locals))
return Template(filename=tpl, lookup=templates).render(**dict_locals)
@app.route('/logout<:re:/?>')
def logout():
if 'auth_id' in app.request.session and app.request.session['auth_id']:
app.request.session['auth_id'] = ''
for key in ['id', 'token']:
if key in cookie:
cookie[key] = ''
app.redirect('/')
@app.error(404)
@app.error(500)
def page_not_found(error):
tpl = '{base}/404.html'.format(base=config.PAGES)
meta = globals()['meta']
result = dict(successes=[], errors=[])
# Default values:
meta['path'] = app.request.fullpath
meta['slug'] = '404'
meta['slugs'] = [
path for path in meta['path'].split('/') if path
]
meta['slugs'].insert(0, meta['slug'])
meta['title'] = 'Page not found'
meta['document_title'] = '{title} - {site_name}'.format(
site_name=meta['site_name'],
title=meta['title']
)
meta['description'] = 'The page does not exist'
# Filter non-dict values:
dict_locals = function.filter_non_dict_values(locals())
dict_locals['session'] = {}
log.info(function.console_log('dict_locals', dict_locals))
return Template(filename=tpl, lookup=templates).render(**dict_locals)
@app.route('/<path:re:((img|css|js)/?|)><file_>')
def static_file(path, file_):
if '.' not in file_:
app.abort(404)
return app.static_file(
file_,
root='{base}/{path}'.format(base=config.ASSETS, path=path)
)
if __name__ == '__main__':
try:
# The pyclean command doesn't seem to work on others Linux distros
# (e.g. CentOS)
subprocess.call(['pyclean', '.']) # remove all .pyc and .pyo files
except:
pass
app.run(
server=config.SERVER,
host=config.HOST,
port=config.PORT,
debug=config.DEBUG,
app=session
)
<file_sep>/py/alchemified/app/app/securities/authorization.py
from pyramid.security import ALL_PERMISSIONS, Allow, Authenticated, Everyone
from app.models.user import UserModel
class RootFactory(object):
__acl__ = [
(Allow, 'group:admin', ALL_PERMISSIONS),
(Allow, 'group:editor', 'edit'),
(Allow, Authenticated, 'add'),
(Allow, Everyone, 'read'),
]
def __init__(self, request):
self.request = request
def group_finder(userid, request):
query = request.dbsession.query(UserModel)
user = query.filter_by(id=userid).first()
if user:
group = user.group
group_ = ['group:{}'.format(group)]
return group_
<file_sep>/py/wooji/wooji/session.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""session.py: Handle application's sessions."""
from beaker.middleware import SessionMiddleware
import app
import config
info = {
'session.data_dir': config.SESSION_PATH,
'session.auto': config.SESSION_AUTO,
'session.type': config.SESSION_TYPE
}
session = SessionMiddleware(app.app(), info)
@app.hook('before_request')
def global_session():
app.request.session \
= app.request.environ.get('beaker.session')
app.BaseTemplate.defaults['session'] = app.request.session
<file_sep>/sh/virtualenvwrapper-rm/.virtualenvwrapper-rm
#!/bin/bash
# Set default vars if virtualenvwrapper vars are empty:
[[ -z ${PROJECT_HOME} ]] && PROJECT_HOME=${HOME}/Devel
[[ -z ${WORKON_HOME} ]] && WORKON_HOME=${HOME}/.virtualenvs
[[ -z ${TRASH_PATH} ]] && TRASH_PATH=${HOME}/.local/share/Trash/files
# Create default directories if not existing:
[[ ! -d ${PROJECT_HOME} ]] && mkdir -p ${PROJECT_HOME}
[[ ! -d ${WORKON_HOME} ]] && mkdir -p ${WORKON_HOME}
[[ ! -d ${TRASH_PATH} ]] && mkdir -p ${TRASH_PATH}
# rmproject auto-complete:
_virtualenvwrapper_rm_completion() {
COMPREPLY=($(compgen -W "$(ls ${PROJECT_HOME})" -- ${COMP_WORDS[COMP_CWORD]}))
}
complete -o nospace -F _virtualenvwrapper_rm_completion rmproject
function rmproject() {
# Remove and move from an existing DEST_DIR.
#
# Usage:
# rmproject DEST_DIR
#
# Example:
# rmproject venv
#
# Options:
# -h, --help Show this help message.
DEST_DIR=${PROJECT_HOME}/${1}
DEST_VENV=${WORKON_HOME}/${1}
if [[ ${#} < 1 || ${1} =~ ^-h$|^--help$ ]]; then
if [[ ${1} =~ ^-h$|^--help$ ]]; then
echo -e 'Remove and move from an existing DEST_DIR.\n'
else
echo -e 'You must provide a DEST_DIR.\n'
fi
echo -e 'Usage:\n\trmproject DEST_DIR\n'
echo -e 'Example:\n\trmproject myawesomeproject\n'
echo -e 'Options:\n\t-h, --help\t\tShow this help message.'
elif [[ ${#} > 1 ]]; then
echo -e 'virtualenvwrapper-rm failed:\n\tThe DEST_DIR can only be a single argument.'
else
if [[ -d ${DEST_DIR} ]]; then
echo -e 'virtualenvwrapper-rm successful:'
echo -e "\tRemoving '${DEST_DIR}'"
echo -e "\nThe DEST_DIR '${1}' was successfully removed."
[[ -d ${DEST_DIR} ]] && mv ${DEST_DIR} -fv --backup=numbered -t ${TRASH_PATH}
else
echo -e "virtualenvwrapper-rm failed:\n\tThe DEST_DIR '${1}' does not exists."
fi
if [[ -d ${DEST_VENV} ]]; then
echo -e 'virtualenvwrapper-rm successful:'
echo -e "\tRemoving '${DEST_VENV}'"
echo -e "\nThe DEST_VENV '${1}' was successfully removed."
[[ -d ${DEST_VENV} ]] && mv ${DEST_VENV} -fv --backup=numbered -t ${TRASH_PATH}
[[ -n ${VIRTUAL_ENV} && ${VIRTUAL_ENV} == ${DEST_VENV} ]] && deactivate && cd ${PROJECT_HOME}
else
echo -e "virtualenvwrapper-rm failed:\n\tThe DEST_VENV '${1}' does not exists."
fi
fi
}
<file_sep>/sh/shell-site-generator/convrt
#!/bin/zsh
#
# Convert a markdown files to html files.
#
# Args:
# * None
#
# Usage:
# $ bash convrt
# Converted '/home/username/shell-site-generator/src/posts/index.md' > '/home/username/shell-site-generator/public/index.html'
#
# Note:
# Or make the script self-executable:
# $ chmod +x convrt
# $ ./convrt
# Converted '/home/username/shell-site-generator/src/posts/index.md' > '/home/username/shell-site-generator/public/index.html'
header=$(pwd)/src/templates/header.html
footer=$(pwd)/src/templates/footer.html
static=$(pwd)/src/static
posts=$(pwd)/src/posts
dest=$(pwd)/public
# Create destination directory:
mkdir -p ${dest}
# Generate html files from markdown files:
for i in ${posts}/*; do
input=${i}
if [[ ${input} == *.md ]]; then
name=$(basename ${input})
output=${dest}/${name%.*}.html
output_tmp=${output}.tmp
marked -i ${input} -o ${output_tmp} --header ${header} --footer ${footer}
cat ${header} ${output_tmp} ${footer} > ${output}
rm ${output_tmp}
echo "Converted '${input}' > '${output}'"
fi
done
# Copy static files to destination directory:
cp -r ${static}/* ${dest}
<file_sep>/py/resume/templates/pages/serp.html
## serp.html
## TODO: Put the search results in this page
<div class="serp">
## Search Engine Results Page (SERP):
## Returns the search results from the search form.
## NOTES:
## * In this website, this is not really useful, since we only show 1 page
## and the other pages requires us to be logged-in, this is here just to
## make us aware of its use.
## * At the following should be included on each return result (each row):
## - Title (emphasized and must be bigger than the rest of related texts)
## - Time (when was it created and updated)
## - Excerpt (A snippet from its content)
## - URL (The path of the page)
</div>
<file_sep>/py/ragnashop/server.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""server.py: TODO"""
import datetime
import math
import os
import bottle as app
import rauth
from beaker.middleware import SessionMiddleware
import config
import html
import models
oauth2 = rauth.OAuth2Service
facebook = oauth2(
client_id=config.FB_APP_ID,
client_secret=config.FB_APP_SECRET,
name='facebook',
authorize_url='https://graph.facebook.com/oauth/authorize',
access_token_url='https://graph.facebook.com/oauth/access_token',
base_url='https://graph.facebook.com/'
)
if config.DEBUG:
uri_pattern = '{uri}:{port}/success'
else:
uri_pattern = '{uri}/success'
redirect_uri = uri_pattern.format(uri=config.BASE_URI, port=config.PORT)
def authenticate(func):
def log_in(*args, **kwargs):
logged_in = app.request.session.get('logged_in')
user_id = app.request.session.get('user_id')
shop_id = app.request.session.get('shop_id')
if logged_in and user_id and shop_id:
return func(*args, **kwargs)
app.redirect('/login')
return log_in
def diff_date(time):
# Awesome snippet from this guy: http://goo.gl/LXQORG
now = datetime.datetime.now()
if type(time) is int:
diff = now - datetime.datetime.fromtimestamp(time)
elif isinstance(time, datetime.datetime):
diff = now - time
elif not time:
diff = now - now
second_diff = diff.seconds
day_diff = diff.days
if day_diff < 0:
return ''
if day_diff == 0:
if second_diff < 10:
return 'just now'
if second_diff < 60:
return str(second_diff) + ' seconds ago'
if second_diff < 120:
return 'a minute ago'
if second_diff < 3600:
return str( second_diff / 60 ) + ' minutes ago'
if second_diff < 7200:
return 'an hour ago'
if second_diff < 86400:
return str( second_diff / 3600 ) + ' hours ago'
if day_diff == 1:
return 'Yesterday'
if day_diff < 7:
return str(day_diff) + ' days ago'
if day_diff < 31:
return str(day_diff/7) + ' weeks ago'
if day_diff < 365:
return str(day_diff/30) + ' months ago'
return str(day_diff/365) + ' years ago'
def paginator(list_, per_page=10):
total_count = len(list_)
pages_count = int(math.ceil(total_count / float(per_page)))
start_count, end_count = 0, per_page
pages = [None] # 1st index is None since pagination always starts at 1 not 0
if per_page > total_count:
end_count = total_count
for i in range(1, pages_count + 1):
pages.append(list_[start_count:end_count])
if start_count <= total_count:
start_count += per_page
if end_count <= total_count:
end_count += per_page
return pages
def paginator_prev(list_, current_index):
try:
if current_index:
current = list_[current_index]
previous = list_[current_index-1] or False
return previous
except:
pass
return False
def paginator_next(list_, current_index):
try:
current = list_[current_index]
next_ = list_[current_index+1]
return next_
except:
return False
@app.hook('before_request')
def global_session():
app.request.session = app.request.environ.get('beaker.session')
reload(html)
@app.get('/<page_num:re:(page/\d+/?)?>')
def index(page_num):
if not page_num:
page_num = 1
else:
page_num = int(page_num.split('/')[1])
if int(page_num) <= 1:
app.redirect('/')
pagination_slug = ''
logged_in = app.request.session.get('logged_in')
user_slug = app.request.session.get('user_slug')
diff_date = globals()['diff_date']
list_types = config.LIST_TYPES
cdn = config.CDN
items = (
models.session.query(models.Item, models.Shop, models.User)
.join(models.Shop, models.Shop.id == models.Item.shop_id)
.join(models.User, models.User.id == models.Shop.user_id)
.order_by(models.Item.id.desc())
).all()
paginated_pages = paginator(items, 10)
paginated_indexes = range(0, len(paginated_pages))
paginated_prev = paginator_prev(paginated_indexes, page_num)
paginated_next = paginator_next(paginated_indexes, page_num)
return app.template('index', html=html, **locals())
@app.get('/login<:re:/?>')
def login():
app.redirect(
facebook.get_authorize_url(
**dict(
# scope='email,public_profile',
scope='public_profile',
response_type='code',
redirect_uri=redirect_uri
)
)
)
@app.get('/success<:re:/?>')
def login_success():
try:
code = app.request.params.get('code')
session = facebook.get_auth_session(
data=dict(
code=code,
redirect_uri=redirect_uri
)
)
session_json = session.get('me').json()
user_data = (
dict(
(k, unicode(v).encode('utf-8'))
for k, v in session_json.iteritems()
)
)
app.request.session['logged_in'] = True
app.request.session['user_data'] = user_data
except:
return 'An error have occured, please contact the Webmaster.'
user = (
models.session.query(models.User)
.filter_by(uid=user_data['id'])
.first()
)
if user:
app.request.session['user_id'] = user.id
app.request.session['user_slug'] = user.slug
shop = (
models.session.query(models.Shop)
.filter_by(user_id=user.id)
.first()
)
if shop:
app.request.session['shop_id'] = shop.id
item = (
models.session.query(models.Item)
.filter_by(shop_id=shop.id)
.first()
)
if not item:
new_item = models.Item(
icon_id=909,
name='Jellopy',
price='10z',
trade='Clover or ???',
amount=1,
list_type=0,
created=datetime.datetime.now(),
shop_id=shop.id
)
models.session.add(new_item)
else:
shop_name = '{name}\'s Shop'.format(name=user_data['name'])
server_name = 'My Ragnarok Online'
new_shop = models.Shop(
name=shop_name,
server=server_name,
ingame='',
email='',
mobile='',
user_id=user.id
)
models.session.add(new_shop)
else:
new_user = models.User(
uid=user_data['id'],
email='', # user_data['email'],
name=user_data['name'],
slug=user_data['id']
)
models.session.add(new_user)
models.session.commit()
app.redirect('/profile')
@app.route('/profile<:re:/?>', method=['POST', 'GET'])
@authenticate
def profile():
logged_in = app.request.session.get('logged_in')
user_slug = app.request.session.get('user_slug')
tab = app.request.query.get('tab')
valid_tabs = ['shop', 'items', 'settings']
list_types = config.LIST_TYPES
cdn = config.CDN
result = {'type': '', 'title': '', 'message': ''}
if not tab or tab not in valid_tabs:
app.redirect('/profile?tab=shop')
user_data = app.request.session.get('user_data')
user_id = app.request.session.get('user_id')
shop_id = app.request.session.get('shop_id')
update = app.request.forms.get('update')
# Tab: Shop
shop = models.session.query(models.Shop).filter_by(id=shop_id).first()
shop_name = app.request.forms.get('shop_name')
server = app.request.forms.get('server')
ingame = app.request.forms.get('ingame')
email = app.request.forms.get('email')
mobile = app.request.forms.get('mobile')
if shop:
shop_name = shop_name or shop.name
server = server or shop.server
ingame = ingame or shop.ingame
email = email or shop.email
mobile = mobile or shop.mobile
# Tab: Items -> New Item
new_item_list_type = app.request.forms.get('new_item_list_type')
new_item_icon_id = app.request.forms.get('new_item_icon_id') or ''
new_item_name = app.request.forms.get('new_item_name') or ''
new_item_price = app.request.forms.get('new_item_price') or ''
new_item_trade = app.request.forms.get('new_item_trade') or ''
new_item_amount = app.request.forms.get('new_item_amount') or 1
add = app.request.forms.get('add')
# Tab: Items -> Existing Items
select_all = app.request.query.get('select_all')
items_selected = app.request.forms.getall('item_selected')
item_list_types = app.request.forms.getall('item_list_type')
item_icon_ids = app.request.forms.getall('item_icon_id') or ''
item_ids = app.request.forms.getall('item_id') or ''
item_names = app.request.forms.getall('item_name') or ''
item_prices = app.request.forms.getall('item_price') or ''
item_trades = app.request.forms.getall('item_trade') or ''
item_amounts = app.request.forms.getall('item_amount') or ''
remove = app.request.forms.get('remove')
# Tab: Settings
user = models.session.query(models.User).filter_by(id=user_id).first()
slug = app.request.forms.get('slug')
name = app.request.forms.get('name')
if user:
name = name or user.name
slug = slug or user.slug
user_slug = slug
if update:
if tab == 'shop':
result.update(
type='success',
title='Congratulations!',
message='Shop successfully updated.'
)
shop.name = shop_name
shop.server = server
shop.ingame = ingame
shop.email = email
shop.mobile = mobile
elif tab == 'items':
for i, j in enumerate(item_ids):
item = models.session.query(models.Item).filter_by(id=j).first()
if not item_names[i]:
item_names[i] = item.name
elif int(item_list_types[i]) <= 1 and not item_prices[i]:
item_prices[i] = item.price
elif int(item_list_types[i]) == 2 and not item_trades[i]:
item_trades[i] = item.trade
elif not item_amounts[i]:
item_amounts[i] = item.amount
item.icon_id = item_icon_ids[i].strip()
item.name = item_names[i]
item.price = item_prices[i]
item.trade = item_trades[i]
item.amount = item_amounts[i]
item.list_type = item_list_types[i]
item.modified = datetime.datetime.now()
item.shop_id = shop_id
if not item_ids:
result.update(
type='warning',
title='Failed to update items:',
message='There is no item to update.'
)
else:
result.update(
type='success',
title='Congratulations!',
message='All items successfully updated.'
)
elif tab == 'settings':
existing_user = (
models.session.query(models.User)
.filter(
models.orm.or_(
models.User.name == name,
models.User.slug == slug
)
).first()
)
if existing_user:
if existing_user.id != user.id:
result.update(
type='error',
title='Failed to update settings:'
)
if existing_user.name == name:
result['message'] = 'Name already exists'
elif existing_user.slug == slug:
result['message'] = 'Slug already exists'
if not result['type']:
result.update(
type='success',
title='Congratulations!',
message='Settings successfully updated.'
)
user.name = name
user.slug = slug
if add:
# Make new_item_list_type to 0 when intentionally modified:
if new_item_list_type not in ['0', '1', '2']:
new_item_list_type = '0'
if (
not new_item_name or int(new_item_list_type) <= 1
and not new_item_price or int(new_item_list_type) == 2
and not new_item_trade
):
result.update(
type='error',
title='Failed to add item:'
)
if not new_item_name:
result['message'] = 'Item Name is required.'
elif int(new_item_list_type) <= 1 and not new_item_price:
result['message'] = 'Item Price is required.'
elif int(new_item_list_type) == 2 and not new_item_trade:
result['message'] = 'Item to Trade is required.'
else:
result.update(
type='success',
title='Congratulations!',
message='Item successfully added.'
)
new_item = models.Item(
icon_id=new_item_icon_id.strip(),
name=new_item_name,
price=new_item_price,
trade=new_item_trade,
amount=new_item_amount,
list_type=new_item_list_type,
shop_id=shop_id
)
models.session.add(new_item)
# Empty fields once successful (except for amount set to 1):
new_item_icon_id = ''
new_item_name = ''
new_item_price = ''
new_item_trade = ''
new_item_amount = 1
if remove:
if not items_selected:
result.update(
type='warning',
title='Failed to remove an item:',
message='No item was selected.'
)
else:
result.update(
type='success',
title='Congratulations',
message='Selected items successfully removed.'
)
for item in items_selected:
(
models.session.query(models.Item)
.filter(models.Item.id == item)
.filter(models.Item.shop_id == shop_id)
.delete()
)
if update or add or remove:
models.session.commit()
if update and tab == 'settings':
app.request.session['user_slug'] = slug
tpl = 'profile_{}'.format(tab)
items = models.session.query(models.Item).filter_by(shop_id=shop_id).all()
return app.template(tpl, html=html, **locals())
@app.get('/<slug><page_num:re:(/page/\d+)?><:re:/?>')
def user(slug, page_num):
if not page_num:
page_num = 1
else:
page_num = int(filter(None, page_num.split('/'))[1])
if int(page_num) <= 1:
app.redirect('/' + slug)
pagination_slug = '/' + slug
logged_in = app.request.session.get('logged_in')
user_slug = app.request.session.get('user_slug')
diff_date = globals()['diff_date']
list_types = config.LIST_TYPES
cdn = config.CDN
user = (
models.session.query(models.User)
.filter_by(slug=slug)
.join(models.Shop)
.join(models.Item)
.first()
)
if not user:
app.abort(404)
paginated_pages = paginator(user.shop.items, 10)
paginated_indexes = range(0, len(paginated_pages))
paginated_prev = paginator_prev(paginated_indexes, page_num)
paginated_next = paginator_next(paginated_indexes, page_num)
return app.template('user', html=html, **locals())
@app.get('/favicon.ico')
def favicon():
root = os.path.join(os.path.dirname(__file__), 'static')
return app.static_file('favicon.ico', root=root)
@app.get('/logout')
def logout():
logged_in = app.request.session.get('logged_in')
user_slug = app.request.session.get('user_slug')
app.request.session.delete()
app.redirect('/')
@app.get('/<path>/<file_>')
def static(path, file_):
root = os.path.join(os.path.dirname(__file__), 'static')
return app.static_file(file_, root=root + '/' + path)
@app.error(404)
@app.error(500)
def page_404(error):
logged_in = app.request.session.get('logged_in')
user_slug = app.request.session.get('user_slug')
return app.template('404', html=html, **locals())
app.run(
server=config.SERVER,
host=config.HOST,
port=config.PORT,
debug=config.DEBUG,
reloader=config.RELOADER,
app=SessionMiddleware(app.app(), {
'session.data_dir': config.SESSION,
'session.type': config.SESSION_TYPE,
'session.auto': config.SESSION_AUTO
})
)
<file_sep>/py/wooji/apps/_media/views.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""views.py: Media files routes."""
import controllers as ctrl
routes = [
('/media/<dir_name:re:(.+?/)*><file_name>', ctrl.media)
]
<file_sep>/py/alchemified/app/app/securities/__init__.py
from pyramid.authorization import ACLAuthorizationPolicy
from .authentication import CustomAuthenticationPolicy, get_user
from .authorization import RootFactory, group_finder
def includeme(config):
settings = config.get_settings()
authentication_secret = settings.get('authentication.secret')
authentication_hashalg = settings.get('authentication.hashalg')
authentication_policy = CustomAuthenticationPolicy(
authentication_secret,
hashalg=authentication_hashalg,
callback=group_finder)
config.set_authentication_policy(authentication_policy)
authorization_policy = ACLAuthorizationPolicy()
config.set_authorization_policy(authorization_policy)
config.set_root_factory(RootFactory)
default_permission = 'edit'
config.set_default_permission(default_permission)
request_method_name = 'user'
config.add_request_method(get_user, request_method_name, reify=True)
<file_sep>/py/alchemified/app/app/routes/__init__.py
from importlib import import_module
from app.helpers import TreeHelper
from . import __name__ as routes_qualname
from . import __file__
def includeme(config):
tree = TreeHelper(__file__)
modules = tree.modules()
for module in modules:
package = '{}.{}'.format(routes_qualname, module)
module_ = import_module(package)
parent = routes_qualname.split('.')[-1]
callback = '{}_{}'.format(module, parent)
routes = getattr(module_, callback)
[config.add_route(n, p) for n, p in routes]
<file_sep>/py/resume/modules/thumbnail.py
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""thumbnail.py: Image to thumbnail converter."""
from PIL import Image
import config
import function
class Thumbnail:
"""TODO: Class docstring."""
def __init__(self, base=config.ASSETS):
"""TODO: Method docstring."""
self.base = base
self.info = {}
self.errors = []
def create(self, path, size=(150, 150)):
"""TODO: Function docstring."""
file_name = path.split('/')[-1]
name, extension = file_name.split('.')
new_file_name = '{name}-thumbnail.{extension}'.format(
name=name,
extension=extension
)
file_path = '{base}/{path}'.format(base=self.base,
path=path.lstrip('/'))
new_file_path = path.replace(file_name, new_file_name)
abs_file_path = file_path.replace(file_name, new_file_name)
try:
image = Image.open(file_path)
image.thumbnail(size, Image.ANTIALIAS)
image.save(abs_file_path)
self.info = function.image_info(new_file_path)
except:
self.errors.append('Failed to create image thumbnail')
return True if self.info else False
|
3eea56666a2d1f5449bab9c1c2ca8acec71dcc23
|
[
"SQL",
"HTML",
"JavaScript",
"Markdown",
"INI",
"Python",
"Text",
"Shell"
] | 124
|
JavaScript
|
ejelome/archaic
|
9dcc6b09b61a72fc2659b52af39a40efe81f60c8
|
46625c2eff9ccec0039473a3fb4fd132c89eaf64
|
refs/heads/master
|
<file_sep>-- 数据库初始化脚本
-- 创建数据库
CREATE DATABASE seckill;
-- 使用数据库
use seckill;
CREATE TABLE seckill(
`seckill_id` bigint not null AUTO_INCREMENT COMMENT '商品库存ID',
`name` VARCHAR(120) not null COMMENT '商品名称',
`number` INT not null COMMENT '库存数量',
`create_time` TIMESTAMP not null DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`start_time` timestamp not null COMMENT '秒杀开始时间',
`end_time` TIMESTAMP not null COMMENT '秒杀结束时间',
PRIMARY key (seckill_id),
key idx_start_time(start_time),
key idx_end_time(end_time),
key idx_create_time(create_time)
)ENGINE=InnoDB AUTO_INCREMENT=1000 DEFAULT CHARSET=`utf8` COMMENT='描述库存表';
-- 初始化数据
INSERT INTO seckill(name,number,start_time,end_time)
value
('1000元秒杀iPhone',100,'2017-11-01 00:00:00','2017-11-02 00:00:00'),
('5000元秒杀iPhone8',200,'2017-11-01 00:00:00','2017-11-02 00:00:00'),
('100元秒杀xiaomi',300,'2017-11-01 00:00:00','2017-11-02 00:00:00'),
('400元秒杀hongmi',200,'2017-11-01 00:00:00','2017-11-02 00:00:00');
-- 秒杀成功信息表
-- 用户登录认证相关信息
CREATE TABLE success_killed(
`seckill_id` bigint not null COMMENT '秒杀商品ID',
`user_phone` bigint not null COMMENT '用户手机号',
`state` tinyint not null DEFAULT -1 COMMENT '状态标识:-1:无效 0:成功 1:已付款',
`create_time` TIMESTAMP not null COMMENT '创建时间',
PRIMARY KEY (seckill_id,user_phone),
key idx_create_time(create_time)
)ENGINE=InnoDB DEFAULT CHARSET=`utf8` COMMENT='秒杀成功信息表';
<file_sep>package com.hu.ssm.service;
import com.hu.ssm.dto.Exposer;
import com.hu.ssm.dto.SeckillExecution;
import com.hu.ssm.entity.Seckill;
import com.hu.ssm.exception.RepeatKillException;
import com.hu.ssm.exception.SeckillCloseException;
import com.hu.ssm.exception.SeckillException;
import java.util.Date;
import java.util.List;
/**
* 业务接口:站在"使用者"角度设计接口
* 三个方面:方法定义粒度,转入参数,返回类型(return 类型和异常)
* Created by huz on 2018/1/9.
*/
public interface ISeckillService {
/**
* 查询所有秒杀记录
* @return
*/
List<Seckill> getSeckillList();
/**
* 查询单个秒杀记录
* @param seckillId
* @return
*/
Seckill getById(long seckillId);
/**
* 秒杀开启时输出秒杀接口
* 否则输出系统时间和秒杀时间
* 防止秒杀前被用户拼出秒杀接口进行秒杀
* @param seckillId
*/
Exposer exportSeckillUrl(long seckillId);
/**
* 执行秒杀操作
* md5判读用户是否正确安全性
* @param seckillId
* @param userPhone
* @param md5
* @return
*/
SeckillExecution executeSeckill(long seckillId,long userPhone,String md5)
throws SeckillException,SeckillCloseException,RepeatKillException;
/**
* 通过存储过程执行秒杀操作
* md5判读用户是否正确安全性
* @param seckillId
* @param userPhone
* @param md5
* @return
*/
SeckillExecution executeSeckillProcedure(long seckillId, long userPhone, String md5)
throws SeckillException,SeckillCloseException,RepeatKillException;
}
<file_sep>package com.hu.ssm.service;
import com.hu.ssm.entity.SuccessKilled;
/**
* Created by huz on 2018/1/9.
*/
public interface ISuccessKilledService {
/**
* 插入购买明细,可过滤重复
* @param seckillId
* @param userPhone
* @return
*/
int insertSuccessKilled(long seckillId,long userPhone);
/**
* 根据ID查询successKilled并携带秒杀产品对象实体
* @param seckillId
* @return
*/
SuccessKilled queryByIdWithSeckill(long seckillId);
}
<file_sep>package com.hu.ssm.dto;
import com.hu.ssm.entity.SuccessKilled;
import com.hu.ssm.enums.SeckillStatEnum;
/**
* Created by huz on 2018/3/17.
* 封装秒杀执行后结果
*/
public class SeckillExecution {
//订单ID
private long seckillId;
//秒杀执行结果状态
private int status;
//状态表示
private String statusInfo;
//秒杀成功对象
private SuccessKilled successKilled;
public SeckillExecution(long seckillId, SeckillStatEnum seckillStatEnum, SuccessKilled successKilled) {
this.seckillId = seckillId;
this.status = seckillStatEnum.getState();
this.statusInfo = seckillStatEnum.getStateinfo();
this.successKilled = successKilled;
}
public SeckillExecution(long seckillId, SeckillStatEnum seckillStatEnum) {
this.seckillId = seckillId;
this.status = seckillStatEnum.getState();
this.statusInfo = seckillStatEnum.getStateinfo();
}
public long getSeckillId() {
return seckillId;
}
public void setSeckillId(long seckillId) {
this.seckillId = seckillId;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getStatusInfo() {
return statusInfo;
}
public void setStatusInfo(String statusInfo) {
this.statusInfo = statusInfo;
}
public SuccessKilled getSuccessKilled() {
return successKilled;
}
public void setSuccessKilled(SuccessKilled successKilled) {
this.successKilled = successKilled;
}
@Override
public String toString() {
return "SeckillExecution{" +
"seckillId=" + seckillId +
", status=" + status +
", statusInfo='" + statusInfo + '\'' +
", successKilled=" + successKilled +
'}';
}
}
<file_sep># 关于开发Java高并发秒杀项目
*业务对象依赖图*

##后台
*service层和dao层总结*
为了提高秒杀时候的安全性,秒杀接口是只有在规定时间内才能暴露给用户,
秒杀商品在数据库中有两个特殊字段,秒杀开启时间和结束时间,除此之外为了安全还有使用MD5加密字符串作为正确用户验证,自己封装秒杀执行后结果
##### 关于MD5验证原理
在秒杀接口方法中有一个MD5加密验证,在用户秒杀一件商品时,为了安全起见秒杀时除了秒杀id和用户电话还需要一个MD5,这个MD5是后台根据自己的一个加密串-盐结合秒杀id生成的,在暴露秒杀接口时将这个生成的MD5传到前台,在秒杀时更加秒杀id和本地的生成MD5方法生成一个相同的MD5,如果两者匹配那么证明就是安全的秒杀,如果不匹配甚至转过来的MD5为空那么就证明,这个访问非法,抛出异常。
**部分代码如下:**
暴露接口方法中:
```
String md5 = getMD5(seckillId);
```
秒杀接口方法中:
```
getMD5(seckillId).equals(md5)
```
getMD5方法:
```
private String getMD5(long seckillId){
String base = seckillId + "/" +slat;
String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
return md5;
}
```
##前台


*Restful接口设计*
比如:GET /seckill/list
Post /seckill/execute/{seckillId}这是反例
Post /seckill/{seckillId}/execution这是正确的
URL设计
/模块/资源/{标示}/集合1/...
## 秒杀学习
1.前后台交互设计
2.resetApi接口设计
3.springmvc更多使用技巧
4.bootstrop和js使用
### 秒杀URL设计
GET /seckill/list 秒杀列表
GET /seckill/{id}/detail 详情页
Get /seckill/time/now 系统时间
POST /seckill/{id}/exposer 暴露秒杀
POST /seckill/{id}/{md5}/execution 执行秒杀
## 项目总结并发优化
系统存在可优化环节

优化思路是把客户端逻辑放到MySQL服务端,避免网络延迟和GC影响
两种解决方案
定制SQL方案:
1.修改MySQL源码,淘宝就有过历史
2.使用存储过程使整个事物在MySQL端完成


这样做的原因是如果插入失败就没必要更新了。


虽然在本示例中使用MySQL中的事务能够有效节约系统系统秒杀事件,但并不适合所有系统,只是本事务较为简单。

集群化部署示例有如下方式:

## 总结
做完示例后学到的有
**秒杀系统的基本理念:**
1.数据库,实体构建
2.接口构建
3.安全保证
<file_sep>package com.hu.ssm.service.impl;
import com.hu.ssm.entity.SuccessKilled;
import com.hu.ssm.service.ISuccessKilledService;
import org.springframework.stereotype.Service;
/**
* Created by huz on 2018/1/9.
*/
@Service
public class SuccessKilledServiceImpl implements ISuccessKilledService {
public int insertSuccessKilled(long seckillId, long userPhone) {
return 0;
}
public SuccessKilled queryByIdWithSeckill(long seckillId) {
return null;
}
}
<file_sep>package com.hu.ssm.mapper;
import com.hu.ssm.entity.SuccessKilled;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import static org.junit.Assert.*;
/**
* Created by huz on 2018/3/13.
*/
@RunWith(SpringJUnit4ClassRunner.class)
//告诉JunitSpring的配置文件
@ContextConfiguration({"classpath:spring-mybatis.xml"})
public class SuccessKilledMapperTest {
@Resource
private SuccessKilledMapper successKilledMapper;
@Test
public void insertSuccessKilled() throws Exception {
long id = 1000L;
long phone = 13502181181L;
int insertCount = successKilledMapper.insertSuccessKilled(id,phone);
System.out.println("insert="+insertCount);
}
@Test
public void queryByIdWithSeckill() throws Exception {
long id = 1000L;
long phone = 13502181181L;
SuccessKilled successKilled = successKilledMapper.queryByIdWithSeckill(id,phone);
System.out.println("insert="+successKilled);
System.out.println(successKilled.getSeckill());
}
}<file_sep>package com.hu.ssm.service;
import com.hu.ssm.dto.Exposer;
import com.hu.ssm.dto.SeckillExecution;
import com.hu.ssm.entity.Seckill;
import com.hu.ssm.exception.RepeatKillException;
import com.hu.ssm.exception.SeckillCloseException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
/**
* Created by huz on 2018/3/24.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring-mybatis.xml",
"classpath:spring-service.xml"})
public class ISeckillServiceTest {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private ISeckillService iSeckillService;
@Test
public void getSeckillList() throws Exception {
List<Seckill> seckillList = iSeckillService.getSeckillList();
logger.info("list={}",seckillList);
}
@Test
public void getById() throws Exception {
}
//测试代码完整逻辑,注意可重复执行
@Test
public void testSeckillLogic() throws Exception {
long id = 1001;
Exposer exposer = iSeckillService.exportSeckillUrl(id);
if (exposer.isExposed()){
logger.info("exposer={}",exposer);
long phone = 13502171183L;
String md5 = "c70d673a0e8614a74c1a4a9124801473";
try {
SeckillExecution seckillExecution = iSeckillService.executeSeckill(id,phone,md5);
logger.info("result={}",seckillExecution);
}catch (RepeatKillException e){
logger.error(e.getMessage());
}catch (SeckillCloseException e){
logger.error(e.getMessage());
}
}else {
//秒杀未开启
logger.warn("exposer={}",exposer);
}
//exposed=true,
// md5='c70d673a0e8614a74c1a4a9124801473',
// seckillId=1000,
// now=0,
// start=0,
// end=0
}
@Test
public void executeSeckill() throws Exception {
long id = 1000;
/**
* 21:02:42.688 {main} DEBUG org.mybatis.spring.SqlSessionUtils - Creating a new SqlSession
21:02:42.696 {main} DEBUG org.mybatis.spring.SqlSessionUtils - Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4604b900]
21:02:42.710 {main} DEBUG o.m.s.t.SpringManagedTransaction - JDBC Connection [com.mchange.v2.c3p0.impl.NewProxyConnection@654c1a54] will be managed by Spring
21:02:42.717 {main} DEBUG c.h.s.m.SeckilledMapper.reduceNumber - ==> Preparing: update seckill SET number = number-1 where seckill_id = ? and start_time <= ? and end_time >= ? and number > 0;
21:02:42.751 {main} DEBUG c.h.s.m.SeckilledMapper.reduceNumber - ==> Parameters: 1000(Long), 2018-03-27 21:02:42.681(Timestamp), 2018-03-27 21:02:42.681(Timestamp)
21:02:42.751 {main} DEBUG c.h.s.m.SeckilledMapper.reduceNumber - <== Updates: 1
21:02:42.752 {main} DEBUG org.mybatis.spring.SqlSessionUtils - Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4604b900]
21:02:42.752 {main} DEBUG org.mybatis.spring.SqlSessionUtils - Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4604b900] from current transaction
21:02:42.752 {main} DEBUG c.h.s.m.S.insertSuccessKilled - ==> Preparing: INSERT ignore INTO success_killed(seckill_id,user_phone,state) VALUES (?,?,0)
21:02:42.753 {main} DEBUG c.h.s.m.S.insertSuccessKilled - ==> Parameters: 1000(Long), 13502171181(Long)
21:02:42.754 {main} DEBUG c.h.s.m.S.insertSuccessKilled - <== Updates: 1
21:02:42.769 {main} DEBUG org.mybatis.spring.SqlSessionUtils - Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4604b900]
21:02:42.770 {main} DEBUG org.mybatis.spring.SqlSessionUtils - Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4604b900] from current transaction
21:02:42.772 {main} DEBUG c.h.s.m.S.queryByIdWithSeckill - ==> Preparing: select sk.seckill_id, sk.user_phone, sk.create_time, sk.state, s.seckill_id "seckill.seckill_id", s.name "seckill.name", s.number "seckill.number", s.start_time "seckill.start_time", s.end_time "seckill.end_time", s.create_time "seckill.create_time" from success_killed sk inner join seckill s on sk.seckill_id = s.seckill_id where sk.seckill_id = ? AND sk.user_phone=?
21:02:42.772 {main} DEBUG c.h.s.m.S.queryByIdWithSeckill - ==> Parameters: 1000(Long), 13502171181(Long)
21:02:42.792 {main} DEBUG c.h.s.m.S.queryByIdWithSeckill - <== Total: 1
21:02:42.799 {main} DEBUG org.mybatis.spring.SqlSessionUtils - Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4604b900]
21:02:42.818 {main} DEBUG org.mybatis.spring.SqlSessionUtils - Transaction synchronization committing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4604b900]
21:02:42.818 {main} DEBUG org.mybatis.spring.SqlSessionUtils - Transaction synchronization deregistering SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4604b900]
21:02:42.819 {main} DEBUG org.mybatis.spring.SqlSessionUtils - Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4604b900]
21:02:42.876 {main} INFO c.hu.ssm.service.ISeckillServiceTest - result=com.hu.ssm.dto.SeckillExecution@779dfe55
*/
/**
* result=SeckillExecution{
* seckillId=1000,
* status=1,
* statusInfo='秒杀成功',
* successKilled=
* SuccessKilled{
* seckillId=1000,
* userPhone=13502171183,
* state=0,
* createTime=Tue Mar 27 21:05:33 CST 2018,
* seckill=Seckill{
* seckillId=1000,
* name='1000元秒杀iPhone',
* startTime=Wed Nov 01 00:00:00 CST 2017,
* endTime=Fri Mar 30 00:00:00 CST 2018,
* createTime=Tue Jan 09 21:22:03 CST 2018}}}
*/
}
@Test
public void executeSeckillProcedure(){
long seckillId = 1001;
long phone = 1366676071;
Exposer exposer = iSeckillService.exportSeckillUrl(seckillId);
if (exposer.isExposed()){
String md5 = exposer.getMd5();
SeckillExecution execution = iSeckillService.executeSeckillProcedure(seckillId,phone,md5);
logger.info(execution.getStatusInfo());
}
}
}
|
d4d2eac282b0dec57981b9b621b88e1f75884fb3
|
[
"Java",
"SQL",
"Markdown"
] | 8
|
SQL
|
bossZhuang/Java-
|
19751b7a23891b5d429ce0f6a23c3ffa4c94a4f2
|
29bccdcc2a892ffd6093701b41fb46e1acf3649d
|
refs/heads/master
|
<repo_name>messageformat/properties-loader<file_sep>/example/src/index.js
import Messages from '@messageformat/runtime/messages'
import en from './messages_en.properties'
const messages = new Messages({ en })
function component() {
const element = document.createElement('div')
element.innerHTML = messages.get(
['errors', 'format'],
['Foo', messages.get(['errors', 'messages', 'wrong_length'], { count: 42 })]
)
return element
}
console.log('locale', messages.locale)
console.log('messages', messages.get([]))
if (typeof document !== 'undefined') document.body.appendChild(component())
<file_sep>/README.md
# Property Resource Bundle Loader for Webpack
Loads .properties files into JavaScript as precompiled functions using [dot-properties] and [messageformat].
Property values are parsed directly as ICU MessageFormat. With the default options, will assume that the filename has `_` separated parts, of which the second is the two- or three-letter language code [as in Java Resource Bundles].
[dot-properties]: https://www.npmjs.com/package/dot-properties
[messageformat]: https://messageformat.github.io/
[as in java resource bundles]: https://docs.oracle.com/javase/9/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-java.util.Locale-java.lang.ClassLoader-
## Installation
```sh
npm install messageformat-properties-loader
```
## Usage
For a working demo of the following, run `npm install && npm run build` in the [`example/`](./example/) directory, and then open `example/dist/index.html` in a browser.
#### Webpack configuration
```js
{
test: /\.properties$/,
loader: 'messageformat-properties-loader',
options: {
biDiSupport: false, // enables bi-directional text support
defaultLocale: 'en', // used if resolution from filename fails
encoding: 'auto', // .properties file encoding, use one of
// 'auto', 'latin1', or 'utf8'
keyPath: false, // if true, dots '.' key names will result
// in multi-level objects -- use a string
// value to customize
pathSep: '_' // separator for parsing locale from filename
}
}
```
Default option values are shown above, though none are required.
#### messages_en.properties
```
errors.confirmation: {src} doesn't match {attribute}
errors.accepted: {src} must be accepted
errors.wrong_length: {src} is the wrong length (should be {count, plural, one{1 character} other{# characters}})
errors.equal_to: {src} must be equal to {count}
```
#### example.js
```js
import messages from './messages_en.properties'
messages.errors.accepted({ src: 'Terms' })
// 'Terms must be accepted'
messages.errors.wrong_length({ src: 'Foo', count: 42 })
// 'Foo is the wrong length (should be 42 characters)'
```
<file_sep>/index.js
const MessageFormat = require('@messageformat/core')
const compileModule = require('@messageformat/core/compile-module')
const { parse } = require('dot-properties')
const loaderUtils = require('loader-utils')
const path = require('path')
const uv = require('uv')
// expected to follow the pattern baseName_language[_script]_country_variant.properties
// source: https://docs.oracle.com/javase/9/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-java.util.Locale-java.lang.ClassLoader-
function localeFromResourcePath(resourcePath, pathSep, defaultLocale) {
const parts = path.basename(resourcePath).split(pathSep)
const locale = parts[1] && parts[1].replace(/\..*$/, '').toLowerCase()
if (locale === 'pt-pt' || (locale === 'pt' && /^pt/i.test(parts[2]))) {
// European Portuguese is the only locale for which subtags matter
return 'pt-PT'
}
return /^[a-z]{2,3}$/.test(locale || '') ? locale : defaultLocale
}
module.exports = function messageformatPropertiesLoader(content) {
let { defaultLocale, encoding, keyPath, pathSep, ...mfOpt } =
loaderUtils.getOptions(this) || {}
if (!encoding || encoding === 'auto')
encoding = uv(content) ? 'utf8' : 'latin1'
const input = content.toString(encoding)
const messages = parse(input, keyPath || false)
const locale = localeFromResourcePath(
this.resourcePath,
pathSep || '_',
defaultLocale || 'en'
)
const mf = new MessageFormat(locale, mfOpt)
return compileModule(mf, messages)
}
// get content as Buffer rather than string
module.exports.raw = true
|
a8673642f048b1d38e0f978c3f642b25aca068e4
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
messageformat/properties-loader
|
6e4ae8952a347b9488fcd5e7215cc5b4bdb8e53d
|
cb6de6e1338132265c4b222b9d5d49c324b54f68
|
refs/heads/main
|
<file_sep>namespace SurveyResultProcessor.Models
{
public enum Survey
{
Theme,
Type,
Text,
}
}
<file_sep>using NUnit.Framework;
namespace SurveyResultProcessor.Test
{
[TestFixture]
public class ResponseStatisticServiceTest
{
[Test]
public void InputFileSurvey1Test()
{
var args = new string[] { @"..//..//..//TestData//survey-1.csv", @"..//..//..//TestData//survey-1-responses.csv" };
var input = new InputDataService();
(var survey, var surveyResponses) = input.GetCommandsFromFile(args);
var action = new ResponseStatisticService();
var stat = action.GetAverageForRatingQuestions(survey, surveyResponses);
Assert.True(stat.Count == 5);
}
[Test]
public void InputFileSurvey3Test()
{
var args = new string[] { @"..//..//..//TestData//survey-3.csv", @"..//..//..//TestData//survey-3-responses.csv" };
var input = new InputDataService();
(var survey, var surveyResponses) = input.GetCommandsFromFile(args);
var action = new ResponseStatisticService();
var stat = action.GetAverageForRatingQuestions(survey, surveyResponses);
Assert.True(stat.Count == 0);
}
[Test]
public void InputFileSurvey2Test()
{
var args = new string[] { @"..//..//..//TestData//survey-2.csv", @"..//..//..//TestData//survey-2-responses.csv" };
var input = new InputDataService();
(var survey, var surveyResponses) = input.GetCommandsFromFile(args);
var action = new ResponseStatisticService();
var stat = action.GetAverageForRatingQuestions(survey, surveyResponses);
Assert.True(stat.Count == 4);
}
}
}<file_sep>using System;
using NUnit.Framework;
namespace SurveyResultProcessor.Test
{
[TestFixture]
public class InputDataServiceTest
{
[Test]
public void InputFileSurvey1Test()
{
var args = new string[] { @"..//..//..//TestData//survey-1.csv", @"..//..//..//TestData//survey-1-responses.csv" };
var action = new InputDataService();
(var survey, var surveyResponses) = action.GetCommandsFromFile(args);
Assert.True(survey.Count - 1 == surveyResponses[0].Questions.Count);
}
[Test]
public void InputFileSurvey2Test()
{
var args = new string[] { @"..//..//..//TestData//survey-2.csv", @"..//..//..//TestData//survey-2-responses.csv" };
var action = new InputDataService();
(var survey, var surveyResponses) = action.GetCommandsFromFile(args);
Assert.True(survey.Count - 1 == surveyResponses[0].Questions.Count);
}
[Test]
public void InputFileSurvey3Test()
{
var args = new string[] { @"..//..//..//TestData//survey-3.csv", @"..//..//..//TestData//survey-3-responses.csv" };
var action = new InputDataService();
(var survey, var surveyResponses) = action.GetCommandsFromFile(args);
Assert.True(survey.Count - 1 == surveyResponses[0].Questions.Count);
}
[Test]
public void InputFileSurveyNoArgTest()
{
var args = new string[] { };
var action = new InputDataService();
var ex = Assert.Throws<Exception>(() => action.GetCommandsFromFile(args));
Assert.That(ex.Message, Is.EqualTo("One of the input parameters are missing. Please provide a file path as a paramater."));
}
[Test]
public void InputFileSurveyOneMissingTest()
{
var args = new string[] { @"..//..//..//TestData//survey-3-responses.csv", @"..//..//..//TestData//survey-3-responses!!!!!.csv" };
var action = new InputDataService();
var ex = Assert.Throws<Exception>(() => action.GetCommandsFromFile(args));
Assert.That(ex.Message, Does.Contain($"File path {args[1]} doesn't exist."));
}
[Test]
public void InputFileSurveyOneMissingOrdserTest()
{
var args = new string[] { @"..//..//..//TestData//survey-3-responses.csv", @"..//..//..//TestData//survey-3-responses.csv" };
var action = new InputDataService();
var ex = Assert.Throws<Exception>(() => action.GetCommandsFromFile(args));
Assert.That(ex.Message, Does.Contain($"Wrong formatting input. Please check input files."));
}
}
}<file_sep># Survey Statistic app description.
Setting environment:
Language, Enviroments: C#, .Net 5.0
Requirements: dotnet SDK
For Windows:
Install:
- https://docs.microsoft.com/en-us/dotnet/core/install/windows?tabs=net50
Building:
- cd SurveyResultProcessor
- dotnet test
- dotnet build -o ./Output
Or:
- via Visual Studio
Run:
- dotnet ./Output/SurveyResultProcessor.dll ./SurveyResultProcessor.Test/TestData/survey-1.csv ./SurveyResultProcessor.Test/TestData/survey-1-responses.csv
Output: There is no input parameter. Please provide a files path as input paramater: <surveyPath> <surveyResponsesPath>.
- dotnet ./Output/SurveyResultProcessor.dll <PathToSurveyInputFile> <PathToSurveyResponseInputFile>
For Mac:
Install:
- https://docs.microsoft.com/en-us/dotnet/core/install/macos
- brew install --cask dotnet-sdk
Building:
- cd SurveyResultProcessor
- dotnet test
- dotnet build -o /Output
Run:
- dotnet ./Output/SurveyResultProcessor.dll ./SurveyResultProcessor.Test/TestData/survey-1.csv ./SurveyResultProcessor.Test/TestData/survey-1-responses.csv
Output: There is no input parameter. Please provide a files path as input paramater: <surveyPath> <surveyResponsesPath>.
- dotnet ./Output/SurveyResultProcessor.dll <PathToSurveyInputFile> <PathToSurveyResponseInputFile>
Design:
The application splitted on 3 parts:
- Model. Decribe domain of application.
- Services:
- InputDataService. Read inputs from files.
- ParticipationService. The participation percentage and total participant counts of the survey.
- ResponseStatisticService. The average for each rating question
- View. Output in console.
The implementation is easy to extend functionalities and add new rules, commands.
<file_sep>using System;
using System.Collections.Generic;
using SurveyResultProcessor.Models;
namespace SurveyResultProcessor
{
public class ResponseStatisticService : IResponseStatisticService
{
public Dictionary<string, int> GetAverageForRatingQuestions(List<string[]> survey, List<SurveyResponse> surveyResponse)
{
var stat = new Dictionary<string, int>(survey.Count);
(var indexOfTypeColumn, var indexOfQuestionColumn) = GetIndexOfTextAndTypeColumns(survey[0]);
for (int questionNumber = 1; questionNumber < survey.Count; questionNumber++)
{
if (Enum.TryParse(survey[questionNumber][indexOfTypeColumn], true, out QuestionType type) && type == QuestionType.ratingquestion)
{
var average = GetAverageFromResponsePerQuestion(questionNumber - 1, surveyResponse);
if (average != 0) stat.Add(survey[questionNumber][indexOfQuestionColumn], average);
}
}
return stat;
}
private int GetAverageFromResponsePerQuestion(int questionOrder, List<SurveyResponse> surveyResponse)
{
var aver = 0;
var total = 0;
foreach (var resp in surveyResponse)
{
if (!string.IsNullOrEmpty(resp.Submitted) && int.TryParse(resp.Questions[questionOrder], out int result))
{
aver += result;
total++;
}
}
return total == 0 ? 0 : aver / total;
}
private (int, int) GetIndexOfTextAndTypeColumns(string[] survey)
{
var typeIndex = -1;
var textIndex = -1;
for (int i = 0; i < survey.Length; i++)
{
if (Enum.TryParse(survey[i], true, out Survey text) && text == Survey.Text) textIndex = i;
if (Enum.TryParse(survey[i], true, out Survey type) && text == Survey.Type) typeIndex = i;
}
if (textIndex == -1 || typeIndex == -1) throw new Exception("Question column header is not defined.");
return (typeIndex, textIndex);
}
}
}
<file_sep>using System.Collections.Generic;
using SurveyResultProcessor.Models;
namespace SurveyResultProcessor
{
interface IInputDataService
{
(List<string[]>, List<SurveyResponse>) GetCommandsFromFile(string[] args);
}
}
<file_sep>namespace SurveyResultProcessor.Models
{
public enum QuestionType
{
ratingquestion,
singleselect
}
}
<file_sep>using System.Collections.Generic;
using SurveyResultProcessor.Models;
namespace SurveyResultProcessor
{
interface IParticipationService
{
(int, double) GetParticipationDetails(List<SurveyResponse> surveyResponse);
}
}
<file_sep>using NUnit.Framework;
namespace SurveyResultProcessor.Test
{
[TestFixture]
public class ParticipationServiceTest
{
[Test]
public void InputFileSurvey1Test()
{
var args = new string[] { @"..//..//..//TestData//survey-1.csv", @"..//..//..//TestData//survey-1-responses.csv" };
var input = new InputDataService();
(var survey, var surveyResponses) = input.GetCommandsFromFile(args);
var action = new ParticipationService();
(var participants, var percatageofParticipants) = action.GetParticipationDetails(surveyResponses);
Assert.True(participants == 5);
Assert.True(percatageofParticipants == 5 / 6.0);
}
[Test]
public void InputFileSurvey2Test()
{
var args = new string[] { @"..//..//..//TestData//survey-2.csv", @"..//..//..//TestData//survey-2-responses.csv" };
var input = new InputDataService();
(var survey, var surveyResponses) = input.GetCommandsFromFile(args);
var action = new ParticipationService();
(var participants, var percatageofParticipants) = action.GetParticipationDetails(surveyResponses);
Assert.True(participants == 5);
Assert.True(percatageofParticipants == 5/5.0);
}
[Test]
public void InputFileSurvey3Test()
{
var args = new string[] { @"..//..//..//TestData//survey-3.csv", @"..//..//..//TestData//survey-3-responses.csv" };
var input = new InputDataService();
(var survey, var surveyResponses) = input.GetCommandsFromFile(args);
var action = new ParticipationService();
(var participants, var percatageofParticipants) = action.GetParticipationDetails(surveyResponses);
Assert.True(participants == 0);
Assert.True(percatageofParticipants == 0);
}
}
}<file_sep>using System.Collections.Generic;
using SurveyResultProcessor.Models;
namespace SurveyResultProcessor
{
public class ParticipationService : IParticipationService
{
public (int, double) GetParticipationDetails(List<SurveyResponse> surveyResponse)
{
var countParticipants = GetPaticipants(surveyResponse);
return (countParticipants, countParticipants*1.0/surveyResponse.Count);
}
private int GetPaticipants(List<SurveyResponse> surveyResponse)
{
var count = 0;
foreach (var response in surveyResponse)
{
if (!string.IsNullOrEmpty(response.Submitted))
{
count++;
}
}
return count;
}
}
}<file_sep>using System.Collections.Generic;
using SurveyResultProcessor.Models;
namespace SurveyResultProcessor
{
interface IResponseStatisticService
{
Dictionary<string, int> GetAverageForRatingQuestions(List<string[]> survey, List<SurveyResponse> surveyResponse);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using SurveyResultProcessor.Models;
namespace SurveyResultProcessor
{
public class InputDataService : IInputDataService
{
public (List<string[]>, List<SurveyResponse>) GetCommandsFromFile(string[] args)
{
if (args == null || args.Length < 2) throw new Exception("One of the input parameters are missing. Please provide a file path as a paramater.");
if (!File.Exists(args[0])) throw new Exception($"File path {args[0]} doesn't exist.");
if (!File.Exists(args[1])) throw new Exception($"File path {args[1]} doesn't exist.");
var surveys = new List<string[]>();
var fileStream = new FileStream(args[0], FileMode.Open);
using (var reader = new StreamReader(fileStream))
{
string line;
while ((line = reader.ReadLine()) != null)
{
surveys.Add(GetColumnsFromRow(line));
}
}
var surveyResponse = new List<SurveyResponse>();
fileStream = new FileStream(args[1], FileMode.Open);
using (var reader = new StreamReader(fileStream))
{
string line;
while ((line = reader.ReadLine()) != null)
{
surveyResponse.Add(SurveyResponseFromFileInput(line));
}
}
return (surveys, surveyResponse);
}
private string[] GetColumnsFromRow(string line)
{
var rgx = new Regex(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
string[] words = rgx.Split(line).Where(w=> !rgx.Match(w).Success).Distinct().ToArray();
if (words.Length > 3) throw new Exception("Wrong formatting input. Please check input files.");
return words;
}
private static SurveyResponse SurveyResponseFromFileInput(string line)
{
var surveyParts = line.Split(',');
if (surveyParts.Length == 0) return null;
var survResp = new SurveyResponse
{
Email = surveyParts[0],
EmployeeId = surveyParts[1],
Submitted = surveyParts[2],
Questions = new List<string>(surveyParts.Length - 3)
};
for (int i = 3; i < surveyParts.Length; i++)
{
survResp.Questions.Add(surveyParts[i]);
}
return survResp;
}
}
}
<file_sep>using System.Collections.Generic;
namespace SurveyResultProcessor.Models
{
public class SurveyResponse
{
public string Email { get; set; }
public string EmployeeId { get; set; }
public string Submitted { get; set; }
public List<string> Questions { get; set; }
}
}
<file_sep>using System;
namespace SurveyResultProcessor
{
class Program
{
static void Main(string[] args)
{
try
{
(var survey, var surveyResponses) = new InputDataService().GetCommandsFromFile(args);
(var participants, var percentage) = new ParticipationService().GetParticipationDetails(surveyResponses);
var statistic = new ResponseStatisticService().GetAverageForRatingQuestions(survey, surveyResponses);
Console.WriteLine("\nSurvey reult:\n");
Console.WriteLine($"Participation percentage {percentage.ToString("P02")} and total participant counts of the survey: {participants} \n");
Console.WriteLine($"The average for each rating question:\n");
if (statistic.Count == 0)
{
Console.WriteLine($"There is no submitted responses for this survey.");
}
else
{
foreach (var question in statistic)
{
Console.WriteLine($"Question: {question.Key} Average: {question.Value}");
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadKey();
}
}
}
|
5982f5c3144d49275012902cec5cf5f0ca3eec46
|
[
"Markdown",
"C#"
] | 14
|
C#
|
ivanpchelnikov/SurveyCultureAMP
|
41a1252ba41d348f5bc86729e735f63c6f362c42
|
0146e4edb45b163c378298814b6dd289b128c11d
|
refs/heads/master
|
<repo_name>sumann/datasciencecoursera<file_sep>/welcome.php
<?php
echo "Welcome to new version";
?>
|
990f153ece86024b903ca8788a23d72ced76daac
|
[
"PHP"
] | 1
|
PHP
|
sumann/datasciencecoursera
|
cab71be599a862ba91928ecc971bc4c93a6f2a64
|
1f893d93ba6ccc3adfaec2013b9621a3ad773ce9
|
refs/heads/master
|
<repo_name>alexkashin90/AleksandrKashin<file_sep>/src/test/resources/test.properties
driver=chrome
timeout.wait.element=10
element.search.strategy=strict
smart.locator=#%s
log.level=INFO
log.info.details=element
browser.size=MAXIMIZE
<file_sep>/src/test/java/ru/training/at/hw4/pages/DifferentElementsPage.java
package ru.training.at.hw4.pages;
import java.util.List;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.Select;
public class DifferentElementsPage extends AbstractPage {
@FindBy(css = "input[type='checkbox']")
private List<WebElement> checkboxes;
@FindBy(css = "input[type='radio']")
private List<WebElement> radios;
@FindBy(css = "select.uui-form-element")
private WebElement dropdown;
@FindBy(css = ".logs >li")
private List<WebElement> logs;
public DifferentElementsPage(WebDriver driver) {
super(driver);
}
public boolean isWaterChecked(int listNumber) {
return checkboxes.get(listNumber).isSelected();
}
public void clickWaterCheckbox(int listNumber) {
checkboxes.get(listNumber).click();
}
public boolean isWindChecked(int listNumber) {
return checkboxes.get(listNumber).isSelected();
}
public void clickWindCheckbox(int listNumber) {
checkboxes.get(listNumber).click();
}
public boolean isSelenRadioChecked(int listNumber) {
return radios.get(listNumber).isSelected();
}
public void selectSelenRadio(int listNumber) {
radios.get(listNumber).click();
}
public void selectColor(String color) {
new Select(dropdown).selectByVisibleText(color);
}
public String getFirstSelectedColor() {
return new Select(dropdown).getFirstSelectedOption().getText();
}
public List<WebElement> getLogs() {
return logs;
}
}
<file_sep>/src/test/java/ru/training/at/hw7/pages/MetalAndColorsPage.java
package ru.training.at.hw7.pages;
import com.epam.jdi.light.elements.common.UIElement;
import com.epam.jdi.light.elements.complex.Checklist;
import com.epam.jdi.light.elements.complex.dropdown.Dropdown;
import com.epam.jdi.light.elements.composite.WebPage;
import com.epam.jdi.light.elements.pageobjects.annotations.locators.Css;
import com.epam.jdi.light.elements.pageobjects.annotations.locators.JDropdown;
import com.epam.jdi.light.elements.pageobjects.annotations.locators.UI;
import com.epam.jdi.light.elements.pageobjects.annotations.locators.XPath;
import com.epam.jdi.light.ui.html.elements.common.Button;
import com.epam.jdi.light.ui.html.elements.complex.RadioButtons;
import java.util.List;
import java.util.stream.Collectors;
import org.openqa.selenium.WebElement;
import ru.training.at.hw7.data.MetalAndColorsData;
public class MetalAndColorsPage extends WebPage {
@Css("#odds-selector input")
private RadioButtons summaryOdds;
@Css("#even-selector input")
private RadioButtons summaryEvens;
@Css("#elements-checklist input")
public Checklist elements;
@JDropdown(list = "#colors li",
expand = "#colors span.caret")
private Dropdown colors;
@JDropdown(list = "#metals span.text",
expand = "#metals span.caret")
private Dropdown metals;
@JDropdown(list = "#vegetables li",
expand = "#vegetables span.caret")
private Dropdown vegetables;
@Css("#submit-button")
private Button submitButton;
@Css(".results li")
private UIElement results;
private void selectFromDropdown(List<String> values, Dropdown dropdown) {
for (String value : values) {
dropdown.select(value);
}
}
private void selectFromCheckList(List<String> values, Checklist checklist) {
for (String value : values) {
checklist.select(value);
}
}
public void fillFormWithValues(MetalAndColorsData data) {
summaryOdds.select(String.valueOf(data.getSummary().get(0)));
summaryEvens.select(String.valueOf(data.getSummary().get(1)));
selectFromCheckList(data.getElements(), elements);
colors.expand();
colors.select(data.getColor());
metals.expand();
metals.select(data.getMetals());
vegetables.expand();
vegetables.select(3);
selectFromDropdown(data.getVegetables(), vegetables);
}
public void submit() {
submitButton.click();
}
public List<String> getResults() {
return results.getAll()
.stream()
.map(WebElement::getText)
.collect(Collectors.toList());
}
}
<file_sep>/src/test/resources/user.properties
login=Roman
password=<PASSWORD>
fullname=<NAME>
<file_sep>/src/test/java/ru/training/at/hw2/data/TestData.java
package ru.training.at.hw2.data;
import java.util.List;
public class TestData {
public static final String HOME_PAGE_URL = "https://jdi-testing.github.io/jdi-light/index.html";
public static final String HOME_PAGE_TITLE = "Home Page";
public static final List<String> HEADER_LINKS_TEXTS = List.of(
"HOME", "CONTACT FORM", "SERVICE", "METALS & COLORS"
);
public static final String LOGIN = "Roman";
public static final String PASSWORD = "<PASSWORD>";
public static final String USERNAME = "<NAME>";
public static final int NUMBER_OF_IMAGES = 4;
public static final List<String> TEXTS_BELOW_IMAGES = List.of(
"To include good practices",
"To be flexible and",
"To be multiplatform",
"Already have good base"
);
public static final List<String> LEFT_SECTION_LINKS_TEXTS = List.of(
"Home", "Contact form", "Service", "Metals & Colors", "Elements packs"
);
public static final String SERVICE_PAGE_TITLE = "Different Elements";
public static final String COLOR = "Yellow";
public static final List<String> TEXTS_OF_LOGS = List.of(
"value changed to Yellow",
"value changed to Selen",
"condition changed to true",
"condition changed to true"
);
}
<file_sep>/src/test/java/ru/training/at/hw5/pages/DifferentElementsPage.java
package ru.training.at.hw5.pages;
import java.util.List;
import java.util.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.Select;
public class DifferentElementsPage extends AbstractPage {
private LogSection logSection;
@FindBy(css = "input[type='checkbox']")
private static List<WebElement> checkboxes;
@FindBy(css = "input[type='radio']")
private static List<WebElement> radios;
@FindBy(css = "div>select")
private static WebElement dropdown;
public DifferentElementsPage(WebDriver driver) {
super(driver);
logSection = new LogSection(driver);
}
public WebElement getCheckboxByText(String checkboxText) {
for (WebElement element : checkboxes) {
String text = element.getAccessibleName();
if (text.equals(checkboxText)) {
return element;
}
}
throw new NoSuchElementException("Element \"" + checkboxText + "\" can not be found");
}
public void clickOnCheckbox(String checkboxText) {
getCheckboxByText(checkboxText).click();
}
public WebElement getRadioByText(String radioText) {
for (WebElement element : radios) {
String text = element.getAccessibleName();
if (text.equals(radioText)) {
return element;
}
}
throw new NoSuchElementException("Element \"" + radioText + "\" can not be found");
}
public void clickOnRadio(String radioText) {
getRadioByText(radioText).click();
}
public void selectColor(String color) {
new Select(dropdown).selectByVisibleText(color);
}
public LogSection getLogSection() {
return logSection;
}
}
<file_sep>/src/test/java/ru/training/at/hw7/data/MetalAndColorsData.java
package ru.training.at.hw7.data;
import java.util.Arrays;
import java.util.List;
public class MetalAndColorsData {
private List<Integer> summary;
private List<String> elements;
private String color;
private String metals;
private List<String> vegetables;
public MetalAndColorsData(List<Integer> summary, List<String> elements, String color, String metals,
List<String> vegetables) {
this.summary = summary;
this.elements = elements;
this.color = color;
this.metals = metals;
this.vegetables = vegetables;
}
public List<Integer> getSummary() {
return summary;
}
public List<String> getElements() {
return elements;
}
public String getColor() {
return color;
}
public String getMetals() {
return metals;
}
public List<String> getVegetables() {
return vegetables;
}
private Integer getSum() {
return getSummary()
.stream()
.mapToInt(Integer::intValue)
.sum();
}
public List<String> getExpectedResult() {
return Arrays.asList(
"Summary: " + (getSum()),
"Elements: " + elements.toString().replace("[", "").replace("]", ""),
"Color: " + color,
"Metal: " + metals,
"Vegetables: " + vegetables.toString().replace("[", "").replace("]", "")
);
}
}
<file_sep>/src/test/java/ru/training/at/hw6/tests/steps/HomePageSteps.java
package ru.training.at.hw6.tests.steps;
import static org.testng.Assert.assertEquals;
import io.qameta.allure.Step;
import ru.training.at.hw6.pages.AbstractPage;
import ru.training.at.hw6.pages.HomePage;
import ru.training.at.hw6.pages.LoggedInHomePage;
public class HomePageSteps {
@Step("Check if 'HomePage' title is correct")
public static void checkThatHomePageTitleIsCorrect(AbstractPage page, String expected) {
assertEquals(page.getTitle(), expected);
}
@Step("Log in user")
public static LoggedInHomePage logInUser(HomePage page) {
return page.logIn();
}
}
<file_sep>/src/test/java/ru/training/at/hw7/JdiSite.java
package ru.training.at.hw7;
import static com.epam.jdi.light.common.CheckTypes.CONTAINS;
import com.epam.jdi.light.elements.pageobjects.annotations.JSite;
import com.epam.jdi.light.elements.pageobjects.annotations.Title;
import com.epam.jdi.light.elements.pageobjects.annotations.Url;
import ru.training.at.hw7.model.User;
import ru.training.at.hw7.pages.HomePage;
import ru.training.at.hw7.pages.MetalAndColorsPage;
@JSite("https://jdi-testing.github.io/jdi-light/")
public class JdiSite {
@Url("/index.html")
@Title(value = "Home", validate = CONTAINS)
public static HomePage homePage;
@Url("/metals-colors.html")
@Title("Metal and Colors")
public static MetalAndColorsPage metalAndColorsPage;
public static void open() {
homePage.open();
}
public static void login(User user) {
HomePage.loginUser(user);
}
}
<file_sep>/src/test/java/ru/training/at/hw5/tests/steps/ThenSteps.java
package ru.training.at.hw5.tests.steps;
import io.cucumber.datatable.DataTable;
import io.cucumber.java.en.Then;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.testng.Assert;
import ru.training.at.hw5.context.TestContext;
import ru.training.at.hw5.pages.DifferentElementsPage;
import ru.training.at.hw5.pages.UserTablePage;
public class ThenSteps {
DifferentElementsPage differentElementsPage = new DifferentElementsPage(TestContext.getInstance().getDriver());
UserTablePage userTablePage = new UserTablePage(TestContext.getInstance().getDriver());
@Then("There are {int} logs in Log section on Different Elements Page")
public void thereAreLogsInLogSection(int expectedNumberOfLogs) {
Assert.assertEquals(differentElementsPage.getLogSection().getLogsSize(), expectedNumberOfLogs);
}
@Then("There is {string} text in the row #{int}")
public void thereAreTextsInTheRow(String expectedLogText, int i) {
String currentLog = differentElementsPage.getLogSection().getLogTexts().get(i - 1);
Assert.assertTrue(currentLog.contains(expectedLogText));
}
@Then("{string} page should be opened")
public void pageShouldBeOpened(String pageTitle) {
String actualTitle = userTablePage.getTitle();
Assert.assertEquals(actualTitle, pageTitle);
}
@Then("{int} Number Type Dropdowns should be displayed on Users Table on User Table Page")
public void numberTypeDropdownsShouldBeDisplayedOnOnUserTablePage(int expectedNumberOfDropdowns) {
Assert.assertEquals(userTablePage.getDropdowns().size(), expectedNumberOfDropdowns);
}
@Then("{int} Usernames should be displayed on Users Table on User Table Page")
public void usernamesShouldBeDisplayedOnUserTablePage(int expectedNumberOfUsernames) {
Assert.assertEquals(userTablePage.getUserNames().size(), expectedNumberOfUsernames);
}
@Then("{int} Description texts under images should be displayed on Users Table on User Table Page")
public void descriptionTextsUnderImagesShouldBeDisplayedOnUserTablePage(int expectedNumberOfDescriptions) {
Assert.assertEquals(userTablePage.getDescriptionsTexts().size(), expectedNumberOfDescriptions);
}
@Then("{int} checkboxes should be displayed on Users Table on User Table Page")
public void checkboxesShouldBeDisplayedOnUsersTablePage(int expectedNumberOfCheckboxes) {
Assert.assertEquals(userTablePage.getCheckboxes().size(), expectedNumberOfCheckboxes);
}
@Then("User table should contain following values:")
public void userTableShouldContainFollowingValues(DataTable dataTable) {
List<Object> expectedTable = dataTable.asList(List.class).subList(1, 6);
List<List<String>> actualTable = new ArrayList<>();
for (int i = 0; i < expectedTable.size(); i++) {
actualTable.add(Arrays.asList(userTablePage.getNumbers().get(i),
userTablePage.getUserNames().get(i),
userTablePage.getDescriptionsTexts().get(i)));
}
Assert.assertEquals(actualTable, expectedTable);
}
@Then("droplist should contain values in column Type for user {string}")
public void droplistShouldContainValuesInColumnTypeForUser(String user, DataTable dataTable) {
List<String> expectedTable = dataTable.asList().subList(1, 4);
List<String> actualTable = userTablePage.getDropdownTextsForUser(user);
Assert.assertEquals(actualTable, expectedTable);
}
}
<file_sep>/src/test/java/ru/training/at/hw4/data/FailTestData.java
package ru.training.at.hw4.data;
public class FailTestData {
public static final String WRONG_PAGE_TITLE = "WRONG!! Home Page";
}
<file_sep>/src/test/java/ru/training/at/hw7/data/TestData.java
package ru.training.at.hw7.data;
public class TestData {
public static final String METAL_AND_COLORS_PAGE_TITLE = "Metal and Colors";
public static final String PATH_TO_TEST_DATA =
"src/test/resources/hw7/JDI_ex8_metalsColorsDataSet.json";
}
<file_sep>/src/test/java/ru/training/at/hw1/tests/CalculatorDivisionTest.java
package ru.training.at.hw1.tests;
import org.testng.Assert;
import org.testng.annotations.Test;
import ru.training.at.hw1.CalculatorTestDataProvider;
import ru.training.at.hw1.GeneralConditions;
public class CalculatorDivisionTest extends GeneralConditions {
@Test(dataProvider = "LongTestData", dataProviderClass = CalculatorTestDataProvider.class)
public void testDivisionLong(long x, long y) {
long expected = x / y;
Assert.assertEquals(calculator.div(x, y), expected);
}
@Test(dataProvider = "DoubleTestData", dataProviderClass = CalculatorTestDataProvider.class)
public void testDivisionDouble(double x, double y) {
double expected = x / y;
Assert.assertEquals(calculator.div(x, y), expected);
}
@Test(dataProvider = "DataForDivisionByZero",
dataProviderClass = CalculatorTestDataProvider.class,
expectedExceptions = NumberFormatException.class)
public void testDivisionByZero(long x, long y) {
calculator.div(x, y);
}
}
<file_sep>/src/test/java/ru/training/at/hw7/utils/UserManager.java
package ru.training.at.hw7.utils;
import static ru.training.at.hw7.data.UserData.getFullName;
import static ru.training.at.hw7.data.UserData.getLogin;
import static ru.training.at.hw7.data.UserData.getPassword;
import ru.training.at.hw7.model.User;
public class UserManager {
public static User createUser() {
return new User(getLogin(), getPassword(), getFullName());
}
}
<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.epam.tc</groupId>
<artifactId>aleksandr_kashin</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<testng.version>7.4.0</testng.version>
<maven-checkstyle-plugin.version>3.1.2</maven-checkstyle-plugin.version>
<checkstyle.version>8.43</checkstyle.version>
<calculator.version>1.0</calculator.version>
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
<webdriver-factory.version>4.4</webdriver-factory.version>
<selenium-java.version>4.0.0-beta-4</selenium-java.version>
<webdrivermanager.version>4.4.3</webdrivermanager.version>
<allure-testng.version>2.13.2</allure-testng.version>
<aspectj.version>1.9.6</aspectj.version>
<allure-maven.version>2.10.0</allure-maven.version>
<slf4j-simple.version>1.7.30</slf4j-simple.version>
<commons-lang3.version>3.12.0</commons-lang3.version>
<assertj.version>3.19.0</assertj.version>
<cucumber.version>6.10.4</cucumber.version>
<jdi-light.version>1.3.12</jdi-light.version>
<additionAndSubtractionTestsXML>src/test/resources/runAdditionAndSubtractionTests.xml
</additionAndSubtractionTestsXML>
<multiplicationAndDivisionTestsXML>src/test/resources/runMultiplicationAndDivisionTests.xml
</multiplicationAndDivisionTestsXML>
<allTestsXML>src/test/resources/runAllTests.xml</allTestsXML>
<allTestsHomework2XML>src/test/resources/runAllTestsHomeWork2.xml</allTestsHomework2XML>
<allTestsHomework3XML>src/test/resources/runAllTestsHomeWork3.xml</allTestsHomework3XML>
<allTestsHomework4XML>src/test/resources/runAllTestsHomeWork4.xml</allTestsHomework4XML>
<allTestsHomework5XML>src/test/resources/runAllTestsHomeWork5.xml</allTestsHomework5XML>
<allTestsHomework6XML>src/test/resources/runAllTestsHomeWork6.xml</allTestsHomework6XML>
<allTestsHomework7XML>src/test/resources/runAllTestsHomeWork7.xml</allTestsHomework7XML>
</properties>
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.epam.tat.module4</groupId>
<artifactId>calculator</artifactId>
<version>${calculator.version}</version>
<scope>system</scope>
<systemPath>${pom.basedir}/lib/calculator-1.0.jar</systemPath>
</dependency>
<dependency>
<groupId>ru.stqa.selenium</groupId>
<artifactId>webdriver-factory</artifactId>
<version>${webdriver-factory.version}</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>${selenium-java.version}</version>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>${webdrivermanager.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-testng</artifactId>
<version>${allure-testng.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>${slf4j-simple.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>${cucumber.version}</version>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-testng</artifactId>
<version>${cucumber.version}</version>
</dependency>
<dependency>
<groupId>com.epam.jdi</groupId>
<artifactId>jdi-light-html</artifactId>
<version>${jdi-light.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>${maven-checkstyle-plugin.version}</version>
<dependencies>
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
<version>${checkstyle.version}</version>
</dependency>
</dependencies>
<configuration>
<configLocation>
https://raw.githubusercontent.com/DmitryKhodakovsky/epam-training-center-code-checkers-configurations/main/checkstyle/checkstyle.xml
</configLocation>
<encoding>UTF-8</encoding>
<includeTestSourceDirectory>true</includeTestSourceDirectory>
<violationSeverity>warning</violationSeverity>
<consoleOutput>true</consoleOutput>
</configuration>
<executions>
<execution>
<id>validate</id>
<phase>validate</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>additionAndSubtractionTests</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>${additionAndSubtractionTestsXML}</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>multiplicationAndDivisionTests</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>${multiplicationAndDivisionTestsXML}</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>allTests</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>${allTestsXML}</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>allTestsHomeWork2</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>${allTestsHomework2XML}</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>allTestsHomeWork3</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>${allTestsHomework3XML}</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>allTestsHomeWork4</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<argLine>
-javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
</argLine>
<suiteXmlFiles>
<suiteXmlFile>${allTestsHomework4XML}</suiteXmlFile>
</suiteXmlFiles>
</configuration>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-maven</artifactId>
<version>${allure-maven.version}</version>
<configuration>
<reportVersion>${allure-testng.version}</reportVersion>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>allTestsHomeWork5</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<argLine>
-javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
-Dcucumber.options="--plugin io.qameta.allure.cucumber5jvm.AllureCucumber5JvmO"
</argLine>
<suiteXmlFiles>
<suiteXmlFile>${allTestsHomework5XML}</suiteXmlFile>
</suiteXmlFiles>
</configuration>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-maven</artifactId>
<version>${allure-maven.version}</version>
<configuration>
<reportVersion>${allure-testng.version}</reportVersion>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>allTestsHomeWork6</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<argLine>
-javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
</argLine>
<suiteXmlFiles>
<suiteXmlFile>${allTestsHomework6XML}</suiteXmlFile>
</suiteXmlFiles>
</configuration>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-maven</artifactId>
<version>${allure-maven.version}</version>
<configuration>
<reportVersion>${allure-testng.version}</reportVersion>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>allTestsHomeWork7</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<argLine>
-javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
</argLine>
<suiteXmlFiles>
<suiteXmlFile>${allTestsHomework7XML}</suiteXmlFile>
</suiteXmlFiles>
</configuration>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-maven</artifactId>
<version>${allure-maven.version}</version>
<configuration>
<reportVersion>${allure-testng.version}</reportVersion>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<reporting>
<excludeDefaults>true</excludeDefaults>
<plugins>
<plugin>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-maven</artifactId>
<version>${allure-maven.version}</version>
<configuration>
<reportVersion>${allure-testng.version}</reportVersion>
</configuration>
</plugin>
</plugins>
</reporting>
</project>
<file_sep>/src/test/java/ru/training/at/hw5/pages/HomePage.java
package ru.training.at.hw5.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import ru.training.at.hw5.data.TestData;
import ru.training.at.hw5.model.User;
import ru.training.at.hw5.utils.UserManager;
public class HomePage extends AbstractPage {
@FindBy(id = "user-icon")
private static WebElement userIcon;
@FindBy(id = "name")
private static WebElement name;
@FindBy(id = "password")
private static WebElement password;
@FindBy(id = "login-button")
private static WebElement loginButton;
public HomePage(WebDriver driver) {
super(driver);
}
public HomePage openHomePage() {
driver.get(TestData.PAGE_URL);
return this;
}
public LoggedInHomePage logIn() {
User user = UserManager.createUser();
userIcon.click();
name.sendKeys(user.getUsername());
password.sendKeys(<PASSWORD>());
loginButton.click();
return new LoggedInHomePage(driver);
}
}
<file_sep>/src/test/java/ru/training/at/hw7/tests/TestsInit.java
package ru.training.at.hw7.tests;
import static com.epam.jdi.light.driver.WebDriverUtils.killAllSeleniumDrivers;
import com.epam.jdi.light.elements.init.PageFactory;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.asserts.SoftAssert;
import ru.training.at.hw7.JdiSite;
import ru.training.at.hw7.model.User;
import ru.training.at.hw7.utils.UserManager;
public class TestsInit {
protected static SoftAssert softAssert = new SoftAssert();
protected static User user = UserManager.createUser();
@BeforeSuite(alwaysRun = true)
public static void setUp() {
PageFactory.initSite(JdiSite.class);
JdiSite.open();
JdiSite.login(user);
}
@AfterSuite(alwaysRun = true)
public static void tearDown() {
killAllSeleniumDrivers();
}
}
<file_sep>/src/test/java/ru/training/at/hw7/model/User.java
package ru.training.at.hw7.model;
public class User {
private final String login;
private final String password;
private final String fullName;
public User(String username, String password, String fullName) {
this.login = username;
this.password = <PASSWORD>;
this.fullName = fullName;
}
public String getLogin() {
return login;
}
public String getPassword() {
return <PASSWORD>;
}
public String getFullName() {
return fullName;
}
}
<file_sep>/src/test/java/ru/training/at/hw5/tests/steps/WhenSteps.java
package ru.training.at.hw5.tests.steps;
import io.cucumber.java.en.When;
import ru.training.at.hw5.context.TestContext;
import ru.training.at.hw5.pages.DifferentElementsPage;
import ru.training.at.hw5.pages.LoggedInHomePage;
import ru.training.at.hw5.pages.UserTablePage;
public class WhenSteps {
LoggedInHomePage loggedInHomePage = new LoggedInHomePage(TestContext.getInstance().getDriver());
DifferentElementsPage differentElementsPage = new DifferentElementsPage(TestContext.getInstance().getDriver());
UserTablePage userTablePage = new UserTablePage(TestContext.getInstance().getDriver());
@When("I click on {string} button in Header")
public void click_on_button_in_Header(String linkText) {
loggedInHomePage.clickOnServiceLink(linkText);
}
@When("I click on {string} button in Service dropdown")
public void clickOnButtonInServiceDropdown(String itemInDropdown) {
loggedInHomePage.clickOnALinkInHeader(itemInDropdown);
}
@When("I select {string} checkbox on Different Elements Page")
public void selectCheckboxOnDifferentElementsPage(
String checkboxText) {
differentElementsPage.clickOnCheckbox(checkboxText);
}
@When("I select {string} radio on Different Elements Page")
public void selectRadioOnDifferentElementsPage(String radioText) {
differentElementsPage.clickOnRadio(radioText);
}
@When("I select {string} color in dropdown on Different Elements Page")
public void selectColorInDropdownOnTheDifferentElementsPage(String color) {
differentElementsPage.selectColor(color);
}
@When("I select 'vip' checkbox for {string}")
public void selectVipCheckboxForUserOnUserTablePage(String user) {
userTablePage.clickCheckboxForUser(user);
}
}
<file_sep>/src/test/java/ru/training/at/hw2/ex1/ContentOfTheHomePageTest.java
package ru.training.at.hw2.ex1;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.annotations.Test;
import ru.training.at.hw2.GeneralConditions;
import ru.training.at.hw2.data.TestData;
public class ContentOfTheHomePageTest extends GeneralConditions {
//5. Assert that there are 4 items on the header section are displayed and they have proper texts
@Test(priority = 2)
public void checkHeaderSectionLinks() {
List<WebElement> headerSectionElements = driver.findElements(By
.cssSelector(".nav > li > a"));
//Assert that there are 4 items on the header section are displayed
softAssert.assertEquals(headerSectionElements.size(), TestData.HEADER_LINKS_TEXTS.size());
checkIfElementsAreDisplayed(headerSectionElements);
//Assert that 4 items on the header section have proper texts
compareTexts(headerSectionElements, TestData.HEADER_LINKS_TEXTS);
}
//6. Assert that there are 4 images on the Index Page and they are displayed
@Test(priority = 3)
public void testFourImagesExist() {
//Assert that there are 4 images on the Index Page
final List<WebElement> imagesOnHomePage = driver.findElements(
By.cssSelector("div.benefit-icon"));
softAssert.assertEquals(imagesOnHomePage.size(), TestData.NUMBER_OF_IMAGES);
//Assert that 4 images on the Index Page are displayed
checkIfElementsAreDisplayed(imagesOnHomePage);
}
//7. Assert that there are 4 texts on the Index Page under icons and they have proper text
@Test(priority = 4)
public void checkIfProperTextsAreBelowImages() {
//Assert that there are 4 texts on the Index Page under icons
final List<WebElement> textsBelowImages = driver.findElements(By.cssSelector("span.benefit-txt"));
softAssert.assertEquals(textsBelowImages.size(), TestData.TEXTS_BELOW_IMAGES.size());
//Assert that texts on the Index Page under icons have proper text
compareTexts(textsBelowImages, TestData.TEXTS_BELOW_IMAGES);
}
//8. Assert that there is the iframe with “Frame Button” exist
@Test(priority = 5)
public void checkIfIFrameExists() {
final WebElement iframeLink = driver.findElement(By.tagName("iframe"));
softAssert.assertTrue(iframeLink.isDisplayed());
}
// 9. Switch to the iframe and check that there is “Frame Button” in the iframe
@Test(priority = 6)
public void checkIfFrameButtonExists() {
//Switch to the iframe
driver.switchTo().frame("frame");
WebElement frameButton = driver.findElement(By.id("frame-button"));
// The frame button exists
softAssert.assertTrue(frameButton.isDisplayed());
}
// 10. Switch to original window back
@Test(priority = 7)
public void checkIfSwitchedToOriginalWindow() {
driver.switchTo().defaultContent();
String currentHandle = driver.getWindowHandle();
softAssert.assertEquals(currentHandle, originalHandle);
}
// 11. Assert that there are 5 items in the Left Section are displayed and they have proper text
@Test(priority = 8)
public void checkElementsOnTheLeftSection() {
List<WebElement> elementsOnTheLeftSection = driver.findElements(By
.cssSelector("ul.sidebar-menu > li > a > span"));
//Assert that there are 5 items on the Left Section are displayed
softAssert.assertEquals(elementsOnTheLeftSection.size(),
TestData.LEFT_SECTION_LINKS_TEXTS.size());
checkIfElementsAreDisplayed(elementsOnTheLeftSection);
//Assert that 5 items on the Left Section have proper texts
compareTexts(elementsOnTheLeftSection, TestData.LEFT_SECTION_LINKS_TEXTS);
}
}
<file_sep>/src/test/java/ru/training/at/hw2/GeneralConditions.java
package ru.training.at.hw2;
import io.github.bonigarcia.wdm.WebDriverManager;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import ru.training.at.hw2.data.TestData;
public class GeneralConditions {
protected final SoftAssert softAssert = new SoftAssert();
protected WebDriver driver;
protected String originalHandle;
@BeforeClass
public void setUp() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.navigate().to(TestData.HOME_PAGE_URL);
originalHandle = driver.getWindowHandle();
}
//2. Assert Browser title
@Test
public void checkHomePageTitleText() {
softAssert.assertEquals(driver.getTitle(), TestData.HOME_PAGE_TITLE);
softAssert.assertAll();
}
//3. Perform login
public void performLogIn() {
driver.findElement(By.id("user-icon")).click();
driver.findElement(By.id("name")).sendKeys(TestData.LOGIN);
driver.findElement(By.id("password")).sendKeys(<PASSWORD>);
driver.findElement(By.id("login-button")).click();
}
//4. Assert Username is logged
@Test(priority = 1)
public void checkIfUserIsLoggedIn() {
performLogIn();
String actualUserName = driver.findElement(By.id("user-name")).getText();
softAssert.assertEquals(actualUserName, TestData.USERNAME);
softAssert.assertAll();
}
//12 or 10. Close browser
@AfterClass(alwaysRun = true)
public void tearDown() {
if (null != driver) {
driver.quit();
}
}
public void compareTexts(List<WebElement> webElements, List<String> expectedTexts) {
IntStream.range(0, webElements.size())
.forEachOrdered(index -> softAssert.assertTrue(
webElements.get(index).getText()
.contains(expectedTexts.get(index))
));
softAssert.assertAll();
}
public void checkIfElementsAreDisplayed(List<WebElement> webElements) {
for (WebElement webElement : webElements) {
softAssert.assertTrue(webElement.isDisplayed());
}
softAssert.assertAll();
}
}
<file_sep>/src/test/java/ru/training/at/hw4/utils/UserManager.java
package ru.training.at.hw4.utils;
import static ru.training.at.hw4.data.UserData.getPassword;
import static ru.training.at.hw4.data.UserData.getUserName;
import ru.training.at.hw4.model.User;
public class UserManager {
public static User createUser() {
return new User(getUserName(), getPassword());
}
}
<file_sep>/src/test/java/ru/training/at/hw1/tests/CalculatorAdditionTest.java
package ru.training.at.hw1.tests;
import org.testng.Assert;
import org.testng.annotations.Test;
import ru.training.at.hw1.CalculatorTestDataProvider;
import ru.training.at.hw1.GeneralConditions;
public class CalculatorAdditionTest extends GeneralConditions {
@Test(dataProvider = "LongTestData", dataProviderClass = CalculatorTestDataProvider.class)
public void testAdditionLong(long x, long y) {
long expected = x + y;
Assert.assertEquals(calculator.sum(x, y), expected);
}
@Test(dataProvider = "DoubleTestData", dataProviderClass = CalculatorTestDataProvider.class)
public void testAdditionDouble(double x, double y) {
double expected = x + y;
Assert.assertEquals(calculator.sum(x, y), expected);
}
}
<file_sep>/src/test/java/ru/training/at/hw1/tests/CalculatorMultiplicationTest.java
package ru.training.at.hw1.tests;
import org.testng.Assert;
import org.testng.annotations.Test;
import ru.training.at.hw1.CalculatorTestDataProvider;
import ru.training.at.hw1.GeneralConditions;
public class CalculatorMultiplicationTest extends GeneralConditions {
@Test(dataProvider = "LongTestData", dataProviderClass = CalculatorTestDataProvider.class)
public void testMultiplicationLong(long x, long y) {
long expected = x * y;
Assert.assertEquals(calculator.mult(x, y), expected);
}
@Test(dataProvider = "DoubleTestData", dataProviderClass = CalculatorTestDataProvider.class)
public void testMultiplicationDouble(double x, double y) {
double expected = x * y;
Assert.assertEquals(calculator.mult(x, y), expected);
}
}
<file_sep>/src/test/java/ru/training/at/hw3/tests/steps/DifferentElementsPageSteps.java
package ru.training.at.hw3.tests.steps;
import static org.testng.Assert.assertEquals;
import java.util.List;
import java.util.stream.IntStream;
import org.openqa.selenium.WebElement;
import org.testng.asserts.SoftAssert;
import ru.training.at.hw3.pages.AbstractPage;
import ru.training.at.hw3.pages.DifferentElementsPage;
public class DifferentElementsPageSteps {
private static final SoftAssert softAssert = new SoftAssert();
public static void checkThatDifferentElementsPageIsOpened(AbstractPage page, String expected) {
softAssert.assertEquals(page.getTitle(), expected);
}
public static void checkThatCheckboxesAreUnchecked(DifferentElementsPage page, int waterListNumber,
int windListNumber) {
softAssert.assertFalse(page.waterIsChecked(waterListNumber));
softAssert.assertFalse(page.windIsChecked(windListNumber));
softAssert.assertAll();
}
public static void selectCheckboxes(DifferentElementsPage page, int waterListNumber,
int windListNumber) {
page.clickWaterCheckbox(waterListNumber);
page.clickWindCheckbox(windListNumber);
}
public static void checkThatCheckboxesAreChecked(DifferentElementsPage page, int waterListNumber,
int windListNumber) {
softAssert.assertTrue(page.waterIsChecked(waterListNumber));
softAssert.assertTrue(page.windIsChecked(windListNumber));
softAssert.assertAll();
}
public static void selectRadio(DifferentElementsPage page, int selenListNumber) {
page.selectSelenRadio(selenListNumber);
}
public static void checkThatRadioIsSelected(DifferentElementsPage page, int selenListNumber) {
softAssert.assertTrue(page.selenRadioIsChecked(selenListNumber));
}
public static void selectYellowInDropdown(DifferentElementsPage page, String color) {
page.selectColor(color);
}
public static void checkThatYellowWasSelected(DifferentElementsPage page, String color) {
assertEquals(page.getFirstSelectedColor(), color);
}
public static void checkThatLogsAreDisplayed(DifferentElementsPage page, List<String> expectedTexts) {
List<WebElement> logs = page.getLogs();
softAssert.assertEquals(logs.size(), expectedTexts.size());
for (WebElement webElement : logs) {
softAssert.assertTrue(webElement.isDisplayed());
}
softAssert.assertAll();
}
public static void checkThatLogsHaveProperTexts(DifferentElementsPage page, List<String> expectedTexts) {
List<WebElement> logs = page.getLogs();
IntStream.range(0, logs.size())
.forEachOrdered(index -> softAssert.assertTrue(
logs.get(index).getText()
.contains(expectedTexts.get(index))
));
softAssert.assertAll();
}
}
<file_sep>/src/test/java/ru/training/at/hw3/utils/UserManager.java
package ru.training.at.hw3.utils;
import static ru.training.at.hw3.data.UserData.getPassword;
import static ru.training.at.hw3.data.UserData.getUserName;
import ru.training.at.hw3.model.User;
public class UserManager {
public static User createUser() {
return new User(getUserName(), getPassword());
}
}
<file_sep>/src/test/java/ru/training/at/hw3/data/BaseTestData.java
package ru.training.at.hw3.data;
public class BaseTestData {
public static final String PAGE_URL = "https://jdi-testing.github.io/jdi-light/index.html";
public static final String PAGE_TITLE = "Home Page";
public static final String USERNAME = "<NAME>";
}
|
2b09c58119196d332f6d7e317059ebfae24c3d25
|
[
"Java",
"Maven POM",
"INI"
] | 27
|
INI
|
alexkashin90/AleksandrKashin
|
7bed4e8b7537a4037a7be0b7ffa2dd5ed32a5de2
|
58defafdf4a113877265b568045c40b07e55a77c
|
refs/heads/master
|
<file_sep>package com.br.compras.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;
import com.br.compras.models.ClienteModel;
import com.br.compras.service.ClienteService;
import com.br.compras.service.OnibusService;
@Controller
public class OnibusController {
@Autowired
private OnibusService onibusService;
@GetMapping("/")
public ModelAndView listarOnibus() {
ModelAndView modelAndView = new ModelAndView("onibus.html");
modelAndView.addObject("listaOnibus", onibusService.exibirTodos());
return modelAndView;
}
@GetMapping("/comprar/{id}")
public ModelAndView compraPassagens() {
ModelAndView modelAndView = new ModelAndView("entradaDeCliente.html");
return modelAndView;
}
// @PostMapping("/comprar/{id}")
// public void cadastrarCliente(@PathVariable int id, ClienteModel cliente) {
//
// ClienteService clienteCadastrado = new ClienteService();
// clienteCadastrado.cadastrarCliente(cliente);
// onibusService.cadastrarCliente(id, cliente);
//
// }
@PostMapping("/comprar/{id}")
public void cliente( ClienteModel cliente, @PathVariable int id) {
ClienteService clienteCadastrado = new ClienteService();
clienteCadastrado.cadastrarCliente(cliente);
onibusService.cadastrarCliente(id, cliente);
}
}
<file_sep>package com.br.compras.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import com.br.compras.models.ClienteModel;
import com.br.compras.models.OnibusModel;
@Service
public class OnibusService {
private List<OnibusModel> listaOnibus = new ArrayList<OnibusModel>();
public List<OnibusModel> exibirTodos() {
List<ClienteModel> lista1 = new ArrayList<ClienteModel>();
List<ClienteModel> lista2 = new ArrayList<ClienteModel>();
lista1.add(new ClienteModel("jefferson", "gugugu", 23, 1));
lista2.add(new ClienteModel("bruno", "gugugu", 23, 1));
listaOnibus.add(new OnibusModel(1, "BrunoBus", "sei la", "Uma hora e meia", 20, 20, lista1));
listaOnibus.add(new OnibusModel(2, "BenBus", "Onde eu quizer", "Uma hora ", 20, 20, lista2));
return listaOnibus;
}
public void cadastrarCliente(int id, ClienteModel cliente) {
List<ClienteModel> lista = new ArrayList<ClienteModel>();
OnibusModel onibus = new OnibusModel();
for (OnibusModel onibusModel : listaOnibus) {
if (onibusModel.getId() == id) {
onibus = onibusModel;
}
}
lista = onibus.getListaClientes();
lista.add(cliente);
onibus.setListaClientes(lista);
}
}
|
1690abe77633780a5977539a9147d10141a4953c
|
[
"Java"
] | 2
|
Java
|
JeffersonBaptista/exe-gitAvan-ado_branchs
|
f63b4cf45825299a150b2c70b2a09ff10f7d7a2f
|
33c8c91be1c188ffea4b04f7d36f3dece0ab6cb8
|
refs/heads/master
|
<repo_name>Munesh-Kumar005/React-company-web<file_sep>/src/Sdata.jsx
import web from "../src/images/boot.png";
import web1 from "../src/images/boot.png";
import web2 from "../src/images/boot.png";
import web3 from "../src/images/sql.jpg";
import web4 from "../src/images/php.jpg";
import web5 from "../src/images/sql.jpg";
const Sdata =[
{
imgsrc:web3,
title:"Web Development",
},
{
imgsrc: web4,
title: "Web Development",
},
{
imgsrc: web5,
title: "Web Development",
},
{
imgsrc: web,
title: "Web Development",
},
{
imgsrc: web1,
title: "Web Development",
},
{
imgsrc: web2,
title: "Web Development",
},
];
export default Sdata;<file_sep>/src/Footer.jsx
import React from 'react';
const Footer =()=>{
return(
<>
<footer className="bg-light text-center">
<p>2020 The <NAME> | All Rights Reserved | Terms and condition must be apply</p>
</footer>
</>
);
};
export default Footer;
|
ab1c1df37478dcb2e1da747506ac036f3e29b1c2
|
[
"JavaScript"
] | 2
|
JavaScript
|
Munesh-Kumar005/React-company-web
|
c0ebabdb688f4b1ee1cbe28469f66fa94a3bb6ec
|
7267cb74522e445ece21edaabd075565c3918295
|
refs/heads/master
|
<repo_name>mawyy/Yummical<file_sep>/app/Http/Controllers/MealController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Redirect;
use App\Meal;
use App\Product;
use DB;
class MealController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function index(Request $request) {
//$meals = Meal::all();
$user = $request->user();
$meals = $user->meals()->orderBy('date', 'desc')->get();
$mealsByDate = $meals->groupBy('date');
$tot_cal_meal = 0;
$mealsByDateWithCal = [];
foreach ($mealsByDate as $date => $meals) {
$tot_cal_day = 0;
foreach ($meals as $meal) {
$tot_cal_day += $meal->getCalories();
}
$mealByDateFinal = new \stdClass;
$mealByDateFinal->date = $date;
$mealByDateFinal->meals = $meals;
$mealByDateFinal->dayCalories = $tot_cal_day;
$mealsByDateWithCal[] = $mealByDateFinal;
}
return view('meal')->with('mealsByDateWithCal', $mealsByDateWithCal);
}
/**
* Show a meal
*/
public function show($id) {
$meal = Meal::find($id);
$products = $meal->products;
$tot_cal_meal = $meal->getCalories();
return view('product')
->with('products', $products)
->with('meal', $meal)
->with('tot_cal_meal', $tot_cal_meal);
}
/**
* Store a meal
*/
public function store(Request $request) {
$rules = [
'meal' => 'required|string',
'date' => 'required|date',
];
$validator = Validator::make($request->all(), $rules, [
'meal.required' => 'Please enter a correct type of meal',
'meal.string' => 'Please enter a correct type of meal',
'date.required' => 'Please enter a correct date (dd/mm/yyyy)',
'date.date' => 'Please enter a correct date (dd/mm/yyyy)',
]);
if ($validator->fails()) {
return redirect('/meal')
->withInput()
->withErrors($validator);
}
$meal = new Meal;
$meal->type = $request->meal;
$meal->date = $request->date;
$meal->save();
$user = $request->user();
$user->meals()->attach($meal->id);
return Redirect::back()->with('success','Meal created successfully!');
}
/**
* Delete a meal
*/
public function deleteMeal($id, Request $request) {
$user = $request->user();
$user->meals()->detach($id);
Meal::destroy($id);
return Redirect::back()->with('success','Meal deleted successfully!');
}
/**
* Delete a product
*/
public function deleteProduct($meal_id, $product_id) {
$meal = Meal::findOrFail($meal_id);
//$meal->products()->detach($product_id);
DB::table($meal->products()->getTable())
->where('meal_id', '=', $meal_id)
->where('product_id', '=', $product_id)
->limit(1)
->delete();
return Redirect::back()->with('success','Food deleted successfully!');
}
}<file_sep>/app/Http/Controllers/ProductController.php
<?php
namespace App\Http\Controllers;
use Request;
use Validator;
use Redirect;
use App\Meal;
use App\Product;
use DB;
use Builder;
use Model;
class ProductController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Store a product
*/
public function store($id) {
$value = request::all();
$meal = Meal::findOrFail($id);
$rules = [
'code' => 'required|string',
];
$validator = Validator::make($value, $rules, [
'code.required' => 'Please enter a code',
'code.string' => 'Please enter a correct code',
]);
if ($validator->fails()) {
return redirect::back()
->withInput()
->withErrors($validator);
}
$url = 'https://fr.openfoodfacts.org/api/v0/produit/' . $value['code'] .'.json';
$data = json_decode(file_get_contents($url), true);
if (empty($data['product']['product_name'])) {
return Redirect::back()->with('error','Please enter a correct code');
}
$product = Product::where('code', $value['code'])->first();
if ($product == null) {
$product = new Product;
$hasImage = isset($data['product']['image_url']);
$product->name = $data['product']['product_name'];
$product->code = $data['code'];
$product->url = $hasImage ? $data['product']['image_url'] : "";
if (isset ($data['product']['nutriments']['energy_value'])) {
if ($data['product']['nutriments']['energy_unit'] == 'kJ') {
$product->calorie = ($data['product']['nutriments']['energy_value']) / 4.184;
} else {
$product->calorie = $data['product']['nutriments']['energy_value'];
}
} else {
$product->calorie = 0;
}
$product->save();
}
$meal->products()->attach($product->id);
return Redirect::back()->with('success','Product added successfully!');
}
}
<file_sep>/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
if(!\Auth::check()){
return view('welcome');
} else {
return redirect('/meal');
}
});
Auth::routes();
Route::prefix('meal')->name('meal.')->group(function () {
Route::get('/', 'MealController@index')->name('index');
Route::post('/', 'MealController@store')->name('store');
Route::delete('/{id}', 'MealController@deleteMeal')->name('deleteMeal');
Route::get('/{id}/edit', 'MealController@show')->name('index');
Route::post('/{id}/edit', 'ProductController@store')->name('storeProducts');
Route::delete('/{meal_id}/{product_id}', 'MealController@deleteProduct')->name('deleteProduct');
});
Route::get('/statistics', 'StatisticsController@statistics')->name('statistics');<file_sep>/app/Http/Controllers/StatisticsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Product;
use DB;
class StatisticsController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
// SELECT distinct products.*
// FROM `products`
// inner join meal_product on products.id = meal_product.product_id
// order by calorie desc
// limit 5
$this->middleware('auth');
}
// SELECT distinct products.*
// FROM `products`
// inner join meal_product on products.id = meal_product.product_id
// inner join meal_user on meal_user.meal_id = meal_product.meal_id
// where meal_user.user_id = 1
// order by calorie desc
private function show5HigherCal($user) {
return Product::join('meal_product', 'products.id', '=', 'meal_product.product_id')
->join('meal_user', 'meal_user.meal_id', '=', 'meal_product.meal_id')
->where('meal_user.user_id', '=', $user->id )
->orderBy('calorie', 'desc')
->select('products.*')
->limit(5)
->distinct()
->get();
}
private function show5LowerCal($user) {
return Product::join('meal_product', 'products.id', '=', 'meal_product.product_id')
->join('meal_user', 'meal_user.meal_id', '=', 'meal_product.meal_id')
->where('meal_user.user_id', '=', $user->id )
->orderBy('calorie', 'asc')
->select('products.*')
->limit(5)
->distinct()
->get();
}
// SELECT products.* , sum(calorie) as total_calories
// FROM `products`
// inner join meal_product on products.id = meal_product.product_id
// group by products.id
// order by total_calories desc
// limit 5
private function show5HigherCalTotal($user) {
return Product::join('meal_product', 'products.id', '=', 'meal_product.product_id')
->join('meal_user', 'meal_user.meal_id', '=', 'meal_product.meal_id')
->where('meal_user.user_id', '=', $user->id )
->select('products.*', DB::raw('SUM(calorie) as total_calories'))
->groupBy('products.id')
->orderByRaw(DB::raw('SUM(calorie) desc'))
->limit(5)
->get();
}
public function statistics(Request $request) {
$user = $request->user();
$show5HigherCal = $this->show5HigherCal($user);
$show5LowerCal = $this->show5LowerCal($user);
$show5HigherCalTotal = $this->show5HigherCalTotal($user);
return view('statistics')
->with('productsWith5HigherCal', $show5HigherCal)
->with('productsWith5LowerCal', $show5LowerCal)
->with('productsWith5HigherCalTotal', $show5HigherCalTotal);
}
}
<file_sep>/app/Meal.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Meal extends Model
{
public function products() {
return $this->belongsToMany('App\Product');
}
public function getCalories() {
$products = $this->products;
$total_cal = 0;
foreach ($products as $product) {
$total_cal += $product->calorie;
}
return $total_cal;
}
}
|
be6092f1baeddd97193f4274566f50b2c2cc7d3f
|
[
"PHP"
] | 5
|
PHP
|
mawyy/Yummical
|
47b17f6f67119c31f50c282a2087abda3acb4969
|
a85af4d78b43decde061c5a8043e86a695e1ecf1
|
refs/heads/master
|
<repo_name>smilingthax/pdftopdf<file_sep>/qpdf_pdftopdf_processor.h
#ifndef QPDF_PDFTOPDF_PROCESSOR_H
#define QPDF_PDFTOPDF_PROCESSOR_H
#include "pdftopdf_processor.h"
#include <qpdf/QPDF.hh>
class QPDF_PDFTOPDF_PageHandle : public PDFTOPDF_PageHandle {
public:
virtual PageRect getRect() const;
virtual void add_border_rect(const PageRect &rect,BorderType border,float fscale);
virtual void add_subpage(const std::shared_ptr<PDFTOPDF_PageHandle> &sub,float xpos,float ypos,float scale,const PageRect *crop=NULL);
virtual void mirror();
virtual void rotate(Rotation rot);
void debug(const PageRect &rect,float xpos,float ypos);
private:
bool isExisting() const;
QPDFObjectHandle get(); // only once!
private:
friend class QPDF_PDFTOPDF_Processor;
// 1st mode: existing
QPDF_PDFTOPDF_PageHandle(QPDFObjectHandle page,int orig_no=-1);
QPDFObjectHandle page;
int no;
// 2nd mode: create new
QPDF_PDFTOPDF_PageHandle(QPDF *pdf,float width,float height);
std::map<std::string,QPDFObjectHandle> xobjs;
std::string content;
Rotation rotation;
};
class QPDF_PDFTOPDF_Processor : public PDFTOPDF_Processor {
public:
virtual bool loadFile(FILE *f,ArgOwnership take=WillStayAlive);
virtual bool loadFilename(const char *name);
// TODO: virtual bool may_modify/may_print/?
virtual bool check_print_permissions();
// virtual bool setProcess(const ProcessingParameters ¶m) =0;
virtual std::vector<std::shared_ptr<PDFTOPDF_PageHandle>> get_pages();
virtual std::shared_ptr<PDFTOPDF_PageHandle> new_page(float width,float height);
virtual void add_page(std::shared_ptr<PDFTOPDF_PageHandle> page,bool front);
virtual void multiply(int copies,bool collate);
virtual void addCM(const char *defaulticc,const char *outputicc);
virtual void setComments(const std::vector<std::string> &comments);
virtual void emitFile(FILE *dst,ArgOwnership take=WillStayAlive);
virtual void emitFilename(const char *name);
private:
void closeFile();
void error(const char *fmt,...);
void start();
private:
std::unique_ptr<QPDF> pdf;
std::vector<QPDFObjectHandle> orig_pages;
bool hasCM;
std::string extraheader;
};
#endif
<file_sep>/pptypes.cc
#include "pptypes.h"
#include <utility>
#include <stdio.h>
#include <assert.h>
void Position_dump(Position pos) // {{{
{
static const char *pstr[3]={"Left/Bottom","Center","Right/Top"};
if ( (pos<LEFT)||(pos>RIGHT) ) {
fprintf(stderr,"(bad position: %d)",pos);
} else {
fputs(pstr[pos+1],stderr);
}
}
// }}}
void Position_dump(Position pos,Axis axis) // {{{
{
assert( (axis==Axis::X)||(axis==Axis::Y) );
if ( (pos<LEFT)||(pos>RIGHT) ) {
fprintf(stderr,"(bad position: %d)",pos);
return;
}
if (axis==Axis::X) {
static const char *pxstr[3]={"Left","Center","Right"};
fputs(pxstr[pos+1],stderr);
} else {
static const char *pystr[3]={"Bottom","Center","Top"};
fputs(pystr[pos+1],stderr);
}
}
// }}}
void Rotation_dump(Rotation rot) // {{{
{
static const char *rstr[4]={"0 deg","90 deg","180 deg","270 deg"}; // CCW
if ( (rot<ROT_0)||(rot>ROT_270) ) {
fprintf(stderr,"(bad rotation: %d)",rot);
} else {
fputs(rstr[rot],stderr);
}
}
// }}}
Rotation operator+(Rotation lhs,Rotation rhs) // {{{
{
return (Rotation)(((int)lhs+(int)rhs)%4);
}
// }}}
Rotation operator-(Rotation lhs,Rotation rhs) // {{{
{
return (Rotation)((((int)lhs-(int)rhs)%4+4)%4);
}
// }}}
Rotation operator-(Rotation rhs) // {{{
{
return (Rotation)((4-(int)rhs)%4);
}
// }}}
void BorderType_dump(BorderType border) // {{{
{
if ( (border<NONE)||(border==1)||(border>TWO_THICK) ) {
fprintf(stderr,"(bad border: %d)",border);
} else {
static const char *bstr[6]={"None",NULL,"one thin","one thick","two thin","two thick"};
fputs(bstr[border],stderr);
}
}
// }}}
void PageRect::rotate_move(Rotation r,float pwidth,float pheight) // {{{
{
#if 1
if (r>=ROT_180) {
std::swap(top,bottom);
std::swap(left,right);
}
if ( (r==ROT_90)||(r==ROT_270) ) {
const float tmp=bottom;
bottom=left;
left=top;
top=right;
right=tmp;
std::swap(width,height);
std::swap(pwidth,pheight);
}
if ( (r==ROT_90)||(r==ROT_180) ) {
left=pwidth-left;
right=pwidth-right;
}
if ( (r==ROT_270)||(r==ROT_180) ) {
top=pheight-top;
bottom=pheight-bottom;
}
#else
switch (r) {
case ROT_0: // no-op
break;
case ROT_90:
const float tmp0=bottom;
bottom=left;
left=pheight-top;
top=right;
right=pheight-tmp0;
std::swap(width,height);
break;
case ROT_180:
const float tmp1=left;
left=width-right;
right=width-left;
const float tmp2=top;
top=pheight-bottom;
bottom=pheight-tmp2;
break;
case ROT_270:
const float tmp3=top;
top=pwidth-left;
left=bottom;
bottom=pwidth-right;
right=tmp3;
std::swap(width,height);
break;
}
#endif
}
// }}}
void PageRect::scale(float mult) // {{{
{
if (mult==1.0) {
return;
}
assert(mult!=0.0);
bottom*=mult;
left*=mult;
top*=mult;
right*=mult;
width*=mult;
height*=mult;
}
// }}}
void PageRect::translate(float tx,float ty) // {{{
{
left+=tx;
bottom+=ty;
right+=tx;
top+=ty;
}
// }}}
void PageRect::set(const PageRect &rhs) // {{{
{
if (!std::isnan(rhs.top)) top=rhs.top;
if (!std::isnan(rhs.left)) left=rhs.left;
if (!std::isnan(rhs.right)) right=rhs.right;
if (!std::isnan(rhs.bottom)) bottom=rhs.bottom;
}
// }}}
void PageRect::dump() const // {{{
{
fprintf(stderr,"top: %f, left: %f, right: %f, bottom: %f\n"
"width: %f, height: %f\n",
top,left,right,bottom,
width,height);
}
// }}}
<file_sep>/pdftopdf_processor.h
#ifndef PDFTOPDF_PROCESSOR_H
#define PDFTOPDF_PROCESSOR_H
#include "pptypes.h"
#include "nup.h"
#include "intervalset.h"
#include <vector>
#include <string>
enum BookletMode { BOOKLET_OFF, BOOKLET_ON, BOOKLET_JUSTSHUFFLE };
struct ProcessingParameters {
ProcessingParameters()
: jobId(0),numCopies(1),
user(0),title(0),
fitplot(false),
orientation(ROT_0),normal_landscape(ROT_270),
duplex(false),
border(NONE),
reverse(false),
// pageLabel(NULL),
evenPages(true),oddPages(true),
mirror(false),
xpos(CENTER),ypos(CENTER),
collate(false),
evenDuplex(false),
booklet(BOOKLET_OFF),bookSignature(-1),
emitJCL(true),deviceCopies(1),deviceReverse(false),
deviceCollate(false),setDuplex(false)
{
page.width=612.0; // letter
page.height=792.0;
page.top=page.height-36.0;
page.bottom=36.0;
page.left=18.0;
page.right=page.width-18.0;
// everything
pageRange.add(1);
pageRange.finish();
}
int jobId, numCopies;
const char *user, *title; // will stay around
bool fitplot;
PageRect page;
Rotation orientation,normal_landscape; // normal_landscape (i.e. default direction) is e.g. needed for number-up=2
bool duplex;
BorderType border;
NupParameters nup;
bool reverse;
// std::string pageLabel; // or NULL? must stay/dup!
bool evenPages,oddPages;
IntervalSet pageRange;
bool mirror;
Position xpos,ypos;
bool collate;
bool evenDuplex; // make number of pages a multiple of 2
BookletMode booklet;
int bookSignature;
// ppd/jcl changes
bool emitJCL;
int deviceCopies;
bool deviceReverse;
bool deviceCollate;
bool setDuplex;
// unsetMirror (always)
// helper functions
bool withPage(int outno) const; // 1 based
void dump() const;
};
#include <stdio.h>
#include <memory>
enum ArgOwnership { WillStayAlive,MustDuplicate,TakeOwnership };
class PDFTOPDF_PageHandle {
public:
virtual ~PDFTOPDF_PageHandle() {}
virtual PageRect getRect() const =0;
// fscale: inverse_scale (from nup, fitplot)
virtual void add_border_rect(const PageRect &rect,BorderType border,float fscale) =0;
// TODO?! add standalone crop(...) method (not only for subpages)
virtual void add_subpage(const std::shared_ptr<PDFTOPDF_PageHandle> &sub,float xpos,float ypos,float scale,const PageRect *crop=NULL) =0;
virtual void mirror() =0;
virtual void rotate(Rotation rot) =0;
};
// TODO: ... error output?
class PDFTOPDF_Processor { // abstract interface
public:
virtual ~PDFTOPDF_Processor() {}
// TODO: ... qpdf wants password at load time
virtual bool loadFile(FILE *f,ArgOwnership take=WillStayAlive) =0;
virtual bool loadFilename(const char *name) =0;
// TODO? virtual bool may_modify/may_print/?
virtual bool check_print_permissions() =0;
virtual std::vector<std::shared_ptr<PDFTOPDF_PageHandle>> get_pages() =0; // shared_ptr because of type erasure (deleter)
virtual std::shared_ptr<PDFTOPDF_PageHandle> new_page(float width,float height) =0;
virtual void add_page(std::shared_ptr<PDFTOPDF_PageHandle> page,bool front) =0; // at back/front -- either from get_pages() or new_page()+add_subpage()-calls (or [also allowed]: empty)
// void remove_page(std::shared_ptr<PDFTOPDF_PageHandle> ph); // not needed: we construct from scratch, at least conceptually.
virtual void multiply(int copies,bool collate) =0;
virtual void addCM(const char *defaulticc,const char *outputicc) =0;
virtual void setComments(const std::vector<std::string> &comments) =0;
virtual void emitFile(FILE *dst,ArgOwnership take=WillStayAlive) =0;
virtual void emitFilename(const char *name) =0; // NULL -> stdout
};
class PDFTOPDF_Factory {
public:
// never NULL, but may throw.
static PDFTOPDF_Processor *processor();
};
//bool checkBookletSignature(int signature) { return (signature%4==0); }
std::vector<int> bookletShuffle(int numPages,int signature=-1);
// This is all we want:
bool processPDFTOPDF(PDFTOPDF_Processor &proc,ProcessingParameters ¶m);
#endif
<file_sep>/qpdf_cm.cc
#include "qpdf_cm.h"
#include <stdio.h>
#include <assert.h>
#include <stdexcept>
// TODO? instead use qpdf's StreamDataProvider, FileInputSource, Buffer etc.
static std::string load_file(const char *filename) // {{{
{
if (!filename) {
throw std::invalid_argument("NULL filename not allowed");
}
FILE *f=fopen(filename,"r");
if (!f) {
throw std::runtime_error(std::string("file ") + filename + " could not be opened");
}
const int bsize=2048;
int pos=0;
std::string ret;
while (!feof(f)) {
ret.resize(pos+bsize);
int res=fread(&ret[pos],1,bsize,f);
pos+=res;
if (res<bsize) {
ret.resize(pos);
break;
}
}
fclose(f);
return ret;
}
// }}}
// TODO?
// TODO? test
bool hasOutputIntent(QPDF &pdf) // {{{
{
auto catalog=pdf.getRoot();
if (!catalog.hasKey("/OutputIntents")) {
return false;
}
return true; // TODO?
}
// }}}
// TODO: test
// TODO? find existing , replace and return (?)
void addOutputIntent(QPDF &pdf,const char *filename) // {{{
{
std::string icc=load_file(filename);
// TODO: check icc fitness
// ICC data, subject to "version limitations" per pdf version...
QPDFObjectHandle outicc=QPDFObjectHandle::newStream(&pdf,icc);
auto sdict=outicc.getDict();
sdict.replaceKey("/N",QPDFObjectHandle::newInteger(4)); // must match ICC
// /Range ? // must match ICC, default [0.0 1.0 ...]
// /Alternate ? (/DeviceCMYK for N=4)
auto intent=QPDFObjectHandle::parse(
"<<"
" /Type /OutputIntent" // Must be so (the standard requires).
" /S /GTS_PDFX" // Must be so (the standard requires).
" /OutputCondition (Commercial and specialty printing)" // TODO: Customize [optional(?)]
" /Info (none)" // TODO: Customize
" /OutputConditionIdentifier (CGATS TR001)" // TODO: FIXME: Customize
" /RegistryName (http://www.color.org)" // Must be so (the standard requires).
" /DestOutputProfile null "
">>");
intent.replaceKey("/DestOutputProfile",outicc);
auto catalog=pdf.getRoot();
if (!catalog.hasKey("/OutputIntents")) {
catalog.replaceKey("/OutputIntents",QPDFObjectHandle::newArray());
}
catalog.getKey("/OutputIntents").appendItem(intent);
}
// }}}
/* for color management:
Use /DefaultGray, /DefaultRGB, /DefaultCMYK ... from *current* resource dictionary ...
i.e. set
/Resources <<
/ColorSpace << --- can use just one indirect ref for this (probably)
/DefaultRGB [/ICCBased 5 0 R] ... sensible use is sRGB for DefaultRGB, etc.
>>
>>
for every page (what with form /XObjects?) and most importantly RGB (leave CMYK, Gray for now, as this is already printer native(?))
? also every form XObject, pattern, type3 font, annotation appearance stream(=form xobject +X)
? what if page already defines /Default? -- probably keep!
*/
// TODO? test
void addDefaultRGB(QPDF &pdf,QPDFObjectHandle srcicc) // {{{
{
srcicc.assertStream();
auto pages=pdf.getAllPages();
for (auto it=pages.begin(),end=pages.end();it!=end;++it) {
if (!it->hasKey("/Resources")) {
it->replaceKey("/Resources",QPDFObjectHandle::newDictionary());
}
auto rdict=it->getKey("/Resources");
if (!rdict.hasKey("/ColorSpace")) {
rdict.replaceKey("/ColorSpace",QPDFObjectHandle::newDictionary());
}
auto cdict=rdict.getKey("/ColorSpace");
if (!cdict.hasKey("/DefaultRGB")) {
cdict.replaceKey("/DefaultRGB",QPDFObjectHandle::parse("[/ICCBased ]"));
cdict.getKey("/DefaultRGB").appendItem(srcicc);
}
}
}
// }}}
// TODO? test
// TODO: find existing , replace and return (?)
// TODO: check icc fitness
QPDFObjectHandle setDefaultICC(QPDF &pdf,const char *filename) // {{{
{
// TODO: find existing , replace and return (?)
std::string icc=load_file(filename);
// TODO: check icc fitness
// ICC data, subject to "version limitations" per pdf version...
QPDFObjectHandle ret=QPDFObjectHandle::newStream(&pdf,icc);
auto sdict=ret.getDict();
sdict.replaceKey("/N",QPDFObjectHandle::newInteger(3)); // must match ICC
// /Range ? // must match ICC, default [0.0 1.0 ...]
// /Alternate ? (/DeviceRGB for N=3)
return ret;
}
// }}}
<file_sep>/Makefile
SOURCES=pdftopdf.cc pdftopdf_jcl.cc pdftopdf_processor.cc qpdf_pdftopdf_processor.cc pptypes.cc nup.cc intervalset.cc qpdf_tools.cc qpdf_xobject.cc qpdf_pdftopdf.cc qpdf_cm.cc
EXEC=pt
#CXX=/home/thobi/dls/gstlfilt/gfilt
#CFLAGS=-O3 -funroll-all-loops -finline-functions -Wall -g
CFLAGS=-Wall -g
CXXFLAGS=-std=c++0x -DDEBUG
LDFLAGS=-g
CPPFLAGS=$(CFLAGS) $(FLAGS)
PACKAGES=
ifneq "$(PACKAGES)" ""
CPPFLAGS+=$(shell pkg-config --cflags $(PACKAGES))
LDFLAGS+=$(shell pkg-config --libs $(PACKAGES))
endif
QPDF=/home/thobi/src/gsoc/2012/qpdf
CPPFLAGS+=-I$(QPDF)/include
LDFLAGS+=-L$(QPDF)/libqpdf/build -lqpdf
CPPFLAGS+=$(shell cups-config --cflags)
LDFLAGS+=$(shell cups-config --libs)
OBJECTS=$(patsubst %.c,$(PREFIX)%$(SUFFIX).o,\
$(patsubst %.cc,$(PREFIX)%$(SUFFIX).o,\
$(SOURCES)))
DEPENDS=$(patsubst %.c,$(PREFIX)%$(SUFFIX).d,\
$(patsubst %.cc,$(PREFIX)%$(SUFFIX).d,\
$(filter-out %.o,""\
$(SOURCES))))
all: $(EXEC)
ifneq "$(MAKECMDGOALS)" "clean"
-include $(DEPENDS)
endif
clean:
rm -f $(EXEC) $(OBJECTS) $(DEPENDS)
%.d: %.c
@$(SHELL) -ec '$(CXX) -MM $(CPPFLAGS) $< \
| sed '\''s/\($*\)\.o[ :]*/\1.o $@ : /g'\'' > $@;\
[ -s $@ ] || rm -f $@'
%.d: %.cc
@$(SHELL) -ec '$(CXX) -MM $(CPPFLAGS) $(CXXFLAGS) $< \
| sed '\''s/\($*\)\.o[ :]*/\1.o $@ : /g'\'' > $@;\
[ -s $@ ] || rm -f $@'
$(EXEC): $(OBJECTS)
# $(CXX) -o $@ $^ $(LDFLAGS)
libtool --mode=link $(CXX) -o $@ $^ $(LDFLAGS)
<file_sep>/pdftopdf_processor.cc
#include "pdftopdf_processor.h"
#include "qpdf_pdftopdf_processor.h"
#include <stdio.h>
#include <assert.h>
#include <numeric>
void BookletMode_dump(BookletMode bkm) // {{{
{
static const char *bstr[3]={"Off","On","Shuffle-Only"};
if ( (bkm<BOOKLET_OFF)||(bkm>BOOKLET_JUSTSHUFFLE) ) {
fprintf(stderr,"(bad booklet mode: %d)",bkm);
} else {
fputs(bstr[bkm],stderr);
}
}
// }}}
bool ProcessingParameters::withPage(int outno) const // {{{
{
if (outno%2 == 0) { // 1-based
if (!evenPages) {
return false;
}
} else if (!oddPages) {
return false;
}
return pageRange.contains(outno);
}
// }}}
void ProcessingParameters::dump() const // {{{
{
fprintf(stderr,"jobId: %d, numCopies: %d\n",
jobId,numCopies);
fprintf(stderr,"user: %s, title: %s\n",
(user)?user:"(null)",(title)?title:"(null)");
fprintf(stderr,"fitplot: %s\n",
(fitplot)?"true":"false");
page.dump();
fprintf(stderr,"Rotation(CCW): ");
Rotation_dump(orientation);
fprintf(stderr,"\n");
fprintf(stderr,"duplex: %s\n",
(duplex)?"true":"false");
fprintf(stderr,"Border: ");
BorderType_dump(border);
fprintf(stderr,"\n");
nup.dump();
fprintf(stderr,"reverse: %s\n",
(reverse)?"true":"false");
fprintf(stderr,"evenPages: %s, oddPages: %s\n",
(evenPages)?"true":"false",
(oddPages)?"true":"false");
fprintf(stderr,"page range: ");
pageRange.dump();
fprintf(stderr,"mirror: %s\n",
(mirror)?"true":"false");
fprintf(stderr,"Position: ");
Position_dump(xpos,Axis::X);
fprintf(stderr,"/");
Position_dump(ypos,Axis::Y);
fprintf(stderr,"\n");
fprintf(stderr,"collate: %s\n",
(collate)?"true":"false");
fprintf(stderr,"evenDuplex: %s\n",
(evenDuplex)?"true":"false");
/*
// std::string pageLabel; // or NULL? must stay/dup!
...
...
*/
fprintf(stderr,"bookletMode: ");
BookletMode_dump(booklet);
fprintf(stderr,"\nbooklet signature: %d\n",
bookSignature);
fprintf(stderr,"emitJCL: %s\n",
(emitJCL)?"true":"false");
fprintf(stderr,"deviceCopies: %d\n",
deviceCopies);
fprintf(stderr,"deviceReverse: %s\n",
(deviceReverse)?"true":"false");
fprintf(stderr,"deviceCollate: %s\n",
(deviceCollate)?"true":"false");
fprintf(stderr,"setDuplex: %s\n",
(setDuplex)?"true":"false");
}
// }}}
PDFTOPDF_Processor *PDFTOPDF_Factory::processor()
{
return new QPDF_PDFTOPDF_Processor();
}
// (1-based)
// 9: [*] [1] [2] [*] [*] [3] [4] [9] [8] [5] [6] [7] -> signature = 12 = 3*4 = ((9+3)/4)*4
// 1 2 3 4 5 6 7 8 9 10 11 12
// NOTE: psbook always fills the sig completely (results in completely white pages (4-set), depending on the input)
// empty pages must be added for output values >=numPages
std::vector<int> bookletShuffle(int numPages,int signature) // {{{
{
if (signature<0) {
signature=(numPages+3)&~0x3;
}
assert(signature%4==0);
std::vector<int> ret;
ret.reserve(numPages+signature-1);
int curpage=0;
while (curpage<numPages) {
// as long as pages to be done -- i.e. multiple times the signature
int firstpage=curpage,
lastpage=curpage+signature-1;
// one signature
while (firstpage<lastpage) {
ret.push_back(lastpage--);
ret.push_back(firstpage++);
ret.push_back(firstpage++);
ret.push_back(lastpage--);
}
curpage+=signature;
}
return ret;
}
// }}}
bool processPDFTOPDF(PDFTOPDF_Processor &proc,ProcessingParameters ¶m) // {{{
{
if (!proc.check_print_permissions()) {
fprintf(stderr,"Not allowed to print\n");
return false;
}
std::vector<std::shared_ptr<PDFTOPDF_PageHandle>> pages=proc.get_pages();
const int numOrigPages=pages.size();
// TODO FIXME? elsewhere
std::vector<int> shuffle;
if (param.booklet!=BOOKLET_OFF) {
shuffle=bookletShuffle(numOrigPages,param.bookSignature);
if (param.booklet==BOOKLET_ON) { // override options
// TODO? specifically "sides=two-sided-short-edge" / DuplexTumble
// param.duplex=true; // param.setDuplex=true; ? currently done in setFinalPPD()
NupParameters::preset(2,param.nup); // TODO?! better
}
} else { // 0 1 2 3 ...
shuffle.resize(numOrigPages);
std::iota(shuffle.begin(),shuffle.end(),0);
}
const int numPages=std::max(shuffle.size(),pages.size());
std::shared_ptr<PDFTOPDF_PageHandle> curpage;
int outputno=0;
if ( (param.nup.nupX==1)&&(param.nup.nupY==1)&&(!param.fitplot) ) {
// TODO? fitplot also without xobject?
/*
param.nup.width=param.page.width;
param.nup.height=param.page.height;
*/
for (int iA=0;iA<numPages;iA++) {
if (!param.withPage(iA+1)) {
continue;
}
if (shuffle[iA]>=numOrigPages) {
// add empty page as filler
proc.add_page(proc.new_page(param.page.width,param.page.height),param.reverse);
continue; // no border, etc.
}
auto page=pages[shuffle[iA]];
page->rotate(param.orientation);
if (param.mirror) {
page->mirror();
}
// place border
if ( (param.border!=BorderType::NONE)&&(iA<numOrigPages) ) {
#if 0 // would be nice, but is not possible
PageRect rect=page->getRect();
rect.left+=param.page.left;
rect.bottom+=param.page.bottom;
rect.top-=param.page.top;
rect.right-=param.page.right;
// width,height not needed for add_border_rect (FIXME?)
page->add_border_rect(rect,param.border,1.0);
#else // this is what pstops does
page->add_border_rect(param.page,param.border,1.0);
#endif
}
proc.add_page(page,param.reverse); // reverse -> insert at beginning
}
outputno=numPages;
} else {
param.nup.width=param.page.right-param.page.left;
param.nup.height=param.page.top-param.page.bottom;
double xpos=param.page.left,
ypos=param.page.bottom; // for whole page... TODO from position...
const bool origls=param.nup.landscape;
if ( (param.orientation==ROT_90)||(param.orientation==ROT_270) ) {
std::swap(param.nup.nupX,param.nup.nupY);
param.nup.landscape=!param.nup.landscape;
param.orientation=param.orientation-param.normal_landscape;
}
if (param.nup.landscape) {
// pages[iA]->rotate(param.normal_landscape);
param.orientation=param.orientation+param.normal_landscape;
// TODO? better
std::swap(param.page.width,param.page.height);
std::swap(param.nup.width,param.nup.height);
}
NupState nupstate(param.nup);
NupPageEdit pgedit;
for (int iA=0;iA<numPages;iA++) {
std::shared_ptr<PDFTOPDF_PageHandle> page;
if (shuffle[iA]>=numOrigPages) {
// add empty page as filler
page=proc.new_page(param.page.width,param.page.height);
} else {
page=pages[shuffle[iA]];
}
PageRect rect;
if (param.fitplot) {
rect=page->getRect();
} else {
rect.width=param.page.width;
rect.height=param.page.height;
// TODO: better
if (!origls) {
if ( (param.orientation==ROT_90)||(param.orientation==ROT_270) ) {
std::swap(rect.width,rect.height);
}
} else {
if ( (param.orientation==ROT_0)||(param.orientation==ROT_180) ) {
std::swap(rect.width,rect.height);
}
}
// TODO?
rect.left=0;
rect.bottom=0;
rect.right=rect.width;
rect.top=rect.height;
rect.rotate_move(param.orientation,rect.width,rect.height);
}
// rect.dump();
bool newPage=nupstate.nextPage(rect.width,rect.height,pgedit);
if (newPage) {
if ( (param.withPage(outputno))&&(curpage) ) {
curpage->rotate(param.orientation);
if (param.mirror) {
curpage->mirror();
// TODO? update rect? --- not needed any more
}
proc.add_page(curpage,param.reverse); // reverse -> insert at beginning
}
outputno++;
curpage=proc.new_page(param.page.width,param.page.height);
}
if (shuffle[iA]>=numOrigPages) {
continue;
}
if (param.border!=BorderType::NONE) {
// TODO FIXME... border gets cutted away, if orignal page had wrong size
// page->"uncrop"(rect); // page->setMedia()
// Note: currently "fixed" in add_subpage(...&rect);
page->add_border_rect(rect,param.border,1.0/pgedit.scale);
}
if (!param.fitplot) {
curpage->add_subpage(page,pgedit.xpos+xpos,pgedit.ypos+ypos,pgedit.scale,&rect);
} else {
curpage->add_subpage(page,pgedit.xpos+xpos,pgedit.ypos+ypos,pgedit.scale);
}
#ifdef DEBUG
if (auto dbg=dynamic_cast<QPDF_PDFTOPDF_PageHandle *>(curpage.get())) {
// dbg->debug(pgedit.sub,xpos,ypos);
}
#endif
// pgedit.dump();
}
if ( (param.withPage(outputno))&&(curpage) ) {
curpage->rotate(param.orientation);
if (param.mirror) {
curpage->mirror();
}
outputno++;
proc.add_page(curpage,param.reverse); // reverse -> insert at beginning
}
}
if ( (param.evenDuplex)&&(outputno&1) ) {
// need to output empty page to not confuse duplex
proc.add_page(proc.new_page(param.page.width,param.page.height),param.reverse);
}
proc.multiply(param.numCopies,param.collate);
return true;
}
// }}}
<file_sep>/qpdf_pdftopdf_processor.cc
#include "qpdf_pdftopdf_processor.h"
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <stdexcept>
#include <qpdf/QPDFWriter.hh>
#include <qpdf/QUtil.hh>
#include "qpdf_tools.h"
#include "qpdf_xobject.h"
#include "qpdf_pdftopdf.h"
// Use: content.append(debug_box(pe.sub,xpos,ypos));
static std::string debug_box(const PageRect &box,float xshift,float yshift) // {{{
{
return std::string("q 1 w 0.1 G\n ")+
QUtil::double_to_string(box.left+xshift)+" "+QUtil::double_to_string(box.bottom+yshift)+" m "+
QUtil::double_to_string(box.right+xshift)+" "+QUtil::double_to_string(box.top+yshift)+" l "+"S \n "+
QUtil::double_to_string(box.right+xshift)+" "+QUtil::double_to_string(box.bottom+yshift)+" m "+
QUtil::double_to_string(box.left+xshift)+" "+QUtil::double_to_string(box.top+yshift)+" l "+"S \n "+
QUtil::double_to_string(box.left+xshift)+" "+QUtil::double_to_string(box.bottom+yshift)+" "+
QUtil::double_to_string(box.right-box.left)+" "+QUtil::double_to_string(box.top-box.bottom)+" re "+"S Q\n";
}
// }}}
QPDF_PDFTOPDF_PageHandle::QPDF_PDFTOPDF_PageHandle(QPDFObjectHandle page,int orig_no) // {{{
: page(page),
no(orig_no),
rotation(ROT_0)
{
}
// }}}
QPDF_PDFTOPDF_PageHandle::QPDF_PDFTOPDF_PageHandle(QPDF *pdf,float width,float height) // {{{
: no(0),
rotation(ROT_0)
{
assert(pdf);
page=QPDFObjectHandle::parse(
"<<"
" /Type /Page"
" /Resources <<"
" /XObject null "
" >>"
" /MediaBox null "
" /Contents null "
">>");
page.replaceKey("/MediaBox",makeBox(0,0,width,height));
page.replaceKey("/Contents",QPDFObjectHandle::newStream(pdf));
// xobjects: later (in get())
content.assign("q\n"); // TODO? different/not needed
page=pdf->makeIndirectObject(page); // stores *pdf
}
// }}}
// Note: PDFTOPDF_Processor always works with "/Rotate"d and "/UserUnit"-scaled pages/coordinates/..., having 0,0 at left,bottom of the TrimBox
PageRect QPDF_PDFTOPDF_PageHandle::getRect() const // {{{
{
page.assertInitialized();
PageRect ret=getBoxAsRect(getTrimBox(page));
ret.translate(-ret.left,-ret.bottom);
ret.rotate_move(getRotate(page),ret.width,ret.height);
ret.scale(getUserUnit(page));
return ret;
}
// }}}
bool QPDF_PDFTOPDF_PageHandle::isExisting() const // {{{
{
page.assertInitialized();
return content.empty();
}
// }}}
QPDFObjectHandle QPDF_PDFTOPDF_PageHandle::get() // {{{
{
QPDFObjectHandle ret=page;
if (!isExisting()) { // finish up page
page.getKey("/Resources").replaceKey("/XObject",QPDFObjectHandle::newDictionary(xobjs));
content.append("Q\n");
page.getKey("/Contents").replaceStreamData(content,QPDFObjectHandle::newNull(),QPDFObjectHandle::newNull());
page.replaceOrRemoveKey("/Rotate",makeRotate(rotation));
} else {
Rotation rot=getRotate(page)+rotation;
page.replaceOrRemoveKey("/Rotate",makeRotate(rot));
}
page=QPDFObjectHandle(); // i.e. uninitialized
return ret;
}
// }}}
// TODO: we probably need a function "ungetRect()" to transform to page/form space
// TODO: as member
static PageRect ungetRect(PageRect rect,const QPDF_PDFTOPDF_PageHandle &ph,Rotation rotation,QPDFObjectHandle page)
{
PageRect pg1=ph.getRect();
PageRect pg2=getBoxAsRect(getTrimBox(page));
// we have to invert /Rotate, /UserUnit and the left,bottom (TrimBox) translation
//Rotation_dump(rotation);
//Rotation_dump(getRotate(page));
rect.width=pg1.width;
rect.height=pg1.height;
//std::swap(rect.width,rect.height);
//rect.rotate_move(-rotation,rect.width,rect.height);
rect.rotate_move(-getRotate(page),pg1.width,pg1.height);
rect.scale(1.0/getUserUnit(page));
// PageRect pg2=getBoxAsRect(getTrimBox(page));
rect.translate(pg2.left,pg2.bottom);
//rect.dump();
return rect;
}
// TODO FIXME rotations are strange ... (via ungetRect)
// TODO? for non-existing (either drop comment or facility to create split streams needed)
void QPDF_PDFTOPDF_PageHandle::add_border_rect(const PageRect &_rect,BorderType border,float fscale) // {{{
{
assert(isExisting());
assert(border!=BorderType::NONE);
// straight from pstops
const double lw=(border&THICK)?0.5:0.24;
double line_width=lw*fscale;
double margin=2.25*fscale;
// (PageLeft+margin,PageBottom+margin) rect (PageRight-PageLeft-2*margin,...) ... for nup>1: PageLeft=0,etc.
// if (double) margin+=2*fscale ...rect...
PageRect rect=ungetRect(_rect,*this,rotation,page);
assert(rect.left<=rect.right);
assert(rect.bottom<=rect.top);
std::string boxcmd="q\n";
boxcmd+=" "+QUtil::double_to_string(line_width)+" w 0 G \n";
boxcmd+=" "+QUtil::double_to_string(rect.left+margin)+" "+QUtil::double_to_string(rect.bottom+margin)+" "+
QUtil::double_to_string(rect.right-rect.left-2*margin)+" "+QUtil::double_to_string(rect.top-rect.bottom-2*margin)+" re S \n";
if (border&TWO) {
margin+=2*fscale;
boxcmd+=" "+QUtil::double_to_string(rect.left+margin)+" "+QUtil::double_to_string(rect.bottom+margin)+" "+
QUtil::double_to_string(rect.right-rect.left-2*margin)+" "+QUtil::double_to_string(rect.top-rect.bottom-2*margin)+" re S \n";
}
boxcmd+="Q\n";
// if (!isExisting()) {
// // TODO: only after
// return;
// }
assert(page.getOwningQPDF()); // existing pages are always indirect
#ifdef DEBUG // draw it on top
static const char *pre="%pdftopdf q\n"
"q\n",
*post="%pdftopdf Q\n"
"Q\n";
QPDFObjectHandle stm1=QPDFObjectHandle::newStream(page.getOwningQPDF(),pre),
stm2=QPDFObjectHandle::newStream(page.getOwningQPDF(),std::string(post)+boxcmd);
page.addPageContents(stm1,true); // before
page.addPageContents(stm2,false); // after
#else
QPDFObjectHandle stm=QPDFObjectHandle::newStream(page.getOwningQPDF(),boxcmd);
page.addPageContents(stm,true); // before
#endif
}
// }}}
// TODO: better cropping
// TODO: test/fix with qsub rotation
void QPDF_PDFTOPDF_PageHandle::add_subpage(const std::shared_ptr<PDFTOPDF_PageHandle> &sub,float xpos,float ypos,float scale,const PageRect *crop) // {{{
{
auto qsub=dynamic_cast<QPDF_PDFTOPDF_PageHandle *>(sub.get());
assert(qsub);
std::string xoname="/X"+QUtil::int_to_string((qsub->no!=-1)?qsub->no:++no);
if (crop) {
PageRect pg=qsub->getRect(),tmp=*crop;
// we need to fix a too small cropbox.
tmp.width=tmp.right-tmp.left;
tmp.height=tmp.top-tmp.bottom;
tmp.rotate_move(-getRotate(qsub->page),tmp.width,tmp.height); // TODO TODO (pg.width? / unneeded?)
// TODO: better
// TODO: we need to obey page./Rotate
if (pg.width<tmp.width) {
pg.right=pg.left+tmp.width;
}
if (pg.height<tmp.height) {
pg.top=pg.bottom+tmp.height;
}
PageRect rect=ungetRect(pg,*qsub,ROT_0,qsub->page);
qsub->page.replaceKey("/TrimBox",makeBox(rect.left,rect.bottom,rect.right,rect.top));
// TODO? do everything for cropping here?
}
xobjs[xoname]=makeXObject(qsub->page.getOwningQPDF(),qsub->page); // trick: should be the same as page->getOwningQPDF() [only after it's made indirect]
Matrix mtx;
mtx.translate(xpos,ypos);
mtx.scale(scale);
mtx.rotate(qsub->rotation); // TODO? -sub.rotation ? // TODO FIXME: this might need another translation!?
if (crop) { // TODO? other technique: set trim-box before makeXObject (but this modifies original page)
mtx.translate(crop->left,crop->bottom);
// crop->dump();
}
content.append("q\n ");
content.append(mtx.get_string()+" cm\n ");
if (crop) {
content.append("0 0 "+QUtil::double_to_string(crop->right-crop->left)+" "+QUtil::double_to_string(crop->top-crop->bottom)+" re W n\n ");
// content.append("0 0 "+QUtil::double_to_string(crop->right-crop->left)+" "+QUtil::double_to_string(crop->top-crop->bottom)+" re S\n ");
}
content.append(xoname+" Do\n");
content.append("Q\n");
}
// }}}
void QPDF_PDFTOPDF_PageHandle::mirror() // {{{
{
PageRect orig=getRect();
if (isExisting()) {
// need to wrap in XObject to keep patterns correct
// TODO? refactor into internal ..._subpage fn ?
std::string xoname="/X"+QUtil::int_to_string(no);
QPDFObjectHandle subpage=get(); // this->page, with rotation
// replace all our data
*this=QPDF_PDFTOPDF_PageHandle(subpage.getOwningQPDF(),orig.width,orig.height);
xobjs[xoname]=makeXObject(subpage.getOwningQPDF(),subpage); // we can only now set this->xobjs
// content.append(std::string("1 0 0 1 0 0 cm\n ");
content.append(xoname+" Do\n");
assert(!isExisting());
}
static const char *pre="%pdftopdf cm\n";
// Note: we don't change (TODO need to?) the media box
std::string mrcmd("-1 0 0 1 "+
QUtil::double_to_string(orig.right)+" 0 cm\n");
content.insert(0,std::string(pre)+mrcmd);
}
// }}}
void QPDF_PDFTOPDF_PageHandle::rotate(Rotation rot) // {{{
{
rotation=rot; // "rotation += rot;" ?
}
// }}}
void QPDF_PDFTOPDF_PageHandle::debug(const PageRect &rect,float xpos,float ypos) // {{{
{
assert(!isExisting());
content.append(debug_box(rect,xpos,ypos));
}
// }}}
void QPDF_PDFTOPDF_Processor::closeFile() // {{{
{
pdf.reset();
hasCM=false;
}
// }}}
void QPDF_PDFTOPDF_Processor::error(const char *fmt,...) // {{{
{
va_list ap;
va_start(ap,fmt);
vfprintf(stderr,fmt,ap);
fputs("\n",stderr);
va_end(ap);
}
// }}}
// TODO? try/catch for PDF parsing errors?
bool QPDF_PDFTOPDF_Processor::loadFile(FILE *f,ArgOwnership take) // {{{
{
closeFile();
if (!f) {
throw std::invalid_argument("loadFile(NULL,...) not allowed");
}
try {
pdf.reset(new QPDF);
} catch (...) {
if (take==TakeOwnership) {
fclose(f);
}
throw;
}
switch (take) {
case WillStayAlive:
try {
pdf->processFile("temp file",f,false);
} catch (const std::exception &e) {
error("loadFile failed: %s",e.what());
return false;
}
break;
case TakeOwnership:
try {
pdf->processFile("temp file",f,true);
} catch (const std::exception &e) {
error("loadFile failed: %s",e.what());
return false;
}
break;
case MustDuplicate:
error("loadFile with MustDuplicate is not supported");
return false;
}
start();
return true;
}
// }}}
bool QPDF_PDFTOPDF_Processor::loadFilename(const char *name) // {{{
{
closeFile();
try {
pdf.reset(new QPDF);
pdf->processFile(name);
} catch (const std::exception &e) {
error("loadFilename failed: %s",e.what());
return false;
}
start();
return true;
}
// }}}
void QPDF_PDFTOPDF_Processor::start() // {{{
{
assert(pdf);
pdf->pushInheritedAttributesToPage();
orig_pages=pdf->getAllPages();
// remove them (just unlink, data still there)
const int len=orig_pages.size();
for (int iA=0;iA<len;iA++) {
pdf->removePage(orig_pages[iA]);
}
// we remove stuff that becomes defunct (probably) TODO
pdf->getRoot().removeKey("/PageMode");
pdf->getRoot().removeKey("/Outlines");
pdf->getRoot().removeKey("/OpenAction");
pdf->getRoot().removeKey("/PageLabels");
}
// }}}
bool QPDF_PDFTOPDF_Processor::check_print_permissions() // {{{
{
if (!pdf) {
error("No PDF loaded");
return false;
}
return pdf->allowPrintHighRes() || pdf->allowPrintLowRes(); // from legacy pdftopdf
}
// }}}
std::vector<std::shared_ptr<PDFTOPDF_PageHandle>> QPDF_PDFTOPDF_Processor::get_pages() // {{{
{
std::vector<std::shared_ptr<PDFTOPDF_PageHandle>> ret;
if (!pdf) {
error("No PDF loaded");
assert(0);
return ret;
}
const int len=orig_pages.size();
ret.reserve(len);
for (int iA=0;iA<len;iA++) {
ret.push_back(std::shared_ptr<PDFTOPDF_PageHandle>(new QPDF_PDFTOPDF_PageHandle(orig_pages[iA],iA+1)));
}
return ret;
}
// }}}
std::shared_ptr<PDFTOPDF_PageHandle> QPDF_PDFTOPDF_Processor::new_page(float width,float height) // {{{
{
if (!pdf) {
error("No PDF loaded");
assert(0);
return std::shared_ptr<PDFTOPDF_PageHandle>();
}
return std::shared_ptr<QPDF_PDFTOPDF_PageHandle>(new QPDF_PDFTOPDF_PageHandle(pdf.get(),width,height));
// return std::make_shared<QPDF_PDFTOPDF_PageHandle>(pdf.get(),width,height); // problem: make_shared not friend
}
// }}}
void QPDF_PDFTOPDF_Processor::add_page(std::shared_ptr<PDFTOPDF_PageHandle> page,bool front) // {{{
{
assert(pdf);
auto qpage=dynamic_cast<QPDF_PDFTOPDF_PageHandle *>(page.get());
if (qpage) {
pdf->addPage(qpage->get(),front);
}
}
// }}}
#if 0
// we remove stuff now probably defunct TODO
pdf->getRoot().removeKey("/PageMode");
pdf->getRoot().removeKey("/Outlines");
pdf->getRoot().removeKey("/OpenAction");
pdf->getRoot().removeKey("/PageLabels");
#endif
void QPDF_PDFTOPDF_Processor::multiply(int copies,bool collate) // {{{
{
assert(pdf);
assert(copies>0);
std::vector<QPDFObjectHandle> pages=pdf->getAllPages(); // need copy
const int len=pages.size();
if (collate) {
for (int iA=1;iA<copies;iA++) {
for (int iB=0;iB<len;iB++) {
pdf->addPage(pages[iB].shallowCopy(),false);
}
}
} else {
for (int iB=0;iB<len;iB++) {
for (int iA=1;iA<copies;iA++) {
pdf->addPageAt(pages[iB].shallowCopy(),false,pages[iB]);
}
}
}
}
// }}}
#include "qpdf_cm.h"
// TODO
void QPDF_PDFTOPDF_Processor::addCM(const char *defaulticc,const char *outputicc) // {{{
{
assert(pdf);
if (hasOutputIntent(*pdf)) {
return; // nothing to do
}
QPDFObjectHandle srcicc=setDefaultICC(*pdf,defaulticc);
addDefaultRGB(*pdf,srcicc);
addOutputIntent(*pdf,outputicc);
hasCM=true;
}
// }}}
void QPDF_PDFTOPDF_Processor::setComments(const std::vector<std::string> &comments) // {{{
{
extraheader.clear();
const int len=comments.size();
for (int iA=0;iA<len;iA++) {
assert(comments[iA].at(0)=='%');
extraheader.append(comments[iA]);
extraheader.push_back('\n');
}
}
// }}}
void QPDF_PDFTOPDF_Processor::emitFile(FILE *f,ArgOwnership take) // {{{
{
if (!pdf) {
return;
}
QPDFWriter out(*pdf);
switch (take) {
case WillStayAlive:
out.setOutputFile("temp file",f,false);
break;
case TakeOwnership:
out.setOutputFile("temp file",f,true);
break;
case MustDuplicate:
error("emitFile with MustDuplicate is not supported");
return;
}
if (hasCM) {
out.setMinimumPDFVersion("1.4");
} else {
out.setMinimumPDFVersion("1.2");
}
if (!extraheader.empty()) {
out.setExtraHeaderText(extraheader);
}
out.write();
}
// }}}
void QPDF_PDFTOPDF_Processor::emitFilename(const char *name) // {{{
{
if (!pdf) {
return;
}
// special case: name==NULL -> stdout
QPDFWriter out(*pdf,name);
if (hasCM) {
out.setMinimumPDFVersion("1.4");
} else {
out.setMinimumPDFVersion("1.2");
}
if (!extraheader.empty()) {
out.setExtraHeaderText(extraheader);
}
out.write();
}
// }}}
// TODO:
// loadPDF(); success?
<file_sep>/qpdf_pdftopdf.cc
#include "qpdf_pdftopdf.h"
#include <assert.h>
#include <stdexcept>
PageRect getBoxAsRect(QPDFObjectHandle box) // {{{
{
PageRect ret;
ret.left=box.getArrayItem(0).getNumericValue();
ret.bottom=box.getArrayItem(1).getNumericValue();
ret.right=box.getArrayItem(2).getNumericValue();
ret.top=box.getArrayItem(3).getNumericValue();
ret.width=ret.right-ret.left;
ret.height=ret.top-ret.bottom;
return ret;
}
// }}}
Rotation getRotate(QPDFObjectHandle page) // {{{
{
if (!page.hasKey("/Rotate")) {
return ROT_0;
}
double rot=page.getKey("/Rotate").getNumericValue();
if (rot==90.0) { // CW
return ROT_270; // CCW
} else if (rot==180.0) {
return ROT_180;
} else if (rot==270.0) {
return ROT_90;
} else {
assert(rot==0.0);
}
return ROT_0;
}
// }}}
double getUserUnit(QPDFObjectHandle page) // {{{
{
if (!page.hasKey("/UserUnit")) {
return 1.0;
}
return page.getKey("/UserUnit").getNumericValue();
}
// }}}
QPDFObjectHandle makeRotate(Rotation rot) // {{{
{
switch (rot) {
case ROT_0:
return QPDFObjectHandle::newNull();
case ROT_90: // CCW
return QPDFObjectHandle::newInteger(270); // CW
case ROT_180:
return QPDFObjectHandle::newInteger(180);
case ROT_270:
return QPDFObjectHandle::newInteger(90);
default:
throw std::invalid_argument("Bad rotation");
}
}
// }}}
#include "qpdf_tools.h"
QPDFObjectHandle getRectAsBox(const PageRect &rect) // {{{
{
return makeBox(rect.left,rect.bottom,rect.right,rect.top);
}
// }}}
#include <qpdf/QUtil.hh>
Matrix::Matrix() // {{{
: ctm{1,0,0,1,0,0}
{
}
// }}}
Matrix::Matrix(QPDFObjectHandle ar) // {{{
{
if (ar.getArrayNItems()!=6) {
throw std::runtime_error("Not a ctm matrix");
}
for (int iA=0;iA<6;iA++) {
ctm[iA]=ar.getArrayItem(iA).getNumericValue();
}
}
// }}}
Matrix &Matrix::rotate(Rotation rot) // {{{
{
switch (rot) {
case ROT_0:
break;
case ROT_90:
std::swap(ctm[0],ctm[2]);
std::swap(ctm[1],ctm[3]);
ctm[2]=-ctm[2];
ctm[3]=-ctm[3];
break;
case ROT_180:
ctm[0]=-ctm[0];
ctm[3]=-ctm[3];
break;
case ROT_270:
std::swap(ctm[0],ctm[2]);
std::swap(ctm[1],ctm[3]);
ctm[0]=-ctm[0];
ctm[1]=-ctm[1];
break;
default:
assert(0);
}
return *this;
}
// }}}
// TODO: test
Matrix &Matrix::rotate_move(Rotation rot,double width,double height) // {{{
{
rotate(rot);
switch (rot) {
case ROT_0:
break;
case ROT_90:
translate(width,0);
break;
case ROT_180:
translate(width,height);
break;
case ROT_270:
translate(0,height);
break;
}
return *this;
}
// }}}
Matrix &Matrix::rotate(double rad) // {{{
{
Matrix tmp;
tmp.ctm[0]=cos(rad);
tmp.ctm[1]=sin(rad);
tmp.ctm[2]=-sin(rad);
tmp.ctm[3]=cos(rad);
return (*this*=tmp);
}
// }}}
Matrix &Matrix::translate(double tx,double ty) // {{{
{
ctm[4]+=ctm[0]*tx+ctm[2]*ty;
ctm[5]+=ctm[1]*tx+ctm[3]*ty;
return *this;
}
// }}}
Matrix &Matrix::scale(double sx,double sy) // {{{
{
ctm[0]*=sx;
ctm[1]*=sx;
ctm[2]*=sy;
ctm[3]*=sy;
return *this;
}
// }}}
Matrix &Matrix::operator*=(const Matrix &rhs) // {{{
{
double tmp[6];
std::copy(ctm,ctm+6,tmp);
ctm[0] = tmp[0]*rhs.ctm[0] + tmp[2]*rhs.ctm[1];
ctm[1] = tmp[1]*rhs.ctm[0] + tmp[3]*rhs.ctm[1];
ctm[2] = tmp[0]*rhs.ctm[2] + tmp[2]*rhs.ctm[3];
ctm[3] = tmp[1]*rhs.ctm[2] + tmp[3]*rhs.ctm[3];
ctm[4] = tmp[0]*rhs.ctm[4] + tmp[2]*rhs.ctm[5] + tmp[4];
ctm[5] = tmp[1]*rhs.ctm[4] + tmp[3]*rhs.ctm[5] + tmp[5];
return *this;
}
// }}}
QPDFObjectHandle Matrix::get() const // {{{
{
QPDFObjectHandle ret=QPDFObjectHandle::newArray();
ret.appendItem(QPDFObjectHandle::newReal(ctm[0]));
ret.appendItem(QPDFObjectHandle::newReal(ctm[1]));
ret.appendItem(QPDFObjectHandle::newReal(ctm[2]));
ret.appendItem(QPDFObjectHandle::newReal(ctm[3]));
ret.appendItem(QPDFObjectHandle::newReal(ctm[4]));
ret.appendItem(QPDFObjectHandle::newReal(ctm[5]));
return ret;
}
// }}}
std::string Matrix::get_string() const // {{{
{
std::string ret;
ret.append(QUtil::double_to_string(ctm[0]));
ret.append(" ");
ret.append(QUtil::double_to_string(ctm[1]));
ret.append(" ");
ret.append(QUtil::double_to_string(ctm[2]));
ret.append(" ");
ret.append(QUtil::double_to_string(ctm[3]));
ret.append(" ");
ret.append(QUtil::double_to_string(ctm[4]));
ret.append(" ");
ret.append(QUtil::double_to_string(ctm[5]));
return ret;
}
// }}}
<file_sep>/nup.cc
#include "nup.h"
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <utility>
void NupParameters::dump() const // {{{
{
fprintf(stderr,"NupX: %d, NupY: %d\n"
"width: %f, height: %f\n",
nupX,nupY,
width,height);
int opos=-1,fpos=-1,spos=-1;
if (xstart==Position::LEFT) { // or Bottom
fpos=0;
} else if (xstart==Position::RIGHT) { // or Top
fpos=1;
}
if (ystart==Position::LEFT) { // or Bottom
spos=0;
} else if (ystart==Position::RIGHT) { // or Top
spos=1;
}
if (first==Axis::X) {
fprintf(stderr,"First Axis: X\n");
opos=0;
} else if (first==Axis::Y) {
fprintf(stderr,"First Axis: Y\n");
opos=2;
std::swap(fpos,spos);
}
if ( (opos==-1)||(fpos==-1)||(spos==-1) ) {
fprintf(stderr,"Bad Spec: %d; start: %d, %d\n\n",
first,xstart,ystart);
} else {
static const char *order[4]={"lr","rl","bt","tb"};
fprintf(stderr,"Order: %s%s\n",
order[opos+fpos],order[(opos+2)%4+spos]);
}
fputs("Alignment: ",stderr);
Position_dump(xalign,Axis::X);
fputs("/",stderr);
Position_dump(yalign,Axis::Y);
fputs("\n",stderr);
}
// }}}
bool NupParameters::possible(int nup) // {{{
{
// 1 2 3 4 6 8 9 10 12 15 16
return (nup>=1)&&(nup<=16)&&
( (nup!=5)||(nup!=7)||(nup!=11)||(nup!=13)||(nup!=14) );
}
// }}}
void NupParameters::preset(int nup,NupParameters &ret) // {{{
{
switch (nup) {
case 1:
ret.nupX=1;
ret.nupY=1;
break;
case 2:
ret.nupX=2;
ret.nupY=1;
ret.landscape=true;
break;
case 3:
ret.nupX=3;
ret.nupY=1;
ret.landscape=true;
break;
case 4:
ret.nupX=2;
ret.nupY=2;
break;
case 6:
ret.nupX=3;
ret.nupY=2;
ret.landscape=true;
break;
case 8:
ret.nupX=4;
ret.nupY=2;
ret.landscape=true;
break;
case 9:
ret.nupX=3;
ret.nupY=3;
break;
case 10:
ret.nupX=5;
ret.nupY=2;
ret.landscape=true;
break;
case 12:
ret.nupX=3;
ret.nupY=4;
break;
case 15:
ret.nupX=5;
ret.nupY=3;
ret.landscape=true;
break;
case 16:
ret.nupX=4;
ret.nupY=4;
break;
}
}
// }}}
NupState::NupState(const NupParameters ¶m) // {{{
: param(param),
in_pages(0),out_pages(0),
nup(param.nupX*param.nupY),
subpage(nup)
{
assert( (param.nupX>0)&&(param.nupY>0) );
}
// }}}
void NupState::reset() // {{{
{
in_pages=0;
out_pages=0;
// nup=param.nupX*param.nupY;
subpage=nup;
}
// }}}
void NupPageEdit::dump() const // {{{
{
fprintf(stderr,"xpos: %f, ypos: %f, scale: %f\n",
xpos,ypos,scale);
sub.dump();
}
// }}}
std::pair<int,int> NupState::convert_order(int subpage) const // {{{
{
int subx,suby;
if (param.first==Axis::X) {
subx=subpage%param.nupX;
suby=subpage/param.nupX;
} else {
subx=subpage/param.nupY;
suby=subpage%param.nupY;
}
subx=(param.nupX-1)*(param.xstart+1)/2-param.xstart*subx;
suby=(param.nupY-1)*(param.ystart+1)/2-param.ystart*suby;
return std::make_pair(subx,suby);
}
// }}}
static inline float lin(Position pos,float size) // {{{
{
if (pos==-1) return 0;
else if (pos==0) return size/2;
else if (pos==1) return size;
return size*(pos+1)/2;
}
// }}}
void NupState::calculate_edit(int subx,int suby,NupPageEdit &ret) const // {{{
{
// dimensions of a "nup cell"
const float width=param.width/param.nupX,
height=param.height/param.nupY;
// first calculate only for bottom-left corner
ret.xpos=subx*width;
ret.ypos=suby*height;
const float scalex=width/ret.sub.width,
scaley=height/ret.sub.height;
float subwidth=ret.sub.width*scaley,
subheight=ret.sub.height*scalex;
// TODO? if ( (!fitPlot)&&(ret.scale>1) ) ret.scale=1.0;
if (scalex>scaley) {
ret.scale=scaley;
subheight=height;
ret.xpos+=lin(param.xalign,width-subwidth);
} else {
ret.scale=scalex;
subwidth=width;
ret.ypos+=lin(param.yalign,height-subheight);
}
ret.sub.left=ret.xpos;
ret.sub.bottom=ret.ypos;
ret.sub.right=ret.sub.left+subwidth;
ret.sub.top=ret.sub.bottom+subheight;
}
// }}}
bool NupState::nextPage(float in_width,float in_height,NupPageEdit &ret) // {{{
{
in_pages++;
subpage++;
if (subpage>=nup) {
subpage=0;
out_pages++;
}
ret.sub.width=in_width;
ret.sub.height=in_height;
auto sub=convert_order(subpage);
calculate_edit(sub.first,sub.second,ret);
return (subpage==0);
}
// }}}
static std::pair<Axis,Position> parsePosition(char a,char b) // {{{ returns ,CENTER(0) on invalid
{
a|=0x20; // make lowercase
b|=0x20;
if ( (a=='l')&&(b=='r') ) {
return std::make_pair(Axis::X,Position::LEFT);
} else if ( (a=='r')&&(b=='l') ) {
return std::make_pair(Axis::X,Position::RIGHT);
} else if ( (a=='t')&&(b=='b') ) {
return std::make_pair(Axis::Y,Position::TOP);
} else if ( (a=='b')&&(b=='t') ) {
return std::make_pair(Axis::Y,Position::BOTTOM);
}
return std::make_pair(Axis::X,Position::CENTER);
}
// }}}
bool parseNupLayout(const char *val,NupParameters &ret) // {{{
{
assert(val);
auto pos0=parsePosition(val[0],val[1]);
if (pos0.second==CENTER) {
return false;
}
auto pos1=parsePosition(val[2],val[3]);
if ( (pos1.second==CENTER)||(pos0.first==pos1.first) ) {
return false;
}
ret.first=pos0.first;
if (ret.first==Axis::X) {
ret.xstart=pos0.second;
ret.ystart=pos1.second;
} else {
ret.xstart=pos1.second;
ret.ystart=pos0.second;
}
return (val[4]==0); // everything seen?
}
// }}}
<file_sep>/pdftopdf.cc
// Copyright (c) 2012 <NAME>
//
// Copyright (c) 2006-2011, BBR Inc. All rights reserved.
// MIT Licensed.
// TODO: check ppd==NULL (?)
#include <stdio.h>
#include <assert.h>
#include <cups/cups.h>
#include <cups/ppd.h>
#include <memory>
#include "pdftopdf_processor.h"
#include "pdftopdf_jcl.h"
#include <stdarg.h>
static void error(const char *fmt,...) // {{{
{
va_list ap;
va_start(ap,fmt);
fputs("Error: ",stderr);
vfprintf(stderr,fmt,ap);
fputs("\n",stderr);
va_end(ap);
}
// }}}
// namespace {}
void setFinalPPD(ppd_file_t *ppd,const ProcessingParameters ¶m)
{
if ( (param.booklet==BOOKLET_ON)&&(ppdFindOption(ppd,"Duplex")) ) {
// TODO: elsewhere, better
ppdMarkOption(ppd,"Duplex","DuplexTumble");
// TODO? sides=two-sided-short-edge
}
// for compatibility
if ( (param.setDuplex)&&(ppdFindOption(ppd,"Duplex")!=NULL) ) {
ppdMarkOption(ppd,"Duplex","True");
ppdMarkOption(ppd,"Duplex","On");
}
// we do it, printer should not
ppd_choice_t *choice;
if ( (choice=ppdFindMarkedChoice(ppd,"MirrorPrint")) != NULL) {
choice->marked=0;
}
// TODO: FIXME: unify code with emitJCLOptions, which does this "by-hand" now (and makes this code superfluous)
if (param.deviceCopies==1) {
// make sure any hardware copying is disabled
ppdMarkOption(ppd,"Copies","1");
ppdMarkOption(ppd,"JCLCopies","1");
}
}
// for choice, only overwrites ret if found in ppd
static bool ppdGetInt(ppd_file_t *ppd,const char *name,int *ret) // {{{
{
assert(ret);
ppd_choice_t *choice=ppdFindMarkedChoice(ppd,name); // !ppd is ok.
if (choice) {
*ret=atoi(choice->choice);
return true;
}
return false;
}
// }}}
static bool optGetInt(const char *name,int num_options,cups_option_t *options,int *ret) // {{{
{
assert(ret);
const char *val=cupsGetOption(name,num_options,options);
if (val) {
*ret=atoi(val);
return true;
}
return false;
}
// }}}
static bool optGetFloat(const char *name,int num_options,cups_option_t *options,float *ret) // {{{
{
assert(ret);
const char *val=cupsGetOption(name,num_options,options);
if (val) {
*ret=atof(val);
return true;
}
return false;
}
// }}}
static bool is_false(const char *value) // {{{
{
if (!value) {
return false;
}
return (strcasecmp(value,"no")==0)||
(strcasecmp(value,"off")==0)||
(strcasecmp(value,"false")==0);
}
// }}}
static bool is_true(const char *value) // {{{
{
if (!value) {
return false;
}
return (strcasecmp(value,"yes")==0)||
(strcasecmp(value,"on")==0)||
(strcasecmp(value,"true")==0);
}
// }}}
static bool ppdGetDuplex(ppd_file_t *ppd) // {{{
{
return ppdIsMarked(ppd,"Duplex","DuplexNoTumble")||
ppdIsMarked(ppd,"Duplex","DuplexTumble")||
ppdIsMarked(ppd,"JCLDuplex","DuplexNoTumble")||
ppdIsMarked(ppd,"JCLDuplex","DuplexTumble")||
ppdIsMarked(ppd,"EFDuplex","DuplexNoTumble")||
ppdIsMarked(ppd,"EFDuplex","DuplexTumble")||
ppdIsMarked(ppd,"KD03Duplex","DuplexNoTumble")||
ppdIsMarked(ppd,"KD03Duplex","DuplexTumble");
}
// }}}
// TODO: enum
static bool ppdDefaultOrder(ppd_file_t *ppd) // {{{ -- is reverse?
{
ppd_choice_t *choice;
ppd_attr_t *attr;
const char *val=NULL;
// Figure out the right default output order from the PPD file...
if ( (choice=ppdFindMarkedChoice(ppd,"OutputOrder")) != NULL) {
val=choice->choice;
} else if ( ( (choice=ppdFindMarkedChoice(ppd,"OutputBin")) != NULL)&&
( (attr=ppdFindAttr(ppd,"PageStackOrder",choice->choice)) != NULL) ) {
val=attr->value;
} else if ( (attr=ppdFindAttr(ppd,"DefaultOutputOrder",0)) != NULL) {
val=attr->value;
}
if ( (!val)||(strcasecmp(val,"Normal")==0) ) {
return false;
} else if (strcasecmp(val,"Reverse")==0) {
return true;
}
error("Unsupported output-order value %s, using 'normal'!",val);
return false;
}
// }}}
static bool optGetCollate(int num_options,cups_option_t *options) // {{{
{
if (is_true(cupsGetOption("Collate",num_options,options))) {
return true;
}
const char *val=NULL;
if ( (val=cupsGetOption("multiple-document-handling",num_options,options)) != NULL) {
/* This IPP attribute is unnecessarily complicated:
* single-document, separate-documents-collated-copies, single-document-new-sheet:
* -> collate (true)
* separate-documents-uncollated-copies:
* -> can be uncollated (false)
*/
return (strcasecmp(val,"separate-documents-uncollated-copies")!=0);
}
return false;
}
// }}}
static bool parsePosition(const char *value,Position &xpos,Position &ypos) // {{{
{
// ['center','top','left','right','top-left','top-right','bottom','bottom-left','bottom-right']
xpos=Position::CENTER;
ypos=Position::CENTER;
int next=0;
if (strcasecmp(value,"center")==0) {
return true;
} else if (strncasecmp(value,"top",3)==0) {
ypos=Position::TOP;
next=3;
} else if (strncasecmp(value,"bottom",6)==0) {
ypos=Position::BOTTOM;
next=6;
}
if (next) {
if (value[next]==0) {
return true;
} else if (value[next]!='-') {
return false;
}
value+=next+1;
}
if (strcasecmp(value,"left")==0) {
xpos=Position::LEFT;
} else if (strcasecmp(value,"right")==0) {
xpos=Position::RIGHT;
} else {
return false;
}
return true;
}
// }}}
#include <ctype.h>
static void parseRanges(const char *range,IntervalSet &ret) // {{{
{
ret.clear();
if (!range) {
ret.add(1); // everything
ret.finish();
return;
}
int lower,upper;
while (*range) {
if (*range=='-') {
range++;
upper=strtol(range,(char **)&range,10);
if (upper>=2147483647) { // see also cups/encode.c
ret.add(1);
} else {
ret.add(1,upper+1);
}
} else {
lower=strtol(range,(char **)&range,10);
if (*range=='-') {
range++;
if (!isdigit(*range)) {
ret.add(lower);
} else {
upper=strtol(range,(char **)&range,10);
if (upper>=2147483647) {
ret.add(1);
} else {
ret.add(lower,upper+1);
}
}
} else {
ret.add(lower,lower+1);
}
}
if (*range!=',') {
break;
}
range++;
}
ret.finish();
}
// }}}
static bool parseBorder(const char *val,BorderType &ret) // {{{
{
assert(val);
if (strcasecmp(val,"none")==0) {
ret=BorderType::NONE;
} else if (strcasecmp(val,"single")==0) {
ret=BorderType::ONE_THIN;
} else if (strcasecmp(val,"single-thick")==0) {
ret=BorderType::ONE_THICK;
} else if (strcasecmp(val,"double")==0) {
ret=BorderType::TWO_THIN;
} else if (strcasecmp(val,"double-thick")==0) {
ret=BorderType::TWO_THICK;
} else {
return false;
}
return true;
}
// }}}
void getParameters(ppd_file_t *ppd,int num_options,cups_option_t *options,ProcessingParameters ¶m) // {{{
{
// param.numCopies initially from commandline
if (param.numCopies==1) {
ppdGetInt(ppd,"Copies",¶m.numCopies);
}
if (param.numCopies==0) {
param.numCopies=1;
}
const char *val;
if ( (val=cupsGetOption("fitplot",num_options,options)) == NULL) {
if ( (val=cupsGetOption("fit-to-page",num_options,options)) == NULL) {
val=cupsGetOption("ipp-attribute-fidelity",num_options,options);
}
}
// TODO? pstops checks =="true", pdftops !is_false ... pstops says: fitplot only for PS (i.e. not for PDF, cmp. cgpdftopdf)
param.fitplot=(val)&&(!is_false(val));
if ( (ppd)&&(ppd->landscape>0) ) { // direction the printer rotates landscape (90 or -90)
param.normal_landscape=ROT_90;
} else {
param.normal_landscape=ROT_270;
}
int ipprot;
param.orientation=ROT_0;
if ( (val=cupsGetOption("landscape",num_options,options)) != NULL) {
if (!is_false(val)) {
param.orientation=param.normal_landscape;
}
} else if (optGetInt("orientation-requested",num_options,options,&ipprot)) {
/* IPP orientation values are:
* 3: 0 degrees, 4: 90 degrees, 5: -90 degrees, 6: 180 degrees
*/
if ( (ipprot<3)||(ipprot>6) ) {
error("Bad value (%d) for orientation-requested, using 0 degrees",ipprot);
} else {
static const Rotation ipp2rot[4]={ROT_0, ROT_90, ROT_270, ROT_180};
param.orientation=ipp2rot[ipprot-3];
}
}
ppd_size_t *pagesize;
// param.page default is letter, border 36,18
if ( (pagesize=ppdPageSize(ppd,0)) != NULL) { // "already rotated"
param.page.top=pagesize->top;
param.page.left=pagesize->left;
param.page.right=pagesize->right;
param.page.bottom=pagesize->bottom;
param.page.width=pagesize->width;
param.page.height=pagesize->length;
}
PageRect tmp; // borders (before rotation)
optGetFloat("page-top",num_options,options,&tmp.top);
optGetFloat("page-left",num_options,options,&tmp.left);
optGetFloat("page-right",num_options,options,&tmp.right);
optGetFloat("page-bottom",num_options,options,&tmp.bottom);
if ( (param.orientation==ROT_90)||(param.orientation==ROT_270) ) { // unrotate page
// NaN stays NaN
tmp.right=param.page.height-tmp.right;
tmp.top=param.page.width-tmp.top;
tmp.rotate_move(param.orientation,param.page.height,param.page.width);
} else {
tmp.right=param.page.width-tmp.right;
tmp.top=param.page.height-tmp.top;
tmp.rotate_move(param.orientation,param.page.width,param.page.height);
}
param.page.set(tmp); // replace values, where tmp.* != NaN (because tmp needed rotation, param.page not!)
if (ppdGetDuplex(ppd)) {
param.duplex=true;
} else if (is_true(cupsGetOption("Duplex",num_options,options))) {
param.duplex=true;
param.setDuplex=true;
} else if ( (val=cupsGetOption("sides",num_options,options)) != NULL) {
if ( (strcasecmp(val,"two-sided-long-edge")==0)||
(strcasecmp(val,"two-sided-short-edge")==0) ) {
param.duplex=true;
param.setDuplex=true;
} else if (strcasecmp(val,"one-sided")!=0) {
error("Unsupported sides value %s, using sides=one-sided!",val);
}
}
// default nup is 1
int nup=1;
if (optGetInt("number-up",num_options,options,&nup)) {
if (!NupParameters::possible(nup)) {
error("Unsupported number-up value %d, using number-up=1!",nup);
nup=1;
}
// TODO ; TODO? nup enabled? ... fitplot
// NupParameters::calculate(nup,param.nup);
NupParameters::preset(nup,param.nup);
}
if ( (val=cupsGetOption("number-up-layout",num_options,options)) != NULL) {
if (!parseNupLayout(val,param.nup)) {
error("Unsupported number-up-layout %s, using number-up-layout=lrtb!",val);
param.nup.first=Axis::X;
param.nup.xstart=Position::LEFT;
param.nup.ystart=Position::TOP;
}
}
if ( (val=cupsGetOption("page-border",num_options,options)) != NULL) {
if (!parseBorder(val,param.border)) {
error("Unsupported page-border value %s, using page-border=none!",val);
param.border=BorderType::NONE;
}
}
if ( (val=cupsGetOption("OutputOrder",num_options,options)) != NULL) {
param.reverse=(strcasecmp(val,"Reverse")==0);
} else if (ppd) {
param.reverse=ppdDefaultOrder(ppd);
}
// TODO: pageLabel (not used)
// param.pageLabel=cupsGetOption("page-label",num_options,options); // strdup?
if ( (val=cupsGetOption("page-set",num_options,options)) != NULL) {
if (strcasecmp(val,"even")==0) {
param.oddPages=false;
} else if (strcasecmp(val,"odd")==0) {
param.evenPages=false;
} else if (strcasecmp(val,"all")!=0) {
error("Unsupported page-set value %s, using page-set=all!",val);
}
}
if ( (val=cupsGetOption("page-ranges",num_options,options)) != NULL) {
parseRanges(val,param.pageRange);
}
ppd_choice_t *choice;
if ( (choice=ppdFindMarkedChoice(ppd,"MirrorPrint")) != NULL) {
val=choice->choice;
} else {
val=cupsGetOption("mirror",num_options,options);
}
param.mirror=is_true(val);
if ( (val=cupsGetOption("emit-jcl",num_options,options)) != NULL) {
param.emitJCL=!is_false(val)&&(strcmp(val,"0")!=0);
}
param.booklet=BookletMode::BOOKLET_OFF;
if ( (val=cupsGetOption("booklet",num_options,options)) != NULL) {
if (strcasecmp(val,"shuffle-only")==0) {
param.booklet=BookletMode::BOOKLET_JUSTSHUFFLE;
} else if (is_true(val)) {
param.booklet=BookletMode::BOOKLET_ON;
} else if (!is_false(val)) {
error("Unsupported booklet value %s, using booklet=off!",val);
}
}
param.bookSignature=-1;
if (optGetInt("booklet-signature",num_options,options,¶m.bookSignature)) {
if (param.bookSignature==0) {
error("Unsupported booklet-signature value, using booklet-signature=-1 (all)!",val);
param.bookSignature=-1;
}
}
if ( (val=cupsGetOption("position",num_options,options)) != NULL) {
if (!parsePosition(val,param.xpos,param.ypos)) {
error("Unrecognized position value %s, using position=center!",val);
param.xpos=Position::CENTER;
param.ypos=Position::CENTER;
}
}
param.collate=optGetCollate(num_options,options);
// FIXME? pdftopdf also considers if ppdCollate is set (only when cupsGetOption is /not/ given) [and if is_true overrides param.collate=true] -- pstops does not
/*
// TODO: scaling
// TODO: natural-scaling
scaling
if ((val = cupsGetOption("scaling",num_options,options)) != 0) {
scaling = atoi(val) * 0.01;
fitplot = gTrue;
} else if (fitplot) {
scaling = 1.0;
}
if ((val = cupsGetOption("natural-scaling",num_options,options)) != 0) {
naturalScaling = atoi(val) * 0.01;
}
bool checkFeature(const char *feature, int num_options, cups_option_t *options) // {{{
{
const char *val;
ppd_attr_t *attr;
return ( (val=cupsGetOption(feature,num_options,options)) != NULL && is_true(val)) ||
( (attr=ppdFindAttr(ppd,feature,0)) != NULL && is_true(attr->val));
}
// }}}
*/
// make pages a multiple of two (only considered when duplex is on).
// i.e. printer has hardware-duplex, but needs pre-inserted filler pages
// FIXME? pdftopdf also supports it as cmdline option (via checkFeature())
ppd_attr_t *attr;
if ( (attr=ppdFindAttr(ppd,"cupsEvenDuplex",0)) != NULL) {
param.evenDuplex=is_true(attr->value);
}
// TODO? pdftopdf* ?
// TODO?! pdftopdfAutoRotate
}
// }}}
static bool printerWillCollate(ppd_file_t *ppd) // {{{
{
ppd_choice_t *choice;
if ( ( (choice=ppdFindMarkedChoice(ppd,"Collate")) != NULL)&&
(is_true(choice->choice)) ) {
// printer can collate, but also for the currently marked ppd features?
ppd_option_t *opt=ppdFindOption(ppd,"Collate");
return (opt)&&(!opt->conflicted);
}
return false;
}
// }}}
void calculate(ppd_file_t *ppd,ProcessingParameters ¶m) // {{{
{
param.deviceReverse=false;
if (param.reverse) {
// test OutputOrder of hardware (ppd)
if (ppdFindOption(ppd,"OutputOrder") != NULL) {
param.deviceReverse=true;
param.reverse=false;
} else {
// Enable evenDuplex or the first page may be empty.
param.evenDuplex=true; // disabled later, if non-duplex
}
}
if (param.numCopies==1) {
// collate is not needed
param.collate=false; // does not make a big difference for us
}
/* TODO? instead:
if (...numOutputPages==1 [after nup,evenDuplex!]) {
param.collate=false; // does not make a big difference for us
}
*/
#if 0 // for now
// enable hardware copy generation
if (ppd) {
if (!ppd->manual_copies) {
// use hardware copying
param.deviceCopies=param.numCopies;
param.numCopies=1;
} else {
param.deviceCopies=1;
}
}
#endif
setFinalPPD(ppd,param);
// check collate device, with current ppd settings
if (param.collate) {
if (param.deviceCopies==1) { // e.g. ppd->manual_copies
param.deviceCollate=false;
} else {
param.deviceCollate=printerWillCollate(ppd);
}
if (!param.deviceCollate) {
ppdMarkOption(ppd,"Collate","False"); // disable any hardware-collate
param.evenDuplex=true; // software collate always needs fillers
}
}
if (!param.duplex) {
param.evenDuplex=false;
}
}
// }}}
// reads from stdin into temporary file. returns FILE * or NULL on error
// TODO? to extra file (also used in pdftoijs, e.g.)
FILE *copy_stdin_to_temp() // {{{
{
char buf[BUFSIZ];
int n;
// FIXME: what does >buf mean here?
int fd=cupsTempFd(buf,sizeof(buf));
if (fd<0) {
error("Can't create temporary file");
return NULL;
}
// remove name
unlink(buf);
// copy stdin to the tmp file
while ( (n=read(0,buf,BUFSIZ)) > 0) {
if (write(fd,buf,n) != n) {
error("Can't copy stdin to temporary file");
close(fd);
return NULL;
}
}
if (lseek(fd,0,SEEK_SET) < 0) {
error("Can't rewind temporary file");
close(fd);
return NULL;
}
FILE *f;
if ( (f=fdopen(fd,"rb")) == 0) {
error("Can't fdopen temporary file");
close(fd);
return NULL;
}
return f;
}
// }}}
int main(int argc,char **argv)
{
if ( (argc<6)||(argc>7) ) {
fprintf(stderr,"Usage: %s job-id user title copies options [file]\n",argv[0]);
#ifdef DEBUG
ProcessingParameters param;
std::unique_ptr<PDFTOPDF_Processor> proc1(PDFTOPDF_Factory::processor());
param.page.width=595.276; // A4
param.page.height=841.89;
param.page.top=param.page.bottom=36.0;
param.page.right=param.page.left=18.0;
param.page.right=param.page.width-param.page.right;
param.page.top=param.page.height-param.page.top;
// param.nup.calculate(4,0.707,0.707,param.nup);
param.nup.nupX=2;
param.nup.nupY=2;
/*
*/
//param.nup.yalign=TOP;
param.border=BorderType::ONE;
//param.mirror=true;
//param.reverse=true;
//param.numCopies=3;
if (!proc1->loadFilename("in.pdf")) return 2;
param.dump();
if (!processPDFTOPDF(*proc1,param)) return 3;
emitComment(*proc1,param);
proc1->emitFilename("out.pdf");
#endif
return 1;
}
try {
ProcessingParameters param;
param.jobId=atoi(argv[1]);
param.user=argv[2];
param.title=argv[3];
param.numCopies=atoi(argv[4]);
// TODO?! sanity checks
int num_options=0;
cups_option_t *options=NULL;
num_options=cupsParseOptions(argv[5],num_options,&options);
ppd_file_t *ppd=NULL;
ppd=ppdOpenFile(getenv("PPD")); // getenv (and thus ppd) may be null. This will not cause problems.
ppdMarkDefaults(ppd);
cupsMarkOptions(ppd,num_options,options);
getParameters(ppd,num_options,options,param);
calculate(ppd,param);
#ifdef DEBUG
param.dump();
#endif
cupsFreeOptions(num_options,options);
std::unique_ptr<PDFTOPDF_Processor> proc(PDFTOPDF_Factory::processor());
if (argc==7) {
if (!proc->loadFilename(argv[6])) {
ppdClose(ppd);
return 1;
}
} else {
FILE *f=copy_stdin_to_temp();
if ( (!f)||
(!proc->loadFile(f,TakeOwnership)) ) {
ppdClose(ppd);
return 1;
}
}
/* TODO
// color management
--- PPD:
copyPPDLine_(fp_dest, fp_src, "*PPD-Adobe: ");
copyPPDLine_(fp_dest, fp_src, "*cupsICCProfile ");
copyPPDLine_(fp_dest, fp_src, "*Manufacturer:");
copyPPDLine_(fp_dest, fp_src, "*ColorDevice:");
copyPPDLine_(fp_dest, fp_src, "*DefaultColorSpace:");
if (cupsICCProfile) {
proc.addCM(...,...);
}
*/
if (!processPDFTOPDF(*proc,param)) {
ppdClose(ppd);
return 2;
}
emitPreamble(ppd,param); // ppdEmit, JCL stuff
emitComment(*proc,param); // pass information to subsequent filters viia PDF comments
// proc->emitFile(stdout);
proc->emitFilename(NULL);
emitPostamble(ppd,param);
ppdClose(ppd);
} catch (std::exception &e) {
// TODO? exception type
fprintf(stderr,"Exception: %s\n",e.what());
return 5;
} catch (...) {
fprintf(stderr,"Unknown exception caught. Exiting.\n");
return 6;
}
return 0;
}
<file_sep>/pdftopdf_jcl.cc
#include <ctype.h>
#include "pdftopdf_processor.h"
#include <cups/ppd.h>
#include <string.h>
// TODO: -currently changes ppd. (Copies)
//
static void emitJCLOptions(FILE *fp, ppd_file_t *ppd, int deviceCopies) // {{{
{
int section;
ppd_choice_t **choices;
int i;
char buf[1024];
ppd_attr_t *attr;
bool withJCL=false,
datawritten=false;
if (!ppd) return;
if ((attr = ppdFindAttr(ppd,"pdftopdfJCLBegin",NULL)) != NULL) {
withJCL=true;
const int n=strlen(attr->value);
for (i = 0;i < n;i++) {
if (attr->value[i] == '\r' || attr->value[i] == '\n') {
// skip new line
continue;
}
fputc(attr->value[i],fp);
datawritten=true;
}
}
snprintf(buf,sizeof(buf),"%d",deviceCopies);
if (ppdFindOption(ppd,"Copies") != NULL) {
ppdMarkOption(ppd,"Copies",buf);
} else {
if ((attr = ppdFindAttr(ppd,"pdftopdfJCLCopies",buf)) != NULL) {
fputs(attr->value,fp);
datawritten=true;
} else if (withJCL) {
fprintf(fp,"Copies=%d;",deviceCopies);
datawritten=true;
}
}
for (section = (int)PPD_ORDER_ANY;
section <= (int)PPD_ORDER_PROLOG;section++) {
int n = ppdCollect(ppd,(ppd_section_t)section,&choices);
for (i = 0;i < n;i++) {
snprintf(buf,sizeof(buf),"pdftopdfJCL%s",
((ppd_option_t *)(choices[i]->option))->keyword);
if ((attr = ppdFindAttr(ppd,buf,choices[i]->choice)) != NULL) {
fputs(attr->value,fp);
datawritten=true;
} else if (withJCL) {
fprintf(fp,"%s=%s;",
((ppd_option_t *)(choices[i]->option))->keyword,
choices[i]->choice);
datawritten=true;
}
}
}
if (datawritten) {
fputc('\n',fp);
}
}
// }}}
/* Copied ppd_decode() from CUPS which is not exported to the API; needed in emitPreamble() */
// {{{ static int ppd_decode(char *string)
static int /* O - Length of decoded string */
ppd_decode(char *string) /* I - String to decode */
{
char *inptr, /* Input pointer */
*outptr; /* Output pointer */
inptr = string;
outptr = string;
while (*inptr != '\0')
if (*inptr == '<' && isxdigit(inptr[1] & 255))
{
/*
* Convert hex to 8-bit values...
*/
inptr ++;
while (isxdigit(*inptr & 255))
{
if (isalpha(*inptr))
*outptr = (tolower(*inptr) - 'a' + 10) << 4;
else
*outptr = (*inptr - '0') << 4;
inptr ++;
if (!isxdigit(*inptr & 255))
break;
if (isalpha(*inptr))
*outptr |= tolower(*inptr) - 'a' + 10;
else
*outptr |= *inptr - '0';
inptr ++;
outptr ++;
}
while (*inptr != '>' && *inptr != '\0')
inptr ++;
while (*inptr == '>')
inptr ++;
}
else
*outptr++ = *inptr++;
*outptr = '\0';
return ((int)(outptr - string));
}
// }}}
void emitPreamble(ppd_file_t *ppd,const ProcessingParameters ¶m) // {{{
{
if (ppd == 0) return;
ppdEmit(ppd,stdout,PPD_ORDER_EXIT);
if (param.emitJCL) {
/* pdftopdf only adds JCL to the job if the printer is a native PDF
printer and the PPD is for this mode, having the "*JCLToPDFInterpreter:"
keyword. We need to read this keyword manually from the PPD and replace
the content of ppd->jcl_ps by the value of this keyword, so that
ppdEmitJCL() actually adds JCL based on the presence on
"*JCLToPDFInterpreter:". */
ppd_attr_t *attr;
if ( (attr=ppdFindAttr(ppd,"JCLToPDFInterpreter",NULL)) != NULL) {
ppd->jcl_ps=strdup(attr->value);
ppd_decode(ppd->jcl_ps);
} else {
ppd->jcl_ps=NULL;
}
ppdEmitJCL(ppd,stdout,param.jobId,param.user,param.title);
emitJCLOptions(stdout,ppd,param.deviceCopies);
}
}
// }}}
void emitPostamble(ppd_file_t *ppd,const ProcessingParameters ¶m) // {{{
{
if (param.emitJCL) {
ppdEmitJCLEnd(ppd,stdout);
}
}
// }}}
// pass information to subsequent filters via PDF comments
void emitComment(PDFTOPDF_Processor &proc,const ProcessingParameters ¶m) // {{{
{
std::vector<std::string> output;
output.push_back("% This file was generated by pdftopdf");
// This is not standard, but like PostScript.
if (param.deviceCopies>0) {
char buf[256];
snprintf(buf,sizeof(buf),"%d",param.deviceCopies);
output.push_back(std::string("%%PDFTOPDFNumCopies : ")+buf);
if (param.deviceCollate) {
output.push_back("%%PDFTOPDFCollate : true");
} else {
output.push_back("%%PDFTOPDFCollate : false");
}
}
proc.setComments(output);
}
// }}}
|
750a3811598b124ee893b6b7be616ad0d2ccd376
|
[
"Makefile",
"C++"
] | 11
|
C++
|
smilingthax/pdftopdf
|
ec5f3c95b6ab9acf60243142b6911ee47677d900
|
3d285f4ef6455bc5f2a25002f20f1fae18b40a50
|
refs/heads/master
|
<file_sep># NewsAggregator
What is News aggregator?
Created a news web page that crawls news from various websites and displays it on this website. This website is completely implementd on AWS platform.
How I created it?
I crawled the data from 3 various websites and stored the data as a csv file. Then created a DynamoDB table to store the data. Then created the DynamoDB table as the Backend for my website and used NodeJS and Javascript to build the website hosted on AWS EC2 instance.
How to run the code?
Create a DyanmoDB table on AWS and then an EC2 instance. Run the sample_crawler_2 file. Then download the NodeJS on EC2 instance and run server.js file on the EC2 instance and you will see that the website is running on localhost port 3000.
<file_sep>$(document).ready(function() {
var NewsData = "sample.json";
$.getJSON(NewsData, function(data) {
$.each(data, function(i, f) {
var NewsList = "<li>"+"<a href=" + f.link +">"+ "<h2>"+ f.Headlines + "</h2>" + "</a>"+"</li>"
$(NewsList).appendTo("#userdata");
});
});
});
|
60ddad009db77a4bc0a3d1f3ddba0a15d8dba908
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
narvasumana/NewsAggregator
|
0186470d8a9550f78d402c8cebefc4eba31312d5
|
cd4f3cab7448db5737ed3c968953bd77b42b3d4e
|
refs/heads/master
|
<repo_name>kinoeater/cafetownsend<file_sep>/src/main/java/properties/config.properties
#browser=chrome
#Didn't need config file for this test cases but it is always good to have for future purposes
<file_sep>/src/main/java/stepDefinitions/WebScenarios.java
package stepDefinitions;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.openqa.selenium.Alert;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import com.paulhammant.ngwebdriver.ByAngular;
import cucumber.api.DataTable;
import cucumber.api.Scenario;
import cucumber.api.java.After;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import pageObjects.Base_Page;
import pageObjects.Page_Objects;
public class WebScenarios extends Page_Objects {
public WebScenarios() throws IOException {
super();
}
/**********************************************************************************
**LOGIN FUNCTION STEP DEFINITIONS
**********************************************************************************/
@Given("^User navigates to login page with \"([^\"]*)\" browser$")
public static void user_navigates_to_login_page_with_browser(String browser) throws Throwable {
goToLoginPage(browser);
}
@Then("^User should still be in login page$")
public void user_should_still_be_in_login_page() throws Throwable {
Thread.sleep(2000);
Base_Page.verify("Login", loginButton);
}
@When("^User clicks on the login$")
public void user_clicks_on_the_login() throws Throwable {
driver.findElement(loginButton).click();
Base_Page.waitAndClickElement(driver.findElement(loginButton));
}
@And("^User logs out$")
public void user_logs_out() throws Throwable {
Base_Page.actionMoveAndClick(driver.findElement(logoutButton));
}
@Then("^User should be at home page$")
public void user_should_be_at_home_page() throws Throwable {
Base_Page.waitForPresenceOfElement(greetings);
Base_Page.verify("Hello Luke", greetings);
}
@Then("^User should see login error message$")
public void user_should_see_login_error_message() throws Throwable {
Base_Page.waitForPresenceOfElement(loginError);
Base_Page.verify("Invalid username or password!", loginError);
}
@And("^User enters following credentials for login$")
public void user_enters_following_credentials_for_login(DataTable table) throws Throwable {
List < Map < String, String >> list = table.asMaps(String.class, String.class);
for (int i = 0; i < list.size(); i++) {
Base_Page.sendKeysToWebElement(driver.findElement(userName), list.get(i).get("username"));
Base_Page.sendKeysToWebElement(driver.findElement(passWord), list.get(i).get("password"));
}
}
/**********************************************************************************
**CREATE FUNCTION STEP DEFINITIONS
**********************************************************************************/
@When("^User clicks on the Add button$")
public void user_clicks_on_the_add_button() throws Exception {
Base_Page.actionMoveAndClick(driver.findElement(createAddButton));
}
@Then("^User should see \"([^\"]*)\" in the employees list$")
public void user_should_see_something_in_the_employees_list(String NameToCheck) throws Throwable {
ngWebdriver.waitForAngularRequestsToFinish();
List < WebElement > employees = driver.findElements(ByAngular.exactRepeater("employee in employees"));
for (WebElement employee: employees) {
try {
// System.out.println(NameToCheck + " is successfully added!");
String exportedName = employee.getText();
Assert.assertTrue(exportedName.equalsIgnoreCase(NameToCheck));
// Assert.assertTrue(exportedName.contains(NameToCheck));
break;
} catch (AssertionError error) {
} catch (Exception e) {
}
}
}
@And("^User clicks on the Create button$")
public void user_clicks_on_the_create_button() throws Throwable {
ngWebdriver.waitForAngularRequestsToFinish(); // wait for angular activity
Base_Page.actionMoveAndClick(driver.findElement(createButton));
}
@And("^User should be in new user page$")
public void user_should_be_in_new_user_page() throws Throwable {
Base_Page.waitForPresenceOfElement(createCancelButton);
}
@And("^User enters following details for new user$")
public void user_enters_following_details_for_new_user(DataTable table) throws Throwable {
List < Map < String, String >> list = table.asMaps(String.class, String.class);
for (int i = 0; i < list.size(); i++) {
Base_Page.sendKeysToWebElement(driver.findElement(createUserName), list.get(i).get("First_name"));
Base_Page.sendKeysToWebElement(driver.findElement(createPassWord), list.get(i).get("Last_name"));
Base_Page.sendKeysToWebElement(driver.findElement(createStartDate), list.get(i).get("Start_date"));
Base_Page.sendKeysToWebElement(driver.findElement(createEmail), list.get(i).get("Email"));
}
}
@When("^User hits enter$")
public void user_hits_enter() throws Throwable {
driver.findElement(createEmail).sendKeys(Keys.ENTER);
}
@Then("^User should see the alert message$")
public void user_should_see_the_alert_message() throws Throwable {
Thread.sleep(3000);
String expectedAlertMessage = "Error trying to create a new employee: {\"start_date\":[\"can't be blank\"]})";
Alert alert = driver.switchTo().alert();
String actualAlertMessage = alert.getText();
// System.out.println("THIS IS ACTUAL ALERT: " + actualAlertMessage);
// System.out.println("THIS IS EXPECTED ALERT: " + expectedAlertMessage);
Assert.assertTrue(expectedAlertMessage.equalsIgnoreCase(actualAlertMessage));
alert.accept();
}
@Then("^User should still be at new user page$")
public void user_should_still_be_at_new_user_page() throws Throwable {
Base_Page.waitForPresenceOfElement(createCancelButton);
}
@And("^User deletes \"([^\"]*)\"$")
public void user_deletes_something(String nameToDelete) throws Throwable {
List < WebElement > employees = driver.findElements(ByAngular.exactRepeater("employee in employees"));
Actions actions = new Actions(driver);
for (WebElement employee: employees) {
try {
String exportedName = employee.getText();
if (exportedName.contentEquals(nameToDelete)) {
actions.click(employee).build().perform();
Thread.sleep(2000);
driver.findElement(deleteButton).click();
Alert alert = driver.switchTo().alert();
System.out.println("Alert message: " + alert.getText());
alert.accept();
}
} catch (NoAlertPresentException e) {
e.printStackTrace();
}
}
}
/**********************************************************************************
**AFTER SCENARIO
**********************************************************************************/
@After
public void tearDownAndScreenshotOnFailure(Scenario scenario) {
try {
if (driver != null && scenario.isFailed()) {
Base_Page.captureScreenshot();
driver.manage().deleteAllCookies();
driver.quit();
driver = null;
}
if (driver != null) {
driver.manage().deleteAllCookies();
driver.quit();
driver = null;
}
}
catch (Exception e) {
System.out.println("Methods failed, Exception: " + e.getMessage());
}
}
}<file_sep>/README.md
#### Automating an Angular Web Page with Page Objects and Cucumber Framework by the help of ngWebDriver
#### You can also read the same information with PDF format by clicking following link.
https://github.com/kinoeater/cafetownsend/blob/master/MOBIQUITY_QA%20TASK.pdf
## CAFETOWNSEND WEB APPLICATION TESTS:
## I. Introduction
This document mainly serves as the plan for testing all software artifacts as well as the reporting of test results.
## II. Automation Framework
### Why " NGWebDriver " but not Protractor?
At first, I was thinking to automate the test cases by using protractor. Although I had some experience on that tool (there is a small project on my github) and it is a good fit for angular apps, I also want to benefit from page objects metodology and Cucumber framework. That was the point I came up to use NGWebDriver. NGWebDriver is a small open source library of WebDriver locators created by " <NAME> " and more for AngularJS (v1.x) and Angular (v2.x +), for Java. It works with Firefox, Chrome and all the other Selenium-WebDriver browsers.
https://github.com/paul-hammant/ngWebDriver
#### Downside of using NGWebDriver:
Unfortunately, it is not a magic tool that makes QA people happy with angular app testing. Sometimes it is causing synchronization issues.
### Why " Cucumber" and "Page Objects"?
By using NGWebDriver library we can handle angular application easily and create page objects with ByAngular locator helper. Another thing page objects design pattern helps us to enhance test maintenance and reduces code duplication. Maybe the best part of this framework is using Gherkin language to create easily readable test cases within the automation. They are are also reusable and easy to edit. Moreover, tomorrow if we want to add more tests, it is very easy, we can pick proper methods from the base page then stick with the step definitions of the gherkin files.
#### Cucumber Framework
You can choose firefox or chrome at the Gherkin level. You do not need to bother with updating the browser drivers, because Bonigarcia’s webdriver manager will easily handle it. If you want to use different browsers like IE, code can also be modified.
Page Object page has its specific web elements in it and Base Page has some specific easy to use methods. More methods can be added if required. It is like a toolbox of the framework, use the gadgets, add new gadgets when you want.
### Scenario: Successfully creates a new user then deletes it
Given User should be at home page
And User clicks on the Create button
And User should be in new user page
And User enters following details for new user
| First_name | Last_name | Start_date | Email |
| Alfred | Pennyworth | 1933-03-14 | <EMAIL> |
When User clicks on the Add button
Then User should see "<NAME>" in the employees list
And User deletes "<NAME>"
# This one deletes newly added employee, so same credentials can be used next time
And User logs out
### What about reporting?
I used Cucumber Extent Report as reporting tool.
After each test run latest test report can be seen with "report.html" name under /output directory.
Report can be opened simply double clicking on the item.
#### Running the Tests
##### 1. By directly using runner class on IDE
###### Prerequisites
*Install Java and Maven to your machine.
*Install an IDE of your choice, Eclipse or Intellij.
*Install cucumber, gherkin and Test NG plugins to your IDE.
a) You should open / choose one of the runner classes under /check_24_Framework/src/test/java/runners
b) Then you should right click on the page or on the class,
c) Then you should click on TestNG option.
##### 2. By using "mvn test" command on CLI
###### Prerequisites
*Install Java and Maven to your machine.
a) You go to root directory of the maven project from command line (CMD / terminal)
b) Then type followings
mvn test
c) Then hit enter
###### Surefire plugin is added to the POM, so you can also put the Jenkins in work
## III. Manual Test Cases
Black box manual test cases that will run on the code. Rather creating all of the test cases I wrote down the test cases for login and create new user functionalities.
The URL: http://cafetownsend-angular-rails.herokuapp.com
### Login functionality tests:
a) Verify that user can successfully login with correct credentials.
b) Verify that user cannot login with incorrect user name.
c) Verify that user cannot login with incorrect password.
d) Verify that user cannot login with empty email
e) Verify that user cannot login with empty password
f) Verify that user cannot login with empty email and empty password
### Create new employee functionality tests:
a) Verify that user can successfully create a new user by entering whole credentials correctly, then deletes newly created user entry.
## Gherkin format:
### Scenario: Successfully creates a new user then deletes it
Given User should be at home page
And User clicks on the Create button
And User should be in new user page
And User enters following details for new user
| First_name | Last_name | Start_date | Email |
| Alfred | Pennyworth | 1933-03-14 | <EMAIL> |
When User clicks on the Add button
Then User should see "<NAME>" in the employees list
And User deletes "<NAME>"
# This one deletes newly added employee, so same credentials can be used next time
And User logs out
b) Verify that User leaves the first name area empty, then cannot create the new user entry.
c) Verify that User leaves the last name area empty, then cannot create the new user entry.
d) Verify that User leaves the start date area empty, then cannot create the new user entry.
d) Verify that User leaves the email area empty or enters email without ' @ ' sign, then cannot create the new user entry.
e) Verify that User enters whole credentials correctly, then hits "enter key" on keyboard instead of using Add button, then successfully creates a new user.
f) Verify that User enters incorrect date format, then presented with an alert and cannot create the new user entry.
|
5513dd9d03aaca2811c427e4fdecaba18f257c23
|
[
"Markdown",
"Java",
"INI"
] | 3
|
INI
|
kinoeater/cafetownsend
|
ae1c21b2cef2bd93118b493da426307ad0e44918
|
eaf03678507ac9dec476cc4215767c7432106be9
|
refs/heads/master
|
<repo_name>lokki-labs/blog-tutorials<file_sep>/sparkvue-tutorial/vue.config.js
const path = require('path');
const outputDirectory = path.resolve(__dirname, 'src', 'main', 'resources', 'public');
const contentBaseDir = path.resolve(__dirname, 'src', 'main', 'resources', 'assets');
const entryFile = path.resolve(__dirname, 'src', 'main','javascript', 'main.js');
const indexHtmlTemplate = path.resolve(__dirname, 'src', 'main','resources', 'templates', 'index.html');
module.exports = {
publicPath: '/',
outputDir: outputDirectory,
assetsDir: '',
devServer: {
contentBase: contentBaseDir,
compress: true,
port: 9000
},
pages: {
index: {
// entry for the page
entry: entryFile,
// the source template
template: indexHtmlTemplate,
// output as dist/index.html
filename: 'index.html',
// when using title option,
// template title tag needs to be <title><%= htmlWebpackPlugin.options.title %></title>
title: 'Vue with Java',
// This is a custom option to inject the base url in a script tag
// <script type="text/javascript">
// window._apiBaseUri="<%= htmlWebpackPlugin.options.apiBaseUri %>";
// </script>
apiBaseUri: 'http://localhost:4567/',
// chunks to include on this page, by default includes
// extracted common chunks and vendor chunks.
chunks: ['chunk-vendors', 'chunk-common', 'index']
}
}
}<file_sep>/sparkjava-micrometer-prometheus/src/main/java/com/yourdomain/sparkprometheus/PrometheusSparkServer.java
package com.yourdomain.sparkprometheus;
import io.micrometer.prometheus.PrometheusMeterRegistry;
/**
* Server for exposing Prometheus metrics.
* With additional functionality for turning the server on/off.
*/
public class PrometheusSparkServer {
private final PrometheusMeterRegistry prometheusRegistry;
private final spark.Service server;
public PrometheusSparkServer(String host, int port, PrometheusMeterRegistry metricRegistry) {
prometheusRegistry = metricRegistry;
server = spark.Service.ignite();
server.ipAddress(host);
server.port(port);
}
public void start() {
server.get("/metrics", (req, res) -> prometheusRegistry.scrape());
server.awaitStop();
}
}<file_sep>/README.md
NNDI Blog tutorials
===
Source code for some tutorials that appear on [NNDI Blog](https://blog.nndi-tech.com/tutorials/)
<file_sep>/sparkvue-tutorial/src/main/java/com/yourdomain/sparkvue/Main.java
package com.yourdomain.sparkvue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import spark.Spark;
import org.slf4j.LoggerFactory;
import static spark.Spark.redirect;
public class Main {
// We use Java's new Record class feature to create an immutable class
public static record Person(
String firstname, String lastname,
int age, String occupation,
String location, String relationship) {}
public static void main(String... args) {
final Gson gson = new Gson();
final List<Person> people = fetchPeople();
Spark.port(4567);
// root is 'src/main/resources', so put files in 'src/main/resources/public'
Spark.staticFiles.location("/public");
addCORS();
redirect.get("/", "/public/index.html");
Spark.get("/people", (request, response) -> {
response.type("application/json;charset=utf-8");
return gson.toJson(people);
});
LoggerFactory.getLogger(Main.class).info("========== API RUNNING =================");
}
public static List<Person> fetchPeople() {
List<Person> m = new ArrayList<>();
m.add(new Person("Bob", "Banda", 13, "Future Accountant", "Blantyre", "Self"));
m.add(new Person("John", "Banda", 68, "Accountant", "Blantyre", "Father"));
m.add(new Person("Mary", "Banda", 8, "Accountant", "Blantyre", "Mother"));
m.add(new Person("James", "Banda", 18, "Accountant", "Blantyre", "Brother"));
m.add(new Person("Jane", "Banda", 8, "Student", "Blantyre", "Sister"));
m.add(new Person("John", "Doe", 22, "Developer", "Lilongwe", "Cousin"));
m.add(new Person("Brian", "Banda", 32, "Student", "Blantyre", "Best Friend"));
m.add(new Person("Hannibal", "Kaya", 12, "Jerk", "Blantyre", "Arch Enemy"));
return m;
}
private static final HashMap<String, String> corsHeaders = new HashMap<String, String>();
static {
corsHeaders.put("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
corsHeaders.put("Access-Control-Allow-Origin", "*");
corsHeaders.put("Access-Control-Allow-Headers", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin,");
corsHeaders.put("Access-Control-Allow-Credentials", "true");
}
public final static void addCORS() {
Spark.after((request, response) -> {
corsHeaders.forEach((key, value) -> {
response.header(key, value);
});
});
}
}<file_sep>/sparkjava-micrometer-prometheus/src/main/java/com/yourdomain/sparkprometheus/Main.java
package com.yourdomain.sparkprometheus;
import com.creditdatamw.zerocell.Reader;
import com.google.gson.Gson;
import io.micrometer.prometheus.PrometheusConfig;
import io.micrometer.prometheus.PrometheusMeterRegistry;
import spark.Spark;
import javax.servlet.MultipartConfigElement;
import javax.servlet.http.Part;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
public class Main {
private static final Map<String, List<Person>> db = new ConcurrentHashMap<>();
public static void main(String... args) {
final PrometheusMeterRegistry registry= new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
final Gson gson = new Gson();
final int port = 4567;
Spark.port(port);
Spark.post("/upload/people", (request, response) -> {
request.attribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement("/temp"));
Part filePart = request.raw().getPart("file"); //file is name of the upload form
if (filePart == null)
return Spark.halt(400);
if (filePart.getInputStream() == null)
return Spark.halt(400);
registry.counter("file.uploads", "endpoint", "/upload/people").increment();
Path tmpPath = Files.createTempFile("z","xlsx");
Files.copy(filePart.getInputStream(), tmpPath, StandardCopyOption.REPLACE_EXISTING);
List<Person> people = Reader.of(Person.class)
.from(tmpPath.toFile())
.list();
registry.counter("people.total").increment(people.size());
registry.counter("people.fetch", "endpoint", "/upload/people").increment();
db.put(filePart.getSubmittedFileName(), people);
response.type("application/json;charset=utf-8");
return gson.toJson(people);
});
Spark.get("/people/all", (request, response) -> {
registry.counter("people.fetch", "endpoint", "/people/all").increment();
List<Person> allPeople = db.values()
.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
response.type("application/json;charset=utf-8");
return gson.toJson(allPeople);
});
new PrometheusSparkServer("localhost", 4550, registry).start();
}
}
|
b32d8da3287ad1fa9d676ca7b77f358b5db8e297
|
[
"JavaScript",
"Java",
"Markdown"
] | 5
|
JavaScript
|
lokki-labs/blog-tutorials
|
d457b01c92b42fd51ce9372a3d700e22b133a75a
|
90fb2cd29b98b6ffdf35b0551032c553b9699b12
|
refs/heads/main
|
<repo_name>multi-ember-mfe/root-config<file_sep>/webpack.config.js
const webpackMerge = require("webpack-merge");
const singleSpaDefaults = require("webpack-config-single-spa");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = (webpackConfigEnv, argv) => {
const orgName = "ember";
const defaultConfig = singleSpaDefaults({
orgName,
projectName: "root-config",
webpackConfigEnv,
argv,
disableHtmlGeneration: true,
});
const merge = webpackMerge({
customizeArray: webpackMerge.unique(
"plugins",
["HtmlWebpackPlugin"],
(plugin) => plugin.constructor && plugin.constructor.name
),
});
return merge(
{
plugins: [
new HtmlWebpackPlugin({
inject: false,
template: "src/index.ejs",
templateParameters: {
isLocal: webpackConfigEnv && webpackConfigEnv.isLocal === "true",
orgName,
},
}),
],
},
defaultConfig,
{
devServer: {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods":
"GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers":
"X-Requested-With, content-type, Authorization",
},
},
}
);
};
|
7c1fcdacefcc77128f3c995413abb8545f976b61
|
[
"JavaScript"
] | 1
|
JavaScript
|
multi-ember-mfe/root-config
|
18b87e87a16cba8cd28b88192df2a88c26d6bbde
|
cfc706bea054c7c3bcbaf3174892e81a8ddbbef7
|
refs/heads/master
|
<repo_name>mElhadki/Create-Plugin<file_sep>/README.md
# Create-Plugin
## Description
it is a plugin with two submenus
one for the general information of the plugin and one for the settings.
## How To Run??
### Installing
steps to run this project
```
create folder named Maria
```
And
```
copy and paste all files in The Maria folder created before
```
after that
```
copy Maria folder and past it in your wordpress instalation under this following path
wp-content\plugins
```
finally
```
activate the Maria plugin from dashboard
```
<file_sep>/setting_page.php
<?php
function wphw_opt(){
require_once(ABSPATH . 'wp-config.php');
$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysqli_select_db($connection,DB_NAME);
$sql = "CREATE TABLE Maria(id int NOT NULL PRIMARY KEY AUTO_INCREMENT, username varchar(255) NOT NULL, descriptions varchar(255) NOT NULL, Options varchar(255) NOT NULL)";
$result = mysqli_query($connection, $sql);
return $result;
}
function insert(){
require_once(ABSPATH . 'wp-config.php');
$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysqli_select_db($connection,DB_NAME);
$username= $_POST['username'];
$descriptions = $_POST['descriptions'];
$Options= $_POST['Options'];
if(empty($_POST['username']) || empty($_POST['descriptions']) || empty($_POST['Options'] ))
{
echo '<div id="message" class="error">
<p>Content not added</p>
</div>';
exit();
}
else
{
$query="insert INTO Maria (username,descriptions,Options)". "VALUES ('$username', '$descriptions', '$Options')";
$result=mysqli_query($connection,$query);
}
}
if(isset($_POST['wphw_submit'])){
wphw_opt();
insert();
}
?>
<div class="wrap">
<div id="icon-options-general" class="icon32"> <br>
</div>
<h2>Plugin Settings</h2>
<?php if(isset($_POST['wphw_submit'])):?>
<div id="message" class="updated below-h2">
<p>Content added successfully</p>
</div>
<?php endif;?>
<div class="metabox-holder">
<div class="postbox">
<h3><strong>Enter all the informations and click on save button.</strong></h3>
<form method="post" action="">
<table class="form-table">
<tr>
<th scope="row"></th>
<td><input type="text" name="username" value="" style="width:350px;" placeholder="Username" /></td>
</tr>
<tr>
<th scope="row"></th>
<td><textarea name="descriptions" value="" style="width:350px;" placeholder="Description"></textarea></td>
</tr>
<tr>
<th scope="row"></th>
<td><select name="Options" style="width:350px;">
<option value="">--Select--</option>
<option name="OptionA" value="OptionA">Option A</option>
<option name="OptionB" value="OptionB">Option B</option>
</td>
</tr>
<tr>
<th scope="row"> </th>
<td style="padding-top:10px;padding-bottom:10px;">
<input type="submit" name="wphw_submit" value="Save" class="button-primary" style="width:10%;" />
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
<file_sep>/Maria.php
<?php
/*
Plugin Name: Maria
Description: Juste une extension de wordpress Simple avec 2 sous menus : un pour les informations générale du plugin et un pour les settings.
Version: 1.0
Author: <NAME>
License: GPLv2 or later
Text Domain: Maria
*/
?>
<?php
add_action('admin_menu', 'my_admin_menu');
function my_admin_menu () {
//parameters details
//add_menu_page(page_title,menu_title,capability,menu_slug,function = '')
//add_submenu_page(parent_slug,page_title,menu_title,capability,menu_slug,function):
//add_management_page($page_title, $menu_title, $capability,$menu_slug,$function);
//add a new setting page udner setting menu
//add_management_page('Description', 'Description', 'manage_options',__FILE__,'Description_admin_page');
//add new menu and its sub menu
add_menu_page('Description', 'Maria', 'manage_options','Description_page', 'Description_admin_page');
add_submenu_page('Description_page', 'Page', 'Settings','manage_options', 'Settings', 'mt_settings_page');
}
function Description_admin_page () {
require_once(ABSPATH . 'wp-config.php');
$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysqli_select_db($connection,DB_NAME);
$sql= "SELECT * FROM Maria";
$result = mysqli_query($connection, $sql);
echo '<div class="wrap">
<h1>Hello!</h1>
<p>it is a plugin with two submenus. A page for the general description of my plugin.Configuration page an input text field, textarea for the description,
an option list and a save button
</p>
<h1 style="margin-left:10px; margin-bottom:20px; color:Red;">List of information</h1>
<table style="width:80%;"align="center" border="1";>
<tr>
<td style="height:50px; text-align:center;">Username</td>
<td style="height:50px; text-align:center;">Description</td>
<td style="height:50px; text-align:center;">Option</td>';
foreach($result as $row){
?>
<tr>
<td style="text-align:center;"><?php echo $row["username"] ;?></td>
<td style="text-align:center;"><?php echo $row["descriptions"] ;?></td>
<td style="text-align:center;"><?php echo $row["Options"] ;?></td>
</tr>
<?php
}
echo"
</table>
</div>";
}
// mt_settings_page() displays the page content for the Test Settings submenu
function mt_settings_page() {
echo "<h2>" . __( 'Settings Configurations', 'menu-test' ) . "</h2>";
include_once('setting_page.php');
}
?>
|
afc1ac78c8260e77b953aa3b0cfd97848aff419f
|
[
"Markdown",
"PHP"
] | 3
|
Markdown
|
mElhadki/Create-Plugin
|
f8b21c12e07c6f464c7e083658b397ab169a7672
|
d82c5dd6c947d0d8fabcb193a6cb54d246b92d1e
|
refs/heads/master
|
<file_sep>import express from 'express';
import React from 'react';
const render = require('./SSR.js');
const app = express();
app.get('/', render.default);
const port = 3007;
app.listen(port);
console.log(`Listening on port ${port}`);
<file_sep>const React = require('react');
class Greeting extends React.Component{
render() {
const name = this.props.name;
return(
<div>
<h1>Hello my name is {name}!</h1>
<h2>It's very nice to meet you.</h2>
</div>
);
}
}
module.exports = Greeting;
<file_sep>const express = require('express');
const app = express();
const http = require('http');
app.use('/api', require('./routes.js'));
// app.use('/greeting', require('./greeting.jsx'));
app.set('views', __dirname + '/views');
app.set('view engine', 'jsx');
app.engine('jsx', require('express-react-views').createEngine());
app.listen(3000);
// const server = http.createServer(function(request, response) {
// response.write('Hello Express from http!');
// response.end();
// });
// server.listen(3000);
|
54aff14be37016f5ff326804ea9ddd4b50982408
|
[
"JavaScript"
] | 3
|
JavaScript
|
beebeean09/NodePractice
|
fd6bf3452e898710701e5684224c578e814950a8
|
50731e7ff0860ebd68b62153a8aa14d7b80b8ca9
|
refs/heads/master
|
<repo_name>matsuno1818/mutwo<file_sep>/spec/models/user_spec.rb
require 'rails_helper'
RSpec.describe User, type: :model do
describe '新規登録情報の保存' do
before do
@user = FactoryBot.build(:user)
end
it 'すべての値が正しく入力されていれば保存できること' do
expect(@user).to be_valid
end
it 'nicknameが空だと保存できないこと' do
@user.nickname = nil
@user.valid?
expect(@user.errors.full_messages).to include("Nickname can't be blank")
end
it 'nicknameが重複していると保存できないこと' do
@user.save
another_user = FactoryBot.build(:user, nickname: @user.nickname)
another_user.valid?
expect(another_user.errors.full_messages).to include("Nickname has already been taken")
end
it 'emailが空だと保存できないこと' do
@user.email = nil
@user.valid?
expect(@user.errors.full_messages).to include("Email can't be blank")
end
it 'emailが重複していると保存できないこと' do
@user.save
another_user = FactoryBot.build(:user, email: @user.email)
another_user.valid?
expect(another_user.errors.full_messages).to include("Email has already been taken")
end
it '@がないと保存できないこと' do
@user.email = 'aomori12'
@user.valid?
expect(@user.errors.full_messages).to include('Email is invalid')
end
it 'passwordが空だと保存できないこと' do
@user.password = nil
@user.valid?
expect(@user.errors.full_messages).to include("Password can't be blank")
end
it 'passwordが6文字以上でないと保存できないこと' do
@user.password = '<PASSWORD>'
@user.password_confirmation = '<PASSWORD>'
@user.valid?
expect(@user.errors.full_messages).to include('Password is too short (minimum is 6 characters)')
end
it 'passwordが存在してもpassword_confirmationが空では登録できないこと' do
@user.password_confirmation = ''
@user.valid?
expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password")
end
it 'last_nameが空だと保存できないこと' do
@user.last_name = nil
@user.valid?
expect(@user.errors.full_messages).to include("Last name can't be blank")
end
it 'last_nameが全角日本語でないと保存できないこと' do
@user.last_name = 'abe゙'
@user.valid?
expect(@user.errors.full_messages).to include("Last name Full-width characters")
end
it 'first_nameが空だと保存できないこと' do
@user.first_name = nil
@user.valid?
expect(@user.errors.full_messages).to include("First name can't be blank")
end
it 'first_nameが全角日本語でないと保存できないこと' do
@user.first_name = 'tarou'
@user.valid?
expect(@user.errors.full_messages).to include("First name Full-width characters")
end
it 'birthdayを選択していないと保存できないこと' do
@user.birthday = nil
@user.valid?
expect(@user.errors.full_messages).to include("Birthday can't be blank")
end
end
end
<file_sep>/app/models/user.rb
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :items
Nickname = /\A[ぁ-んァ-ン一-龥a-z0-9]+\z/i
Email = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
Password = /\A[a-z0-9]+\z{6,}/i
Zenkaku = /\A[ぁ-んァ-ン一-龥]/
with_options presence: true do
validates :nickname, uniqueness: true, format: {with: Nickname, message: "Nickname has already been taken" }
validates :email, uniqueness: true, format: { with: Email, message: "Email has already been taken" }
validates :password, format: { with: <PASSWORD>, message: "Password Include both letters and numbers" }
validates :last_name, :first_name, format: { with: Zenkaku, message: "Full-width characters" }
validates :birthday
end
end
|
2032898aeec6a59f73c36fec09fb8fddfad23a7a
|
[
"Ruby"
] | 2
|
Ruby
|
matsuno1818/mutwo
|
9e857300bf2ce31d98f017c3a011b99b1e7c60c4
|
5c447fdbc8226b8b941bca7f1682f6c9634b6538
|
refs/heads/master
|
<file_sep>## Project - HOIR1
## Collation started on 14 Jun 2017 by <NAME>
## Original file location in DROPBOX: >Mayfield Lab >Master Data Vault >Western Australia >Ring Plots (Mayfield_HilleRisLambers_Stouffer)
This project file ('complete.Rdata') contains estimated seed set (fecundity) data on 773 individuals of six focal annual plant species common to the York Gum woodlands in SW Western Australia. Seed set per focal plant was estimated for each plant by counting up the total number of flowers (or inflorescences) on each plant and multiplying that number by the average number of seeds produced per flower(infor.) using 1-3 flowers(inflor.) per plant. In addition to seed production values, this dataset also includes the identity and abundance of all plants within a 7.5 cm radius around each focal plant. More details are available in the readme file and in the methods of the paper associated with this dataset.
######################################################
Info for complete.Rdata
This file contains an R list object, called fecundity.data, made up of six data frames, one per focal species. Each data frame is set up in the same way with the following columns:
Seeds, focal, site, quadrat, the name of each possible competitor species.
Row identifiers are unique identifiers for each focal plant.
“seeds”: contains the number of seeds produced by the focal plant in that row (this value is estimated from real field data - see methods of associated paper methods for details)
“focal”: just tells you which focal species the focal plant is
“site”: tells you which site the focal plant was located in: K = Kunjin, B = Bendering
“quadrat”: is the quadrat number the focal plant is in, separate from the site. There are generally three focal plants per quadrat so these numbers appear 1-3 times in each data frame.
Competitor columns (each the species name of a competitor species): data entered these columns are abundances – so 0 indicates that no plants of that species were present in the quadrat around that focal plant and any other number is the number of individuals in that neighbourhood.
The following is a sample work flow for this dataset using the R code (fit.fecundity.model.R) for which it is structured to work with. This code is available from <NAME> or <NAME> and as a supplementary file (Data File 1) in the paper associated with this dataset: Higher-order interactions capture unexplained complexity in diverse communities.
####
# sample workflow for data analysis from manuscript
# this code fits the no competition, direct competition only, and direct and higher-order competition models to a sample dataset
####
## save the "complete.Rdata" file from Dryad in your working directory
## save the "fit.fecundity.model.R" file accompanying the manuscript in your working directory
## setwd()## set this to suit your system
# load the data frame - example data provided or complete dataset from Dryad, code here for complete dataset
load('complete.Rdata')## list with one data.frame per focal species (six data.frames total)
# read in the model-fitting function - function provided with manuscript
source('fit.fecundity.model.R')
# fit a negative-binomial model without any effect of competition
null.model <- fit.fecundity.model(fecundity.data, type="negbin", fit.alphas=FALSE, fit.betas=FALSE)
# fit a negative-binomial model with direct competition only
alpha.model <- fit.fecundity.model(fecundity.data, type="negbin", fit.alphas=TRUE, fit.betas=FALSE)
# fit a negative-binomial model with direct competition and higher-order competition
beta.model <- fit.fecundity.model(fecundity.data, type="negbin", fit.alphas=TRUE, fit.betas=TRUE)
<file_sep>---
title: "Protocol for Functional Trait Database"
author: "<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>"
address: "University of Queensland, Mayfield Plant Ecology Lab"
version: "Version 1"
date: 8 May 2018
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

***
This is a protocol for how to add new projects to the Mayfield Plant Functional Trait Database in SQLite.
## Adding new projects
Assign a new project a 4-letter code and sequential number identifier. For example: Watering project = **WATR1**. If another watering project is added later then that project will be **WATR2**.
Next make a folder for that project labeled with the unique ID *(e.g. **WATR1**)*. Within that folder, place 2 sub-folders *'raw'* and *'clean'* (both names should be lowercase). Within the *'raw'* folder, you should place all raw data files relevant to the project as well as a *'readme.txt'* that describes where those files were originally located in the MayfieldLab Dropbox and what data are in each. Within the *'clean'* folder, you should have the R code file used to create the cleaned data csv's as well as multiple csvs for that project structured as the following.
### List of CSVs for each project
The files must be names exactly as listed below (in all lowercase) and have the same column headings.
* projects.csv
+ project_id = a unique integer given to that project **(PKey)**
+ project = a text string giving a title to the project *(e.g. Survey of 12 sites along a climatic gradient)*
+ researcher = a text string noting the head PI/researcher for the proejct
+ email = a text string noting the current email address of head PI
+ study_sites = a text string listing the study sites of the project, seperated by an underscore *(e.g. Bendering_Kunjin_Perenjori)*
* field_season.csv
+ field_season_id = a unique integer given to the field season **(PKey)**
+ project_id = **FKey** to *'projects'* table
+ year = a 4-integer year identifying the year of the field season *(e.g. 2018)*
+ crew = a text string listing the field crew with names separated by underscores *(e.g. JohnDwyer_ClaireWainwright)*
+ fs_min_temp_C = the minimum temperature in degrees C for the field season
+ fs_max_temp_C = the maximum temperature in degrees C for the field season
+ fs_mean_precip_mm = the mean precipitation over the field season period.
**NOTE:** where are we getting these 3 above measures from - the field, BOM, another source ? Regardless, it should be standardised.
Also, when a field season covers several sites, are we just taking the min and max temps across all sites ?
* site.csv
+ site_id = unique integer for site **(PKey)**
+ site = text string for site name *(e.g. West Perenjori Nature Reserve)*
+ area = area of the site (estimated is okay) *(e.g. 3)*
+ units = units of the above estimation of site *(e.g. km2)*
+ lat = latitude value of site
+ long = longitude value of site
+ max_temp_C = long term (30-yr) mean annual maximum temperature in ^o^C
+ min_temp_C = long term (30-yr) mean annual minimum temperature in ^o^C
+ ann_precip_mm = long term (30-yr) mean annual precipitation in mm
**NOTE:** Same as above regarding the measures of temperature and precipitation.
* treatment.csv
+ treatment_id = unique integer for treatment **(PKey)**
+ treatment = string text describing teatment
**NOTE:** How in depth should the treatment description be ? We should give an example. We also need to figure out how we should deal with multiple treatments at some point.
* trait_summary.csv
+ field_season_id = **FKey** to *'field_season'* table
+ traits = text string of traits that were collected in the field season seperated by underscore *(e.g. seedmass_sla_leafarea)*
* plot.csv
+ plot_id = unique integer for plot **(PKey)**
+ field_season_id = **FKey** to *'field_season'* table
+ site_id = **FKey** to *'site'* table
+ block = integer with block number *(if no block present fill with NULL)*
+ plot_size_cm2 = numeric plot size in cm^2^
+ plot_shape = text string noting shape *(e.g. circle or square)*
+ treatment_id = FKey to 'treatment' table
+ lat = latitude value for the plot *(if not present fill with NULL)*
+ long = longitude value for the plot *(if not present fill with NULL)*
* individual.csv
+ individual_id = unique integer for individual plant **(PKey)**
+ plot_id = **FKey** to *'plot'* table
+ species_id = **FKey** to *'species'* table
### List of potential environmental CSVs for plots
Below is a list of potential tables for various plot-level environmental characteristics.
* plant_avail_p.csv
* plant_avail_n.csv
* plant_avail_k.csv
* soil_ph.csv
* canopy_cover.csv
* per_woody_debris.csv
* per_litter.csv
* per_bareground.csv
**NOTE:** We need to make sure that all these measures are standardised across sites and projects.
#### Example environmental table
Below is an example table with column headings listed.
* plant_avail_p.csv
+ plant_avail_p_id = unique integer for variable entry **(PKey)**
+ plant_avail_p = text string describing the environmental variable
+ plot_id = **FKey** to *'plot'* table
+ soilp_kg_cm = numeric value for soil P
+ date_collected = date sample was collected
### List of potential trait CSVs for individuals
Below is a list of potential tables for various individual-level traits.
* seed_mass.csv
* height.csv
* width.csv
* sla.csv
* leaf_area.csv
* leaf_dry_mass.csv
#### Example trait table
Below is an example table with column headings listed.
* seed_mass.csv
+ seed_mass_id = unique integer for trait entry **(PKey)**
+ individual_id = **FKey** to *'individual'* table
+ seedmass_mg = numeric value of the trait
+ date_collected = date sample was collected
## Setup of the species tables for the database
Below is the setup for the species portion of the functional trait database. This part of the database will be called through the individual plant id.
* species.csv
+ species_id = unique integer for species **(PKey)**
+ species = the specific epithet of the plant scientific name
+ family_id = **FKey** to *'family'* table
+ genus_id = **FKey** to *'genus'* table
+ invasive_id = **FKey** to *'invasive'* table
+ habit_id = **FKey** to *'habit'* table
+ life_form = **FKey** tp *'life_form'* table
* family.csv
+ family_id = unique integer for plant family **(PKey)**
+ family = text string for the plant family name
* genus.csv
+ genus_id = unique integer for plant genus **(PKey)**
+ genus = text string for the plant genus name
* invasive.csv
+ invasive_id = unique integer for native/invasive statue (either 1 or 2) **(PKey)**
+ invasive = text string for the status (native and exotic, respectively)
* habit.csv
+ habit_id = unique integer for habit **(PKey)**
+ habit = text string to describe the habit *(e.g. grass or forb)*
* life_form.csv
+ life_form_id = unique integer for the life form
+ life_form = text string labelling life form *(e.g. annual or perennial)*
***
### Potential future additions
* Include species-level trait values
* Include growth chamber/glasshouse experiments
* Add spatial data
* Others??<file_sep>######################################
#### Code written by <NAME> ####
#### Version 1: 15-06-2017 ####
######################################
# clear workspace
rm(list=ls())
##### Cleaning code for SURV1 ####
### set working directory
setwd("/home/uqtmart7/data/Dropbox/Mayfield Lab/FunctionalTraitDatabase/Projects/SURV1/RAW")
raw<-read.csv('quadrat_scale_data_June_2017.csv')
# list all sites
sites<-unique(raw$remnant)
## projects dataframe
projects<-data.frame(project_id=1,researcher="JohnDwyer",email="<EMAIL>",study_sites=paste(sites,collapse="_"))
# list all years
years<-unique(raw$year)
## field_season dataframe
field_season<-data.frame(field_season_id=c(1,2),project_id=1,year=years,crew=c("JohnDwyer","JohnDwyer_ClaireWainwright"))
## site dataframe
site<-data.frame(site_id=seq(1,length(sites)),site=sites,area=0,units="ha",lat=0,long=0,max_temp=0,min_temp=0,ann_precip=0)
## treatment dataframe
treatment<-data.frame(treatment_id=c(1,2),treatment=c("Edge","Interior"))
## make plot dataframe
# make smaller dataframe without extranious values for plot dataframe
raw.plot<-data.frame(year=raw$year,site=raw$remnant,block=raw$site,plot=raw$quadrat, edge=raw$edge)
# remove duplicate values
raw.plot<-raw.plot[!duplicated(raw.plot),]
# add treatment values - match the edge code (0,1) to treatment code listed above (1,2)
raw.plot$treatment<-unlist(lapply(raw.plot$edge, function (x) replace (x,x==1,2)))
raw.plot$treatment<-unlist(lapply(raw.plot$treatment, function (x) replace (x,x==0,1)))
# match site name with site_id above
raw.plot<-merge(raw.plot,site[,c("site_id","site")],by="site")
# match field season year with field_season_id above
raw.plot<-merge(raw.plot,field_season[,c("field_season_id","year")],by="year")
# sort the dataframe so it is easy to compare to original 'raw'
raw.plot<-raw.plot[order(raw.plot$field_season_id,raw.plot$site_id,raw.plot$block,raw.plot$plot,raw.plot$edge),]
# plot dataframe
plot<-data.frame(plot_id=seq(1,length(raw.plot$plot)),field_season_id=raw.plot$field_season_id,site_id=raw.plot$site_id,block=raw.plot$block,treatment_id=raw.plot$treatment)
###########################3
## make trait summary dataframe
# read in raw trait data (this is actually only average data - will get actual individual data from John on Monday June 19 2017)
raw.trait<-read.csv("species_in_quadrat_scale_data_June_2017.csv")
# add field_season_id from above
raw.trait<-merge(raw.trait,field_season[,c("year","field_season_id")],"year")
# split the large dataframe by field_season_id incase there are different traits for different seasons
raw.trait.fs.1<-na.omit(raw.trait[which(raw.trait$field_season_id==1),])
raw.trait.fs.2<-na.omit(raw.trait[which(raw.trait$field_season_id==2),])
# visually insepect which column headers are traits
head(raw.trait.fs.1)
head(raw.trait.fs.2)
# extract column names for trait values
trait.col.names.1<-colnames(raw.trait.fs.1)[8:30]
trait.col.names.2<-colnames(raw.trait.fs.2)[8:30]
# make trait dataframe
#list of traits = paste in column headers without the "." and then all merged into one string separted by "_"
trait_summary<-data.frame(field_season_id=c(1,2),traits=c(paste(gsub("\\.","",trait.col.names.1),collapse = "_"),paste(gsub("\\.","",trait.col.names.2),collapse = "_")))
#####################
## write out csv's
setwd("/home/uqtmart7/data/Dropbox/Mayfield Lab/FunctionalTraitDatabase/Projects/SURV1/CLEAN")
write.csv(projects,"projects.csv",row.names=F)
write.csv(field_season,"field_season.csv",row.names=F)
write.csv(site,"site.csv",row.names=F)
write.csv(treatment,"treatment.csv",row.names=F)
write.csv(plot,"plot.csv",row.names=F)
write.csv(trait_summary,"trait_summary.csv",row.names = F)
###########################
<file_sep>###############################################
# Project: Traits database #
# Script to clean FACL1 project data #
# #
# author: Malyon #
# date: June 2017 #
###############################################
# Set path to project folder
############################
local_path <- '~/Dropbox/' # this is where you put in the path to whatever folder holds the Mayfield Lab folder on your computer
path <- paste0(local_path, 'Mayfield Lab/FunctionalTraitDatabase/Projects/FACL1/')
# Load relevant files
#######################
field_counts <- read.csv(paste0(path, 'raw/field_counts.csv'), header = T,
stringsAsFactors = F)
field_plant_level_with_env <- read.csv(paste0(path, 'raw/field_plant_level_with_env.csv'), header = T,
stringsAsFactors = F)
field_plot_level <- read.csv(paste0(path, 'raw/field_plot_level.csv'), header = T,
stringsAsFactors = F)
# Afaik this contains plot environmental and density data for the 18 plots at Bendering: W.acuminata grown in monoculture (8)
# and W.acuminata grown surrounded by A.cupaniana (10)
## ISSUES :
# There's a different number of plots in each files
# files don't say which plots are at which site
# create some ID variables - those will be modifed in the database (?)
project_id <- '1'
field_season_id <- '1'
site_id <- c('1', '2')
treatment_id <- c()
# # REDUNDANT FILES:
# field_plant_level <- read.csv(paste0(path, 'raw/field_plant_level.csv'), header = T,
# stringsAsFactors = F)
# this is the same file as field_plant_level_with_env, but with 4 fewer columns (soil moisture,
# phosphorus, nitrate and mean canopy)
# Now on to the output
########################
# projects table
#----------------
projects <- data.frame(project_id = project_id,
researcher = 'ClaireWainwright',
email = '<EMAIL>',
study_sites = c('bendering', 'kunjin'))
write.csv(projects, paste0(path, 'clean/projects.csv'), row.names = F)
# field season table // UNFINISHED //
#--------------------
field_season <- data.frame(field_season_id = field_season_id,
project_id = project_id,
year = 2013,
crew = 'ClaireWainwright_XingwenLoy_AngelaGardner_<NAME>',
fs_max_temp_C = NA, # not available in the collected data, check methods
fs_min_temp_C = NA, # not available in the collected data, check methods
fs_mean_precip_mm = NA) # available in methods but different for each site
write.csv(field_season, paste0(path, 'clean/field_season.csv'), row.names = F)
# trait summary table // UNFINISHED //
#---------------------
trait_summary <- data.frame(field_season_id = field_season_id,
traits = c('', ''))
write.csv(trait_summary, paste0(path, 'clean/trait_summary.csv'), row.names = F)
# site table // UNFINISHED //
#------------
site <- data.frame(site_id = site_id,
site = '',
area = NA,
units = NA,
lat = NA, # can be found in methods
long = NA, # can be found in methods
max_temp_C = NA, # not available in the collected data - methods ?
min_temp_C = NA, # not available in the collected data - methods ?
ann_precip_mm = NA) # not available in the collected data - methods ?
# treatment table // UNFINISHED //
#-----------------
treatment <- data.frame(treatment_id = treatment_id,
treatment = c())
write.csv(treatment, paste0(path, 'clean/treatment.csv'), row.names = F)
# plot table // UNFINISHED //
#------------
# create the df
plot <- data.frame(plot_id = ,
field_season_id = ,
site_id = ,
block = ,
treatment_id = ,
lat = ,
long = )
write.csv(plot, paste0(path, 'clean/plot'), row.names = F)
<file_sep>## Project - POLL2
## Collation started on 14 Jun 2017 by <NAME>
6 focal species:
Goodenia berardiana -
Podolepis lessonii -
Podotheca gnaphaliodes -
Rhodanthe manglesii -
Waitzia acuminata -
Arctotheca calendula -
<file_sep>######################################
#### Code written by <NAME> ####
#### Version 1: 06-06-2018 ####
######################################
####Clear workspace
rm(list=ls())
#####This is an example code which shows you how to set the appropriate working directories,
#####and produce CSVs with standardised names. Although some parts will require adaptation for
#####the specific project that you are working on, it has been designed so that in some cases,
#####you simply change the input names that I have used to the ones appropriate to your project.
#####In this code, I have used SURV1 which is <NAME>'s survey data from 2011.
###function to write clean csvs automatically given the name of the dataframe
write.clean.csv<-function(x) write.csv(x, paste("clean/",deparse(substitute(x)),".csv", sep=""))
#####PLUG-AND-PLAY REQUIRED INFO#########
####Insert the name of the project folder
project.name<-"SURV1"
####Insert the name, email of the principal investigator
researcher<-"ClaireWainwright"
email<-"<EMAIL>"
####Project ID number
project_id<-2
####set working directory to the designated project folder (no change required for this line)
setwd(project.name)
##### The following needs to be changed as per the requirements of the project ####
####To bring in a raw datasheet to be reformatted - all project folders include a "raw"
####file, thus the only thing that needs to be changed here is the name of the
####file (i.e. quadrat_scale_data_June_2017.csv) and the name of the object (i.e. plot.level)
plot.level<-read.csv('raw/quadrat_scale_data_June_2017.csv')
individual.level<-read.csv("raw/species_in_quadrat_scale_data_June_2017.csv")
####Which study sites did this project occur at? If this column does not exist in data then manually entry
####using line below which is ###ed out
study_sites<-unique(plot.level$remnant)
##study_sites<-c("mystudysite1","mystudysite2")
####Create projects dataframe
projects<-data.frame(project_id=project_id,
project=project.name,
researcher=researcher,
study_sites=paste(study_sites,collapse="_"),
notes=NA)
####list all years that the study occurred - if not available in raw dataframe then
####fill in manual years as a vector
#year<-c(2010,2011,...)
year<-unique(plot.level$year)
####Create field season dataframe
#Field_season_id appropriate if split over years, if only one field season then fill in "1" only
#If crew does not change between years then fill in only one entry
field_season<-data.frame(field_season_id=c(1,2),
project_id=project_id,
year=year,crew=c("JohnDwyer","JohnDwyer_ClaireWainwright"),
notes=NA)
####Create site dataframe
site<-data.frame(site_id=seq(1,length(study_sites)),
site=study_sites,
area=-9999,
units=-9999,
lat=-9999,
long=-9999,
notes=NA)
## treatment dataframe - each treatment is assigned an identifier and a name for the treatment
treatment<-data.frame(treatment_id=c(1,2),
treatment=c("Edge","Interior"))
#### Plot dataframe will have the same amount of observations as the plot.level data.frame so we will
#### assign the plot.level to a new name with just the variables needed for the plot level
# make smaller dataframe without extranious values for plot dataframe
plot.level.thinned<-data.frame(year=plot.level$year,
site=plot.level$remnant,
block=plot.level$site,
plot=plot.level$yrsq,
edge=plot.level$edge,
lat=plot.level$site.lat,
long=plot.level$site.long,
notes=NA)
###remove duplicated values if they are present
plot.level.thinned<-plot.level.thinned[!duplicated(plot.level.thinned),]
####edge is currently a variable assigned as either 0=interior or 1=edge but when we want
####to compare across the entire trait database we want these values to match the treatment ID
####for all studies which compare edge to interior
plot.level.thinned$treatment<-unlist(lapply(plot.level.thinned$edge, function (x) replace (x,x==1,2)))
plot.level.thinned$treatment<-unlist(lapply(plot.level.thinned$treatment, function (x) replace (x,x==0,1)))
# match site name with site_id above
plot.level.thinned<-merge(plot.level.thinned,site[,c("site_id","site")],by="site")
# match field season year with field_season_id above
plot.level.thinned<-merge(plot.level.thinned,field_season[,c("field_season_id","year")],by="year")
# sort the dataframe so it is easy to compare to original 'raw'
plot.level.thinned<-plot.level.thinned[order(plot.level.thinned$field_season_id,plot.level.thinned$site_id,plot.level.thinned$block,plot.level.thinned$plot,plot.level.thinned$edge),]
###add plot id to plot.level.thinned
plot.level.thinned$plot_id<-seq(1,length(plot.level.thinned$plot))
###make the plot data frame
plot<-data.frame(plot_id=plot.level.thinned$plot_id,field_season_id=plot.level.thinned$field_season_id,site_id=plot.level.thinned$site_id,block=plot.level.thinned$block,treatment_id=plot.level.thinned$treatment, lat=plot.level.thinned$lat, long=plot.level.thinned$long)
######making environmental dataframes######
plot.level$plot<-plot.level$yrsq
plot.level<-merge(plot.level, data.frame(plot=plot.level.thinned$plot, plot_id=plot.level.thinned$plot_id), by="plot")
woody.cover<-data.frame(woody_cover_id=seq(1:length(plot.level$woody.cover)),
plot_id=plot.level$plot_id,
woody_cover_percent=plot.level$woody.cover,
date_collected=plot.level$year,
notes=NA)
##############repeat in the same way for all environment variables
#### to make the species-level dataframe
#######################TBA#####################################
####Species level dataframe and all higher-level csvs related to taxonomy are still to come
####Species information will be extracted from a common SLQ database and the species IDS
####matched up to the appropriate species in the spreadsheet. At the moment, we are currently
####just using the species name as a placeholder
###individual data frame will have the same amount of observations of the raw individual-level data set
###just get the variables we will need
individual.level.thinned<-data.frame(plot=individual.level$yrsq, species=individual.level$species)
####merge the plot ID to the individual level, duplicates of plot ID because several individuals
####occur within each plot
individual.level.thinned<-merge(individual.level.thinned, plot.level.thinned[,c("plot","plot_id")], by="plot")
#####assign each individual an ID, but paste the name of the project to the front
individual.level.thinned$individual_id<-paste(project.name, seq(1:length(individual.level.thinned[,1])), sep="_")
####make the individual dataframe
individual<-data.frame(individual_id=individual.level.thinned$individual_id
,plot_id=individual.level.thinned$plot_id
,species=individual.level.thinned$species)
####remember that above, species could be essentially whatever you like, we are still working on liking the
####the SLq database of species to the R code
###########################
## make trait summary dataframe
####include the field season ID variable to the individual level dataframe
individual.level.trait<-merge(individual.level,field_season[,c("year","field_season_id")],"year")
# split the large dataframe by field_season_id incase there are different traits for different seasons
individual.level.trait.fs1<-(individual.level.trait[which(individual.level.trait$field_season_id==1),])
individual.level.trait.fs2<-(individual.level.trait[which(individual.level.trait$field_season_id==2),])
# visually insepect which column headers are traits
head(individual.level.trait.fs1)
head(individual.level.trait.fs2)
# extract column names for trait values
trait.col.names.1<-colnames(individual.level.trait.fs1)[9:length(colnames(individual.level.trait.fs1))]
trait.col.names.2<-colnames(individual.level.trait.fs2)[9:length(colnames(individual.level.trait.fs2))]
# make trait dataframe
#list of traits = paste in column headers without the "." and then all merged into one string separted by "_"
trait_summary<-data.frame(field_season_id=c(1,2),traits=c(paste(gsub("\\.","",trait.col.names.1),collapse = "_"),paste(gsub("\\.","",trait.col.names.2),collapse = "_")))
###########################TO MAKE TRAIT CSVs###########################################
######assign the individual ID
individual.level.trait$individual_id<-individual.level.thinned$individual_id
SLA<-data.frame(SLA_id=seq(1:length(individual.level.trait$measured.sla))
,individual_id=individual.level.trait$individual_id
,SLA_mm2_mg=individual.level.trait$measured.sla
,date_collected=individual.level.trait$year,
notes=NA)
height<-data.frame(height_id=seq(1:length(individual.level.trait$measured.height))
,individual_id=individual.level.trait$individual_id
,height_mm=individual.level.trait$measured.height
,date_collected=individual.level.trait$year,
notes=NA)
leaf_area<-data.frame(height_id=seq(1:length(individual.level.trait$leaf.area.for.sla))
,individual_id=individual.level.trait$individual_id
,height_mm=individual.level.trait$leaf.area.for.sla
,date_collected=individual.level.trait$year,
notes=NA)
write.clean.csv(projects)
write.clean.csv(field_season)
write.clean.csv(site)
write.clean.csv(plot)
write.clean.csv(individual)
write.clean.csv(height)
write.clean.csv(SLA)
write.clean.csv(leaf_area)
write.clean.csv(trait_summary)
write.clean.csv(treatment)
write.clean.csv(woody.cover)
<file_sep>## In this folder
- create_database_structure.sql - from Chrissy testing how to create the structure of the database
- R code for species.R - from Chrissy. Using John's and Claire's species data to create the species part of the database
- GetProjects - code from Chrissy to combine all .csv's with the same title from different proejcts together before putting into database
<file_sep>species<-c("Aira.caryophylla",
"Avena.barbata",
"Briza.maxima","Bromus.rubens",
"Ehrharta.longiflora",
"Pentaschistis.airoides",
"Vulpia.bromoides","Vulpia.sp", "Austrostipa.elegantissima",
"Blennospora.drummondii",
"Brachyscome.iberidifolia", "Calandrinia.eremaea",
"Ceratogyne.obionoides","Crassula.sp",
"Gnephosis.tenuissima","Gonocarpus.nodulosus",
"Goodenia.sp","Hyalosperma.demissum",
"Hydrocotyle.pilifera" ,"Lawrencella.rosea",
"Lobelia.gibbosa" ,"Neurachne.alopecuroidea",
"Nicotiana.rotundifolia","Phyllangium.sulcatum",
"Podolepis.lessonii","Podotheca.angustifolia",
"Podotheca.gnaphalioides","Poranthera.microphylla",
"Rhodanthe.citrina","Rhodanthe.laevis",
"Rhodanthe.manglesii","Thysanotus.rectantherus",
"Trachymene.cyanopetala","Trachymene.ornata",
"Trachymene.pilosa","Triglochin.isingiana",
"Wahlenbergia.gracilenta","Waitzia.acuminata",
"Brassica.tournefortii","Hypochaeris.glabra",
"Lysimachia.arvensis","Oxalis.sp",
"Petrorhagia.dubia","Ursinia.anthemoides",
"Zaluzianskya.divaricata","Parentucellia.latifolia",
"Arctotheca.calendula")
species %in% raw.trait$species
trace.trait<-raw.trait[which(raw.trait$species %in% species),]
cool<-aggregate(raw.trait$species, by=list(raw.trait$remnant), FUN=summary)
seed.mass<-na.omit(aggregate(raw.trait$mean.seed.mass, by=list(raw.trait$species,raw.trait$remnant),FUN=mean))
head(raw.trait)
data.frame(do.call("rbind",strsplit(as.character(raw.trait$life.form),".",2)))
#install.packages('tidyr')
library(tidyr)
raw.trait$life.form<-as.character(raw.trait$life.form)
unique(raw.trait$life.form)
xx<-str_split_fixed(as.character(raw.trait$life.form),pattern="\\.",n=3)
unique(xx[,3])
for (i in 1:length(xx[,3])) {
if (xx[,3]=="forb" | xx[,3]=="twiner") {
}
<file_sep>temp.max<-read.csv(file.choose())
temp.min<-read.csv(file.choose())
ppt<-read.csv(file.choose())
fix.weather.headings<-function(x) {
names(x)<-tolower(names(x))
names(x)<-gsub(".","_",names(x),fixed=T)
names(x)<-gsub("temperature","temp",names(x),fixed=T)
return(x)
}
temp.max<-fix.weather.headings(temp)
temp.min<-fix.weather.headings(temp.min)
ppt<-fix.weather.headings(ppt)
colnames(temp.max)[length(x[1,])]<-"quality_max"
colnames(temp.min)[length(x[1,])]<-"quality_min"
colnames(ppt)[length(x[1,])]<-"quality_ppt"
temp.join<-join(temp.min,temp.max,by=c("product_code","bureau_of_meteorology_station_number","year","month","day"))
temp.ppt.join<-join(temp.join,ppt,by=c("product_code","bureau_of_meteorology_station_number","year","month","day"))
<file_sep>
Species level Data
——————————————————
# Chrissy 2017
- Species data was collated from John’s Survey data from 2010 and 2011 (found in SURV1 project)
- Family and genus data collected from: http://www.theplantlist.org/1.1/browse/-/-/
NB. Compositae == Asteraceae
Tables
——————
/genus_family.csv
- table with 23831 genera and associated families
/genus.csv
- Key and genus table
/habit.csv
- Key and growth habit table
/invasive.csv
- Key and invasiveness table
/life_form.csv
- Key and life_form table
Code
————
/plant_genus_list.py
- Code to scrape the website to get the full genus/family list
/
<file_sep>** Unsure about these notes as I'm still waiting on hearing back from Claire on this project **<file_sep>Project undertaken in WA Field Season 2016 by <NAME> in West Perenjori Reserve
Updated on 10 Jun 2017
List of files for project
'TIME1.csv' - multiple measurements of individuals over time in field season 2016
'TIME1.metadata.txt' - metadata about 'TIME1.csv' with information about measurements and how plants were measured
'Plot.DATA.06.09.2017.csv' - uncomplete data of plot level information for plots in the project from field season 2016
'Plot.DATA.metadata.txt' - metadata about 'Plot.DATA.06.09.2017,csv' with information about what variables were taken at the plot level
<file_sep>This is the collation of 2 projects:
- a shade experiment run by <NAME> in 2015
- a shade experiment run by <NAME> in 2015 (Honours student)
Plots were very close together (Perenjori site) and the same experimental treatments were applied so the data can be analysed together.
Data collected by <NAME>, <NAME> and <NAME>
*** Seed mass and SLA traits were taken from John's Dwyer's data and not measured directly during this project ***
## Files:
/Wainwright_ESA2016.pdf : slides for Claire's ESA talk about some of the data that includes as diagram of the experimental design. In her words: "we created plots in which we located individuals of 8 focal in dense ("High competition" in the datasheets) neighborhoods and also located individuals growing with no competition just outside of these plots ("solos" in the datasheets). We then collected seeds from each individual (column BG in the data file I sent you, "Seedcount.extrap.integer"). Half of the plots had netting over them as a shade treatment."
/raw folder:
/2015 data.xlsx : this looks like a rawer, uncleaned version of the field data
/2015 focal species germ and viab rates.xlsx : self-explanatory **
/2015_plant_level_data_CEW170712.csv: 'plant level data' sheet saved fron .xlsx file below (fecundity, height, and some other response variables, as well as some biotic and abiotic explanatory variables at various scales eg. nearest neighbor identity, avg. soil moisture at the plot level, etc) **
/2015 plant level data with metadata CEW170712.xlsx : metadata (as below) and a sheet with plant level data **
/2015_plant_level_metadata_CEW170712.csv : metadata (a copy of the metadata sheet in the file above) **
/neighb_data_final_CEW170712.csv : neighborhood data for each focal individual **
/Perenjori_data_FLANAGAN_05.16.xlsx : all of Tom's data, copied from /Western Australia Coexistence/Experiments_Data/16_Shade_TomF/
/Soil results.xlsx
all the above were copied from Mayfield Lab/Master Data Vault/Western Australia /Shade Experiment 2016 (Wainwright_Flanagan)/Claire Wainwright/
tom_shade.csv : csv version of Perenjori_data_FLANAGAN_05.16.xlsx
most of the raw data was copied on 26/06/2017
** : was copied over on 17/07/2017 after Claire did some quality control on the data and fixed some errors in the original files. Original uncorrected fiels are still available in the Master Data Vault
Note: file names remain unchanged, except for converting white spaces to _ in .csv files (for R)
-- Malyon 26/06/2017
-- extra comments Malyon 17/07/2017
<file_sep>###############################################
# Project: Traits database #
# Script to clean SHAD1 project data #
# #
# author: Malyon #
# date: July 2017 #
###############################################
# Set path to project folder
############################
local_path <- '~/Documents/' # this is where you put in the path to whatever folder holds the Mayfield Lab folder on your computer
path <- paste0(local_path, 'GitHub/FunctionalTraitDB/Projects/SHAD1/')
# Load relevant files
#######################
metadata <- read.csv(paste0(path, 'raw/2015_plant_level_metadata_CEW170712.csv'), header = T, stringsAsFactors = F)
plantdata <- read.csv(paste0(path, 'raw/2015_plant_level_data_CEW170712.csv'), header = T, stringsAsFactors = F)
## IMPORTANT NOTE: I'm ignoring the soil results and the germination & viability data for now
# create some ID variables - those will be modifed in the database (?)
project_id <- '1'
field_season_id <- '1'
site_id <-
treatment_id <-
# Now on to the output
########################
# projects table
#----------------
projects <- data.frame(project_id = project_id,
project = 'WA shade experiment',
researcher = 'ClaireWainwright',
email = '<EMAIL>',
study_sites = 'Perenjori')
write.csv(projects, paste0(path, 'clean/projects.csv'), row.names = F)
# field season table
#--------------------
field_season <- data.frame(field_season_id = field_season_id,
project_id = project_id,
year = 2015,
crew = 'ClaireWainwright_TomFlannagan_MaiaRaymundo',
fs_max_temp_C = NA, # not available in the collected data
fs_min_temp_C = NA, # not available in the collected data
fs_mean_precip_mm = NA) # not available in the collected data
write.csv(field_season, paste0(path, 'clean/field_season.csv'), row.names = F)
# site table UNFINISHED
#-------------------
site <- data.frame(site_id = site_id,
site = 'West Perenjori Nature Reserve',
area = 3.6,
units = 'km2',
lat = ,
max_temp_C = ,
min_temp_C = ,
annual_temp_mm = )
write.csv(site, paste0(path, 'clean/site.csv'), row.names = F)
# treatment table
#------------------
treatment <- data.frame(treatment_id = treatment_id,
treatment = 'shade, open')
write.csv(treatment, paste0(path, 'clean/treatment.csv'), row.names = F)
# trait summary table - not even sure if all of these are traits?
#-------------------
trait_summary <- data.frame(field_season_id = field_season_id,
traits = Focal.height_Solo.height_Height_Num.fl.total_Num.fl.seeding.total_Seedcount.extrap.interger_Mean.solo.seedcount.extrap.integer.block_Delta.seedcount.meansolospeciesblock_Solo.seedcount.extrap.integer_Delta.seedcount.highcomp.solo.pair_no.developed.flowers_Mean.seed.per.flower_Extrapolated.Seed.Total_Viability_Germination)
write.csv(trait_summary, paste0(path, 'clean/trait_summary.csv'), row.names = F)
# plot table
#------------------
plot <- data.frame(plot_id = plot_id,
field_season_id = field_season_id,
site_id = site_id,
block = )<file_sep>---------------
-- SQL GUIDE
--------------
-- all lines must end in ";"" unless they're preceeded by "."
-- Create table
CREATE TABLE projects (
project_id integer PRIMARY KEY,
researcher text NOT NULL);
-- Insert values
INSERT INTO projects VALUES
(3, '<NAME>; <NAME>', '<EMAIL>', 'BEND1'),
(4, '<NAME>; Steph', '', 'BEND1');
-- Add column
ALTER TABLE contacts ADD COLUMN age integer;
-- Update values
UPDATE contacts SET age = 22.9 WHERE proj_id = 1;
-- CREATE UNIQUE INDEX
CREATE UNIQUE INDEX id ON projects(site);
-- REPLACE means insert or replace (not update!)
REPLACE INTO projects(id, researcher) VALUES (1, 'Chrissy')
-- import csv
.mode csv
.import /filename tablename -- if no existing table, it will use headers for column names
.schema tablename
-- export table as csv
ec
-- create trigger
ALTER TABLE employee ADD COLUMN updatedon date;
# vi employee_update_trg.sql
CREATE TRIGGER employee_update_trg AFTER UPDATE ON employee
BEGIN
UPDATE employee SET updatedon = datetime('NOW') WHERE rowid = new.rowid;
END;
company.db < employee_update_trg.sql
-- create view, this creates a new table
create view empdept as select empid, e.name, title, d.name, location from employee e, dept d where e.deptid = d.deptid;
select * from empdept
explain query plan SELECT * FROM empdept;
-- savepoint and roll back
SAVEPOINT major;
-- make some changes but decide you don't want them
ROLLBACK to SAVEPOINT major;
-- UNION QUERY
SELECT empid, name, title FROM c1.employee UNION SELECT empid, name, title from c2.employee;
<file_sep># notes on creating a database from https://www.r-bloggers.com/r-and-sqlite-part-1/
library(RSQLite)
library(DBI)
library(sqldf)
## extract the home directory
home_dir<-getwd()
## set the working directory
setwd("test_trait_database")
## make a new folder to test R creating databases in
# system("mkdir testing_R_db")
## reset the working directory
setwd("testing_R_db")
## make a new database
db <- dbConnect(SQLite(), dbname="Test.species.sqlite")
## write in the tables for tha database
dbWriteTable(conn = db, name = "life_form", value = "life_form.csv",
row.names = FALSE, header = TRUE)
dbWriteTable(conn = db, name = "family", value = "family.csv",
row.names = FALSE, header = TRUE)
dbWriteTable(conn = db, name = "invasive", value = "invasive.csv",
row.names = FALSE, header = TRUE)
dbWriteTable(conn = db, name = "species", value = "species.csv",
row.names = FALSE, header = TRUE)
dbWriteTable(conn = db, name = "genus", value = "genus.csv",
row.names = FALSE, header = TRUE)
dbWriteTable(conn = db, name = "habit", value = "habit.csv",
row.names = FALSE, header = TRUE)
## check the list of tables in the database
dbListTables(db)
## query a dataframe of genus and species native status
species.status<-dbGetQuery(db, "SELECT * FROM genus,invasive INNER JOIN species ON species.genus_id = genus.genus_id AND species.invasive_id = invasive.invasive_id")
## clean the dataframe by remove the rows with "_id"
species.status.clean<-species.status[,-grep("id",names(species.status))]
<file_sep>/*
MAYFIELD LAB
-------------
FUNCTIONAL TRAIT DATABASE SCHEMA 2017
<NAME>
*/
-- Change working directory to .db location then:
sqlite3 databasefile.db
-- Use these statements to display your query as a table
.headers on
.mode columns
-- To view constraints of table created
select sql from sqlite_master where type='table' and name='demo_tab';
-- to Query multiple tables
SELECT ... FROM table1 NATURAL JOIN table2... NATURAL JOIN table3 ...
-- to Query specific columns on multiple tables
SELECT block, plot, site.site, treatment.treatment FROM plot
LEFT OUTER JOIN treatment ON plot.treatment = treatment.id
LEFT OUTER JOIN site ON plot.site = site.id;
--------------------------------------------------------------------------------------------------
-- DATABASE CONSTRUCTION AND CONSTRAINTS
CREATE TABLE projects (
project_id integer PRIMARY KEY,
researcher text NOT NULL,
email text NOT NULL,
site text NOT NULL);
INSERT INTO projects (project_id, researcher, email, site)
VALUES (1, '<NAME>', '<EMAIL>', 'Tasmania');
INSERT INTO projects (project_id, researcher, email, site)
VALUES (2, '<NAME>', '<EMAIL>', 'WA');
CREATE TABLE field_season (
fs_id integer PRIMARY KEY,
project_id integer,
year integer NOT NULL,
crew_list text NOT NUll,
FOREIGN KEY(project_id) REFERENCES projects(project_id));
INSERT INTO field_season VALUES (1, 1, 2016, '<NAME>, Leander, Hannah, Ian');
INSERT INTO field_season VALUES (2, 1, 2017, 'Chrissy, Loy, Leander, Hannah, Ian');
INSERT INTO field_season VALUES (3, 2, 2015, 'Cath, Trace, Maia, Margie');
INSERT INTO field_season VALUES (4, 2, 2016, 'Cath, Trace, Maia, Margie');
CREATE TABLE traits (
trait_id integer PRIMARY KEY, -- probably don't need the trait_id column
fs_id integer,
traits text NOT NULL,
FOREIGN KEY(fs_id) REFERENCES field_season(fs_id));
INSERT INTO traits VALUES (1, 1, 'SLA, leaf area, RTD'),
(2, 2, 'biomass, leaf area, RTD'),
(3, 3, 'L:S, leaf area, RTD'),
(4, 4, 'SLA, height, RTD');
-------
CREATE TABLE site (
id integer NOT NULL PRIMARY KEY,
site text NOT NULL,
area_km2 integer,
longitude integer,
latitude integer,
max_temp integer,
min_temp integer,
ann_precip_mm integer);
INSERT INTO site VALUES (1, 'bendering', 300, 152.00000, 27.00000, 2, 1, 100);
INSERT INTO site (id, site) VALUES (2, 'Kunjin');
-------
CREATE TABLE treatment (
id integer NOT NULL PRIMARY KEY,
treatment text NOT NULL);
INSERT INTO treatment VALUES (1, 'control'),
(2, 'water'),
(3, 'shade'),
(4, 'density_30'),
(5, 'density_60');
--------
CREATE TABLE plot (
plot_id integer PRIMARY KEY,
fs_id integer NOT NULL,
site text NOT NULL,
block integer NOT NULL,
plot integer NOT NULL,
treatment text,
FOREIGN KEY(fs_id) REFERENCES field_season(fs_id),
FOREIGN KEY(site) REFERENCES site(site),
FOREIGN KEY(treatment) REFERENCES treatment(id));
INSERT INTO plot VALUES (1, 1, 1, 1, 1, 1);
INSERT INTO plot VALUES (2, 1, 1, 1, 2, 2);
INSERT INTO plot VALUES (3, 1, 1, 2, 1, 1);
INSERT INTO plot VALUES (4, 1, 1, 2, 2, 2);
INSERT INTO plot VALUES (5, 1, 2, 1, 2, 2), (6, 2, 2, 1, 2, 2), (7, 1, 2, 1, 1, 1);
------
CREATE TABLE soil_moisture (
id PRIMARY KEY,
plot_id integer,
value integer NOT NULL,
unit text NOT NULL,
date_collected text,
FOREIGN KEY(plot_id) REFERENCES plot(plot_id));
INSERT INTO soil moisture VALUES (1, 1, 33, '%', '3/1/17');
--------
CREATE TABLE family (
id integer NOT NULL PRIMARY KEY,
family text NOT NULL);
INSERT INTO family VALUES (1, asteraceae), (2, goodeniaceae);
CREATE TABLE invasive (
id integer NOT NULL PRIMARY KEY,
invasive NOT NULL);
INSERT INTO invasive VALUES (1, native), (2, exotic);
CREATE TABLE habit (
id integer NOT NULL PRIMARY KEY,
habit text NOT NULL);
INSERT INTO habit VALUES (1, graminoid), (2, forb);
CREATE TABLE life_form (
id integer NOT NULL PRIMARY KEY,
life_form text NOT NULL);
INSERT INTO life_form VALUES (1, annual), (2, biannual), (3, perennial);
-------
CREATE TABLE species (
species_id integer PRIMARY KEY,
family text NOT NULL REFERENCES family(id),
genus text NOT NULL,
species text NOT NULL,
invasive integer REFERENCES invasive(id),
habit integer REFERENCES habit(id),
life_form integer REFERENCES life_form(id));
INSERT INTO species VALUES (1, 1, 'Arctotheca', 'calendula', 1, 2, 1)
-------
CREATE TABLE individual (
indv_id integer PRIMARY KEY,
species_id integer NOT NULL,
plot_id integer NOT NULL,
FOREIGN KEY(species_id) REFERENCES species(species_id),
FOREIGN KEY(plot_id) REFERENCES plot(plot_id));
CREATE TABLE sla (
indv_id integer PRIMARY KEY,
value integer NOT NULL,
unit text NOT NULL,
date_collected text,
FOREIGN KEY(indv_id) REFERENCES individual(indv_id));<file_sep>/*
SQLite Tutorial
----------------
Create a database, add a table and values, update the table and add new columns
https://www.tutorialspoint.com/sqlite/sqlite_update_query.htm
*/
/* create a database */
sqlite3 testdb.db
/* Create a table
the blue bits = type of input
null = null value
integer = number
the red bits = contraints
not null = row in column must have a value
UNIQUE = every row in that column must be unique */
CREATE TABLE contacts (
contact_id integer PRIMARY KEY,
first_name text NOT NULL,
last_name text NOT NULL,
email text NOT NULL UNIQUE,
phone text NOT NULL UNIQUE
);
/* INSERT DATA INTO TABLE */
INSERT INTO contacts (contact_id, first_name, last_name, email, phone)
VALUES (1, 'chrissy', 'elmer', '<EMAIL>', '0474808044');
/* ALTER TABLE TO ADD NEW COLUMN and value */
ALTER TABLE contacts ADD COLUMN age integer;
UPDATE contacts SET age = 22.9 WHERE first_name = 'chrissy'
DELETE FROM table WHERE id = 2;
/* Querying the database
Column view */
.header on
.mode column
.width 12 6
SELECT * from contacts;
-- JOINING TABLES
-------------------
--from tables
company (id, name, age, address, salary)
department (id, dept, emp_id)
-- CROSS JOIN
SELECT ... FROM table1 CROSS JOIN table2 ...
-- eg.
SELECT emp_id, name, dept FROM company CROSS JOIN department;
-- INNER JOIN
SELECT ... FROM table1 JOIN table2 USING (column1, column2...)
-- or
SELECT ... FROM table1 INNER JOIN table2 ON conditional_expression ...
-- eg.
SELECT emp_id, name, dept FROM company INNER JOIN department ON company.id = department.emp_id
-- NATURAL JOIN (automatically tests for equality between the values of every column in both tables)
SELECT ... FROM table1 NATURAL JOIN table2...
select student.student_name, exams.exam_code, ...
from student
join wrote_exam using (student_number)
join exams using (exam_code)
where ...<file_sep>## Project - POLL2
## Collation started on 14 Jun 2017 by <NAME>
'Xingwen.et.al.2015.pdf' is the resulting publication from this study. Has information on methods and focal species.
22.06.2017 - in contact with Loy and he said that he will share data sometime late August when the US field season is over.
<file_sep>This project involved both 1 field season in 2013 and one growth chamber experiment.
** I'm not sure how we want to incorporate the growth chamber experiment data though I guess that's a problem for another day **
Data collected by <NAME>, <NAME>, <NAME>, <NAME>
Methods should be described in the draft manuscript present in this folder.
NOTE: This project also incorp[orated data from the HOIR1 project (ring data) - described as Kunjin field data in the methods
### Files:
/Wainwright_Facilitation_JEcol_20feb17.docx: draft manuscript for publication using this data, emailed by Claire on 20/06/2017. Should contain methods.
# /raw folder:
/claire_IEM_assays_2013.xls: results from deploying ion exchange membranes in each plot (IEMs) to test whether nitrate and ammonium cycling rates differed among treatment and control plots
/IEM extraction.xlsx: list of plot names and corresponding sample labels for the experiment above
*** those 2 files contain IEM data for plots from both the FACL1 and LITT1 projects - we will have to match plot numbers to figure out which are from which ***
copied from Mayfield Lab/Master Data Vault/Western Australia/Wainwright/Litter on 21/06/2017
/Waitzia.grass.data.2014.15dec14.xlsx: contains both field data and growth chamber data. Field data are the sheets with the prefix 'field', growth chamber data are the sheets with the prefix 'UQ'
copied from Mayfield Lab/Master Data Vault/Western Australia/Wainwright/Facilitation on 21/06/2017
Those files were then saved as .csv files for cleaning in R. The .csv file names match the sheet names in Waitzia.grass.data.2014.15dec14.xlsx
As previously, field data are prefixed by 'field', growth chamber data are prefixed by 'UQ'.
Some sheets were not saved as .csv files because they contain analysis rather than raw data, or redundant data that wasn't used in the analyses (“Sheet 1”, “field unmanip plots WAAC” (this is actually from the Bendering experiment BEND1), “UQ sp lvl”, “UQ means”, “field means for plotting”, “model coefs”, “HOI calcs”, and “Sheet 2”)
# /clean folder:
/cleaning_FACL1.R: script to clean raw FIELD data files for input into database
database-ready data are saved as .csv, with one file for each database table.
see databaseschema.png for a reference of table names and what they each contain
** Claire is (hopefully) writing up some metadata **
Publications:
In prep, draft is in folder (/Wainwright_Facilitation_JEcol_20feb17.docx)
-- Malyon 21/06/2017
-- comments on 23/06/2017
<file_sep>## Project - BEND1
## Collation started on 14 Jun 2017 by <NAME>
## Original 'file_protocol_2014' file location in DROPBOX: >Mayfield Lab >WA MM Bendering Boxes
## Original 'bend_box2014_2015.xls' file location in DROPBOX: >Western Australia Coexistence> Experiments_Data >14-15benderingBoxes
<file_sep>######################################
#### Code written by <NAME> ####
#### Version 1: 15-06-2017 ####
######################################
rm(list=ls())
##### Cleaning code for BEND1 ####
### set working directory
setwd("/home/uqtmart7/data/Dropbox/Mayfield Lab/FunctionalTraitDatabase/Projects/BEND1/RAW")
## projects dataframe
projects<-data.frame(project_id=1,researcher="MaiaRaymundo",email="<EMAIL>",study_sites="bendering")
## field_season dataframe
field_season<-data.frame(field_season_id=c(1,2,3,4),project_id=1,year=c(2014,2015,2016,2017),crew=c("HaoRanLin_MargaretMayfield_XingwenLoy_EmmaLodourceur_JohnPark_ClaireWainwright_AlexanderNance_LeanderLoveAnderegg","HaoRanLin_XingwenLoy","MaiaRaymundo","MaiaRaymundo"))
## site dataframe
site<-data.frame(site_id=1,site="bendering",area=1602,units="ha",lat=0,long=0,max_temp=24.3,min_temp=9.4,ann_precip=361.3)
## treatment dataframe
treatment<-data.frame(treatment_id=c(1,2,3,4,5,6),treatment=c("OpenDry","OpenWet","ControlDry","ControlWet","LidDry","LidWet"))
# Below are various codes use here and in the raw files for the treatments
#Wet = w "Wet"
#Dry = d "Dry"
#Open = o "Open"
#Control/Wall = c "Control"
#Wall+Lid = k "Lid
########################
#### function to add treatment code to dataframe based on 'exclusion' and 'water' columns (in that order into the function) ####
BEND.treatment<- function (x,w) {
treatment.ew<-vector()
for (i in 1:length(x)) {
ex<-x[i]
wat<-w[i]
if (ex=="c" & wat=="w") {treatment.ew[i]<-4}
else if (ex=="o" & wat=="w") {treatment.ew[i]<-2}
else if (ex=="k" & wat=="w") {treatment.ew[i]<-6}
else if (ex=="c" & wat=="d") {treatment.ew[i]<-3}
else if (ex=="o" & wat=="d") {treatment.ew[i]<-1}
else if (ex=="k" & wat=="d") {treatment.ew[i]<-5}
}
return (treatment.ew)
}
############################
#### function to extract block number out of the 'unique.plot. column ####
BEND.block<- function (x) {
m<-sapply(as.character(x), function(k) strsplit(k, "[^0-9]"))
sol<-as.numeric(unlist(m))
return(sol[!is.na(sol)])
}
#############################
## read in raw file
raw<-read.csv('bend_box2014_2015.csv')
# make smaller dataframe without extranious values
raw.plot<-data.frame(exclsuion=raw$exclusion,water=raw$water,unique.plot=raw$unique.plot)
# remove duplicate values
raw.plot<-raw.plot[!duplicated(raw.plot),]
# add block number
raw.plot$block.num<-BEND.block(raw.plot$unique.plot)
# add treatment values
raw.plot$treatment<-BEND.treatment(raw.plot$exclsuion,raw.plot$water)
## make plot dataframe
# plot dataframe
plot<-data.frame(plot_id=seq(1,length(unique(raw.plot$unique.plot))),field_season_id=1,site_id=1,block=raw.plot$block.num,treatment_id=raw.plot$treatment)
#####################
## write out csv's
setwd("/home/uqtmart7/data/Dropbox/Mayfield Lab/FunctionalTraitDatabase/Projects/BEND1/CLEAN")
write.csv(projects,"projects.csv",row.names=F)
write.csv(field_season,"field_season.csv",row.names=F)
write.csv(site,"site.csv",row.names=F)
write.csv(treatment,"treatment.csv",row.names=F)
write.csv(plot,"plot.csv",row.names=F)
<file_sep>###############################################
# Project: Traits database #
# Script to clean LITT1 project data #
# #
# author: Malyon #
# date: June 2017 #
###############################################
# Set path to project folder
############################
local_path <- '~/Dropbox/' # this is where you put in the path to whatever folder holds the Mayfield Lab folder on your computer
path <- paste0(local_path, 'Mayfield Lab/FunctionalTraitDatabase/Projects/LITT1/')
# Load relevant files
#######################
plot_level <- read.csv(paste0(path, 'raw/litter_plot_level_Wainwright_20aug14.csv'), header = T,
stringsAsFactors = F)
# contains plot environment data
Kunj_plot_level <- read.csv(paste0(path, 'raw/compiled_Kunj_plot_level.csv'), header = T,
stringsAsFactors = F)
# this file is a merged file of plot_level, species densities and IEM results for each plot
Kunj_all_survey_data <- read.csv(paste0(path, 'raw/compiled_Kunj_all_survey_data.csv'), header = T,
stringsAsFactors = F)
# *** I'm confused - this file has two species columns that aren't in Kunj_plot_level, but fewer species columns overall ??? ***
Kunjin_harvest_species <- read.csv(paste0(path, 'raw/compiled_Kunjin_harvest_species.csv'), header = T,
stringsAsFactors = F)
Kunjin_harvest_individuals <- read.csv(paste0(path, 'raw/compiled_Kunjin_harvest_individuals.csv'), header = T,
stringsAsFactors = F)
# *** There's more rows in the harvest_species df than the harvest_indivs column ?? Investigate ***
# update: If I remove the rows where Plant.biomass is NA, I get the same number of rows for both files
Kunj_seed_mass_per_individual <- read.csv(paste0(path, 'raw/compiled_Kunj_seed_mass_per_individual.csv'), header = T,
stringsAsFactors = F)
# seed mass data
anion_exchange_strips <- read.csv(paste0(path, 'raw/compiled_Kunj_survey_Sep_2013.csv'), header = T,
stringsAsFactors = F)
# this file contains anion-exchange membrane strip data
# create some ID variables - those will be modifed in the database (?)
project_id <- '1'
field_season_id <- '1'
site_id <- '1'
treatment_id <- c(1, 2)
# REDUNDANT FILES:
# plot_inventory <- read.csv(paste0(path, 'raw/Litter_plot_inventory_Wainwright.csv'), header = T,
# stringsAsFactors = F)
# this file contains an inventory of all plots, including more plots than what is mentionned in the methods (154) ??
# other than that, redundant info
# Kunj_plot_level_annuals_only <- read.csv(paste0(path, 'raw/compiled_Kunj_plot_level_annuals_only.csv'), header = T,
# stringsAsFactors = F)
# this file is the exact same as Kunj_plot_level, but with 10 fewer columns (9 non_annual plant species and Wallaby grass)
# Kunj_survey_Aug_2013 <- read.csv(paste0(path, 'raw/compiled_Kunj_survey_Aug_2013.csv'), header = T,
# stringsAsFactors = F)
# summary table of species densities - redundant
# Kunj_species_level_annuals_only <- read.csv(paste0(path, 'raw/compiled_Kunj_species_level_annuals_only.csv'), header = T,
# stringsAsFactors = F)
# redundant species density info (annual species only)
# Kunj_rarefield_Aug_richness <- read.csv(paste0(path, 'raw/compiled_Kunj_rarefield_Aug_richness.csv'), header = T,
# stringsAsFactors = F)
# this appears to be another redundant file of species densities
# focal_species_biomass <- read.csv(paste0(path, 'raw/compiled_focal_species_biomass.csv'), header = T,
# stringsAsFactors = F)
# this file just contains mean biomass measures of focal species ie. data analysis. Redundant info
# Now on to the output
########################
# projects table
#----------------
projects <- data.frame(project_id = project_id,
researcher = 'ClaireWainwright',
email = '<EMAIL>',
study_sites = 'kunjin')
write.csv(projects, paste0(path, 'clean/projects.csv'), row.names = F)
# field season table // UNFINISHED //
#--------------------
field_season <- data.frame(field_season_id = field_season_id,
project_id = project_id,
year = 2013,
crew = 'ClaireWainwright_XingwenLoy',
fs_max_temp_C = NA, # not available in the collected data
fs_min_temp_C = NA, # not available in the collected data
fs_mean_precip_mm = NA) # not available in the collected data
write.csv(field_season, paste0(path, 'clean/field_season.csv'), row.names = F)
# trait summary table
#---------------------
trait_summary <- data.frame(field_season_id = field_season_id,
traits = c('seed_mass', 'biomass'))
write.csv(trait_summary, paste0(path, 'clean/trait_summary.csv'), row.names = F)
# site table // UNFINISHED //
#------------
site <- data.frame(site_id = site_id,
site = 'kunjin',
area = NA,
units = NA,
lat = NA, # can be found in methods
long = NA, # can be found in methods
max_temp_C = NA, # not available in the collected data - methods ?
min_temp_C = NA, # not available in the collected data - methods ?
ann_precip_mm = NA) # not available in the collected data - methods ?
# treatment table
#-----------------
treatment <- data.frame(treatment_id = treatment_id,
treatment = c('control', 'added_litter'))
write.csv(treatment, paste0(path, 'clean/treatment.csv'), row.names = F)
# plot table // UNFINISHED //
#------------
# note: 120 plots total (see methods), but 9 were discarded due to animal damage
# gather the info
plots <- plot_level[, c('Block', 'Plot.ID', 'Treatment')]
# renumber & rename according to database framework
plots$Block <- as.factor(plots$Block)
levels(plots$Block) <- seq_along(levels(plots$Block)) # this ensures we have a key of plot IDs as per the database and
# plot IDs as they are referred to in the raw data
plots$plot <- as.factor(plots$Plot.ID)
levels(plots$plot) <- seq_along(levels(plots$plot))
plots[plots$Treatment == 'Control', ]$Treatment <- 'control'
plots[plots$Treatment == 'Litter', ]$Treatment <- 'added_litter'
# create the df
plot <- data.frame(plot_id = plots$plot,
field_season_id = field_season_id,
site_id = site_id,
block = plots$Block,
treatment_id = plots$Treatment,
lat = NA, # there is a 'GPS.ID" column in the plot_level df but I don't know
long = NA) # how that relates to actual GPS coordinates
write.csv(plot, paste0(path, 'clean/plot'), row.names = F)
<file_sep>## In this folder
- FinalSchema.png = current (as of 08.05.2018) database schema outline
- SQLite_Database.Rproj = R project for the functional trait db
- Protocol_markdown.Rmd = Rmarkdown file for creating the protocol for the db
- Protocol_markdown.html = the output from the Rmarkdown file
Subfolders
- Construction = .sql and .R code for creating the database
- Species = raw and cleaned data for the species db. Also contains current species db
- Example_SQLite_R_Code = includes example .sql and .R code for creating and quering databases
- Design = includes design schema and old design schema files
<file_sep>######################################
#### Code written by <NAME> ####
#### Version 1: 06-06-2018 ####
######################################
####Clear workspace
rm(list=ls())
#####This is an example code which shows you how to set the appropriate working directories,
#####and produce CSVs with standardised names. Although some parts will require adaptation for
#####the specific project that you are working on, it has been designed so that in some cases,
#####you simply change the input names that I have used to the ones appropriate to your project.
#####In this code, I have used SURV1 which is <NAME>'s survey data from 2011.
###function to write clean csvs automatically given the name of the dataframe
write.clean.csv<-function(x) write.csv(x, paste("clean/",deparse(substitute(x)),".csv", sep=""))
#####PLUG-AND-PLAY REQUIRED INFO#########
####Insert the name of the project folder
project.name<-"DENS1"
####Insert the name, email of the principal investigator
researcher<-"ClaireWainwright"
email<-"<EMAIL>"
####Project ID number
project_id<-3
####set working directory to the designated project folder (no change required for this line)
setwd(project.name)
##### The following needs to be changed as per the requirements of the project ####
####To bring in a raw datasheet to be reformatted - all project folders include a "raw"
####file, thus the only thing that needs to be changed here is the name of the
####file (i.e. quadrat_scale_data_June_2017.csv) and the name of the object (i.e. plot.level)
plot.level<-read.csv('raw/DENs1_final_heights.csv')
####Which study sites did this project occur at? If this column does not exist in data then manually entry
####using line below which is ###ed out
#study_sites<-unique(plot.level$remnant)
study_sites<-c("Growth_chamber")
####Create projects dataframe
projects<-data.frame(project_id=project_id,
project=project.name,
researcher=researcher,
study_sites=paste(study_sites,collapse="_"),
notes=NA)
####list all years that the study occurred - if not available in raw dataframe then
####fill in manual years as a vector
year<-c(2012)
#year<-unique(plot.level$year)
####Create field season dataframe
#Field_season_id appropriate if split over years, if only one field season then fill in "1" only
#If crew does not change between years then fill in only one entry
field_season<-data.frame(field_season_id=c(1),
project_id=project_id,
year=year,crew=c("ClaireWainwright"),
notes=NA)
####Create site dataframe
site<-data.frame(site_id=seq(1,length(study_sites)),
site=study_sites,
area=-9999,
units=-9999,
lat=-9999,
long=-9999,
notes=NA)
## treatment dataframe - each treatment is assigned an identifier and a name for the treatment
treatment<-data.frame(treatment_id=c(1,2,3,4),
treatment=c("Control","Low","Medium","High"))
#### Plot dataframe will have the same amount of observations as the plot.level data.frame so we will
#### assign the plot.level to a new name with just the variables needed for the plot level
# make smaller dataframe without extranious values for plot dataframe
###remove duplicated values if they are present
plot.level.unique<-plot.level[!duplicated(plot.level$Pot_ID_let),]
plot.level.unique$Treatment<-as.character(plot.level.unique$Density)
for (i in 1:nrow(plot.level.unique))
{
if(plot.level.unique[i,"Treatment"]=="high"){
plot.level.unique[i,"Treatment"]<-3}else{
if(plot.level.unique[i,"Treatment"]=="medium"){
plot.level.unique[i,"Treatment"]<-2}else{
if(plot.level.unique[i,"Treatment"]=="low"){
plot.level.unique[i,"Treatment"]<-1}else{
plot.level.unique[i,"Treatment"]<-0
}
}
}
}
###make the plot data frame. I did not use merge because this project only has one site
plot<-data.frame(plot_id=plot.level.unique$Pot_ID_let,field_season_id=unique(field_season$field_season_id),
site_id=1,block=NA,treatment_id=plot.level.unique$Treatment,
lat=site$lat, long=site$lat)
######making environmental dataframes######
#This was a growth chamber experiment run once in 2012.
####Species level dataframe and all higher-level csvs related to taxonomy are still to come
####Species information will be extracted from a common SLQ database and the species IDS
####matched up to the appropriate species in the spreadsheet. At the moment, we are currently
####just using the species name as a placeholder
###individual data frame will have the same amount of observations of the raw individual-level data set
###just get the variables we will need
#include species names based on project codes (metadata sheet from "raw/2012_densitydata.xlsx")
A<- "W.nitida"
B<- 'H.glutinosum.glutinosum'
C<- 'G.berardiana'
D<- "H.glabra"
E<- "P.airoides"
F<- "grass.2"
#
DENS1_heights<-read.csv("raw/DENS1_heights.csv")
DENS1_heights<-gather(DENS1_heights,species,heights,(c(7:11,13:17,
19:23,25:29,
31:35,37:41)))
######assign the individual ID
individual.level.dens<-data.frame(plot=DENS1_heights$Pot_ID_let, species=DENS1_heights$species)
#####assign each individual an ID, but paste the name of the project to the front
individual.level.dens$individual_id<-paste(project.name, seq(1:length(individual.level.dens[,1])), sep="_")
####make the individual dataframe
individual<-data.frame(individual_id=individual.level.dens$individual_id
,plot_id=individual.level.dens$plot
,species=individual.level.dens$species)
####remember that above, species could be essentially whatever you like, we are still working on liking the
####the SLq database of species to the R code
###########################
# make trait dataframe
#list of traits = paste in column headers without the "." and then all merged into one string separted by "_"
trait_summary<-data.frame(field_season_id=1,traits =c("Height"))
###########################TO MAKE TRAIT CSVs###########################################
height<-data.frame(height_id=seq(1:length(DENS1_heights$heights))
,individual_id=individual.level.dens$individual_id
,height_mm=DENS1_heights$heights
,date_collected=DENS1_heights$Date,
Days_after_planting=DENS1_heights$Days_after_planting,
notes=NA)
write.clean.csv(projects)
write.clean.csv(field_season)
write.clean.csv(site)
write.clean.csv(plot)
write.clean.csv(individual)
write.clean.csv(height)
write.clean.csv(trait_summary)
write.clean.csv(treatment)
<file_sep>## In this folder
- Claire_species_20attribute_v2.csv = list of species from one of Claire's projects.
- TEM.Species.List_15_06_2017.csv = list of species from Trace's 2016 maps.
- species_in_quadrate_scale_datda_June_2017.csv = dataset that lists species from John's 2010/2011 survey data.
- genus_family.csv = webscrapped data from Chrissy to relate plant genus to family.
<file_sep>
# **Mayfield Lab Functional Trait Database**
#### *<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>*
#### *Mayfield Plant Ecology Lab PI: Prof. <NAME>*
#### *University of Queensland*
##### *Initial commit: May 8, 2018*
***
## Introduction
This is a database that combines all completed datsets from projects that have individual-level trait data available. We have in this repository the data and code to create the SQLite database as well as example queries.
This project was initialized with <NAME>, <NAME>, <NAME>, and <NAME> in May 2017 but was dropped during the field season and post. It has since been picked up by the above authors in May 2018.
### Timeline for completion
Below is the *tentative* timeline for completion of the database (pre-2018 field season data aquistion).
* May 11 = <NAME> send Mal current protocol.
* May 16 = <NAME> and <NAME> present current protocol to the group.
* May 16 = All receive assignments for projects.
* Jun 6 = All data cleaning is complete.
* Jun 6 = Assign tasks for data compling, DB assembly, DB check, QAQC, and example query making.
* Jun 29 = Functional trait datdabase is up-to-date to the best of everyone's knowledge
* Recurring = Update the protocol
## Helpful tutorials
In this project we use a number of different softwares. It may be helpful to familiarize yourself with all or some of them when working with the database. For you convenience, here are some tutorials!
* What is a database?
* Git and Github
+ A simple introduction is here:
+ https://www.youtube.com/playlist?list=PLRqwX-V7Uu6ZF9C0YMKuns9sLDzK6zoiV
+ More advanced info can be found here:
+ Video: https://www.youtube.com/watch?v=1ffBJ4sVUb4
+ Text: https://swcarpentry.github.io/git-novice/
* SQL
## Adding new projects
Assign a new project a 4-letter code and sequential number identifier. For example: Watering project = **WATR1**. If another watering project is added later ten that proejct will be **WATR2**.
Next make a folder for that project labeled with the unique ID *(e.g. **WATR1**)*. Within that folder, place 2 sub-folder *'raw'* and *'clean'* (both names should be lowercase). Within the *'raw'* folder, you should place all raw data files relevent to the project as well as a *'readme.txt'* that describes where those files were originally located in the MayfieldLab Dropbox and what data are in each. Within the *'clean'* folder, you should have the R code file used to create the cleaned data csv's as well as multiple csvs for that project structured as the following.
### List of CSVs for each project
The files must be names exactly as listed below (in all lowercase) and have the same column headings.
* projects.csv
+ project_id = a unique integer given to that project **(PKey)**
+ project = a text string giving a title to the project *(e.g. Survey of 12 sites along a climatic gradient)*
+ researcher = a text string noting the head PI/researcher for the proejct
+ email = a text string noting the current email address of head PI
+ study_sites = a text string listing the study sites of the project
* field_season.csv
+ field_season_id = a unique integer given to the field season **(PKey)**
+ project_id = **FKey** to *'projects'* table
+ year = a 4-integer year identifying the year of the field season *(e.g. 2018)*
+ crew = a text string listing the field crew with names separated by underscores *(e.g. JohnDwyer_ClaireWainwright)*
+ fs_min_temp_C = the minimum temperature in ^o^C for the field season
+ Go to http://www.bom.gov.au/climate/data/index.shtml
+ Fill out the data query form
1. Select 'Temperature', 'Daily', 'Minimum temperature'
2. Enter site location. Select the nearest open bureau station, Select year.
3. Click 'Get Data'
4. Click "1 year of data" to download csv file
+ fs_max_temp_C = the maximum temperature in ^o^C for the field season
+ Follow steps as above, change obsercations to "maximum temperature"
+ fs_mean_precip_mm = the mean precipitaiton over the field season period.
+ Follow steps as above, Select data about "Rainfall"
* site.csv
+ site_id = unique integer for site **(PKey)**
+ site = text string for site name *(e.g. West Perenjori Nature Reserve)*
+ area = area of the site (estimated is okay) *(e.g. 3)*
+ units = units of the above estimation of site *(e.g. km2)*
+ lat = latitude value of site
+ long = longitude value of site
+ max_temp_C = long term (30-yr) mean annual maximum temperature in ^o^C
+ min_temp_C = long term (30-yr) mean annual minimum temperature in ^o^C
+ ann_precip_mm = long term (30-yr) mean annual precipitation in mm
* treatment.csv
+ treatment_id = unique integer for treatment **(PKey)**
+ treatment = string text describing teatment
* trait_summary.csv
+ field_season_id = **FKey** to *'field_season'* table
+ traits = text string of traits that were collected in the field season seperated by underscore *(e.g. seedmass_sla_leafarea)*
* plot.csv
+ plot_id = unique integer for plot **(PKey)**
+ field_season_id = **FKey** to *'field_season'* table
+ site_id = **FKey** to *'site'* table
+ block = integer with block number *(if no block present fill with NULL)*
+ plot_size_cm2 = numeric plot size in cm^2^
+ plot_shape = text string noting shape *(e.g. circle or square)*
+ treatment_id = FKey to 'treatment' table
+ lat = latitude value for the plot *(if not present fill with NULL)*
+ long = longitude value for the plot *(if not present fill with NULL)*
* individual.csv
+ individual_id = unique integer for individual plant **(PKey)**
+ plot_id = **FKey** to *'plot'* table
+ species_id = **FKey** to *'species'* table
### List of potential environmental CSVs for plots
Below is a list of potential tables for various plot-level enviornmental characterstics.
* plant_avail_p.csv
* plant_avail_n.csv
* plant_avail_k.csv
* soil_ph.csv
* canopy_cover.csv
* per_woody_debris.csv
* per_litter.csv
* per_bareground.csv
#### Example environmental table
Below is an example table with column headings listed.
* plant_avail_p.csv
+ plant_avail_p_id = unique integer for variable entry **(PKey)**
+ plant_avail_p = text string describing the environmental variable
+ plot_id = **FKey** to *'plot'* table
+ soilp_kg_cm = numeric value for soil P
+ date_collected = date sample was collected
### List of potential trait CSVs for individuals
Below is a list of potential tables for various individual-level traits.
* seed_mass.csv
* height.csv
* width.csv
* sla.csv
* leaf_area.csv
* leaf_dry_mass.csv
#### Example trait table
Below is an example table with column headings listed.
* seed_mass.csv
+ seed_mass_id = unique integer for trait entry **(PKey)**
+ individual_id = **FKey** to *'individual'* table
+ seedmass_mg = numeric value of the trait
+ date_collected = date sample was collected
***
### Potential future additions
* Include species-level trait values
* Include growth chamber/glasshouse experiments
* Add spatial data
* Others??
<file_sep>/*
MAYFIELD LAB
-------------
FUNCTIONAL TRAIT DATABASE SCHEMA 2017
<NAME>
*/
-- Change working directory to .db location then:
sqlite3 databasefile.db
-- Use these statements to display your query as a table
.headers on
.mode columns
-- To view constraints of table created
select sql from sqlite_master where type='table' and name='demo_tab';
-- to Query multiple tables
SELECT ... FROM table1 NATURAL JOIN table2... NATURAL JOIN table3 ...
-- to Query specific columns on multiple tables
SELECT block, plot, site.site, treatment.treatment FROM plot
LEFT OUTER JOIN treatment ON plot.treatment = treatment.id
LEFT OUTER JOIN site ON plot.site = site.id;
--------------------------------------------------------------------------------------------------
-- DATABASE CONSTRUCTION AND CONSTRAINTS
CREATE TABLE projects (
project_id integer PRIMARY KEY,
researcher text NOT NULL,
email text NOT NULL,
site text NOT NULL);
INSERT INTO projects VALUES
(3, '<NAME>; <NAME>', '<EMAIL>', 'BEND1'),
(4, '<NAME>; Steph', '', 'BEND1'),
(5, '<NAME>', '<EMAIL>', 'DENS1');
CREATE TABLE field_season (
fs_id integer PRIMARY KEY,
project_id integer REFERENCES projects(project_id),
year integer NOT NULL,
crew_list text NOT NUll);
INSERT INTO field_season VALUES (1, 1, 2016, 'Chrissy, Loy, Leander, Hannah, Ian');
INSERT INTO field_season VALUES (2, 1, 2017, 'Chrissy, Loy, Leander, Hannah, Ian');
INSERT INTO field_season VALUES (3, 2, 2015, 'Cath, Trace, Maia, Margie');
INSERT INTO field_season VALUES (4, 2, 2016, 'Cath, Trace, Maia, Margie');
INSERT INTO field_season VALUES (5, 3, 2013, '<NAME>'), (6, 4, 2015, '<NAME>'), (7, 5, 2014,'<NAME>');
CREATE TABLE trait_summary (
trait_id integer PRIMARY KEY, -- probably don't need the trait_id column
fs_id integer,
traits text NOT NULL,
FOREIGN KEY(fs_id) REFERENCES field_season(fs_id));
INSERT INTO trait_summary VALUES (1, 1, 'SLA, leaf area, RTD'),
(2, 2, 'biomass, leaf area, RTD'),
(3, 3, 'L:S, leaf area, RTD'),
(4, 4, 'SLA, height, RTD');
INSERT INTO trait_summary VALUES (5, 5, 'height, leaf area, RTD'),
(6, 6, 'flower number, leaf area, RTD'),
(7, 7, 'L:S, leaf area, RTD, flower size'),
(8, 8, 'height, biomass, RTD');
-------
CREATE TABLE site (
id integer NOT NULL PRIMARY KEY,
site text NOT NULL,
area_km2 integer,
longitude integer,
latitude integer,
max_temp integer,
min_temp integer,
ann_precip_mm integer);
INSERT INTO site VALUES (1, 'bendering', 300, 152.00000, 27.00000, 32, 1, 100);
INSERT INTO site VALUES (2, 'perenjori', 300, 152.00000, 28.00000, 33, -2, 100);
INSERT INTO site VALUES (3, 'Kunjin', 250, 152.00000, 32.00000, 40, -2, 100),
(4, 'Bongada', 500, 152.00000, 32.00000, 29, -5, 100);
-------
CREATE TABLE treatment (
id integer NOT NULL PRIMARY KEY,
treatment text NOT NULL);
INSERT INTO treatment VALUES (1, 'control'),
(2, 'water'),
(3, 'shade'),
(4, 'density_30'),
(5, 'density_60');
--------
CREATE TABLE plot (
plot_id integer PRIMARY KEY,
fs_id integer NOT NULL,
site text NOT NULL,
block integer NOT NULL,
plot integer NOT NULL,
treatment text,
FOREIGN KEY(fs_id) REFERENCES field_season(fs_id),
FOREIGN KEY(site) REFERENCES site(site),
FOREIGN KEY(treatment) REFERENCES treatment(id));
INSERT INTO plot VALUES (1, 1, 1, 1, 1, 1);
INSERT INTO plot VALUES (2, 1, 1, 1, 2, 2);
INSERT INTO plot VALUES (3, 1, 1, 2, 1, 1);
INSERT INTO plot VALUES (4, 1, 1, 2, 2, 2);
INSERT INTO plot VALUES (5, 1, 2, 1, 2, 2), (6, 2, 2, 1, 2, 2), (7, 1, 2, 1, 1, 1);
INSERT INTO plot VALUES (8, 1, 3, 1, 2, 2), (9, 2, 3, 1, 2, 2), (10, 1, 4, 1, 1, 1);
------
CREATE TABLE soil_moisture (
id PRIMARY KEY,
plot_id integer,
value integer NOT NULL,
unit text NOT NULL,
date_collected text,
FOREIGN KEY(plot_id) REFERENCES plot(plot_id));
INSERT INTO soil moisture VALUES (1, 1, 33, '%', '3/1/17');
--------
CREATE TABLE family (
family_id integer NOT NULL PRIMARY KEY,
family text NOT NULL);
INSERT INTO family VALUES (1, "asteraceae"), (2, "goodeniaceae");
CREATE TABLE genus (
genus_id integer NOT NULL PRIMARY KEY,
genus text NOT NULL);
INSERT INTO genus VALUES (1, "arctotheca"), (2, "velleia");
CREATE TABLE invasive (
invasive_id integer NOT NULL PRIMARY KEY,
invasive NOT NULL);
INSERT INTO invasive VALUES (1, "native"), (2, "exotic");
CREATE TABLE habit (
habit_id integer NOT NULL PRIMARY KEY,
habit text NOT NULL);
INSERT INTO habit VALUES (1, "graminoid"), (2, "forb");
CREATE TABLE life_form (
life_form_id integer NOT NULL PRIMARY KEY,
life_form text NOT NULL);
INSERT INTO life_form VALUES (1, "annual"), (2, 'biannual'), (3, 'perennial');
-------
CREATE TABLE species (
species_id integer PRIMARY KEY,
family text NOT NULL REFERENCES family(family_id),
genus text NOT NULL,
species text NOT NULL,
invasive integer REFERENCES invasive(invasive_id),
habit integer REFERENCES habit(habit_id),
life_form integer REFERENCES life_form(life_form_id));
INSERT INTO species VALUES (1, 1, 1, 'calendula', 2, 2, 1),(2, 2, 2, 'rosea', 1, 2, 1);
-------
CREATE TABLE individual (
indv_id integer PRIMARY KEY,
species_id integer NOT NULL,
plot_id integer NOT NULL,
FOREIGN KEY(species_id) REFERENCES species(species_id),
FOREIGN KEY(plot_id) REFERENCES plot(plot_id));
CREATE TABLE sla (
indv_id integer PRIMARY KEY,
value integer NOT NULL,
unit text NOT NULL,
date_collected text,
FOREIGN KEY(indv_id) REFERENCES individual(indv_id));<file_sep>######################################
#### Code written by <NAME> ####
#### Version 1: 06-06-2018 ####
######################################
####Clear workspace
rm(list=ls())
#####This is an example code which shows you how to set the appropriate working directories,
#####and produce CSVs with standardised names. Although some parts will require adaptation for
#####the specific project that you are working on, it has been designed so that in some cases,
#####you simply change the input names that I have used to the ones appropriate to your project.
#####In this code, I have used SURV1 which is <NAME>'s survey data from 2011.
###function to write clean csvs automatically given the name of the dataframe
write.clean.csv<-function(x) write.csv(x, paste("clean/",deparse(substitute(x)),".csv", sep=""))
#####PLUG-AND-PLAY REQUIRED INFO#########
####Insert the name of the project folder
project.name<-"SHAD1"
####Insert the name, email of the principal investigator
researcher<-"ClaireWainwright"
email<-"<EMAIL>"
####Project ID number
project_id<-2
####set working directory to the designated project folder (no change required for this line)
setwd(project.name)
##### The following needs to be changed as per the requirements of the project ####
####To bring in a raw datasheet to be reformatted - all project folders include a "raw"
####file, thus the only thing that needs to be changed here is the name of the
####file (i.e. quadrat_scale_data_June_2017.csv) and the name of the object (i.e. plot.level)
plot.level<-read.csv('raw/shade1_plot_data.csv')
####Which study sites did this project occur at? If this column does not exist in data then manually entry
####using line below which is ###ed out
#study_sites<-unique(plot.level$remnant)
study_sites<-c("Perenjori")
####Create projects dataframe
projects<-data.frame(project_id=project_id,
project=project.name,
researcher=researcher,
study_sites=paste(study_sites,collapse="_"),
notes=NA)
####list all years that the study occurred - if not available in raw dataframe then
####fill in manual years as a vector
year<-c(2015)
#year<-unique(plot.level$year)
####Create field season dataframe
#Field_season_id appropriate if split over years, if only one field season then fill in "1" only
#If crew does not change between years then fill in only one entry
field_season<-data.frame(field_season_id=c(1),
project_id=project_id,
year=year,crew=c("ClaireWainwright","TomFlannagan"),
notes=NA)
####Create site dataframe
site<-data.frame(site_id=seq(1,length(study_sites)),
site=study_sites,
area=-9999,
units=-9999,
lat=-9999,
long=-9999,
notes=NA)
## treatment dataframe - each treatment is assigned an identifier and a name for the treatment
treatment<-data.frame(treatment_id=c(1,2),
treatment=c("Open","Shade"))
#### Plot dataframe will have the same amount of observations as the plot.level data.frame so we will
#### assign the plot.level to a new name with just the variables needed for the plot level
# make smaller dataframe without extranious values for plot dataframe
###remove duplicated values if they are present
plot.level.unique<-plot.level[!duplicated(plot.level$Plot.ID),]
####edge is currently a variable assigned as either 0=interior or 1=edge but when we want
####to compare across the entire trait database we want these values to match the treatment ID
####for all studies which compare edge to interior
plot.level.unique$Treatment<-as.character(plot.level.unique$Treatment)
for (i in 1:nrow(plot.level.unique))
{
if(plot.level.unique[i,"Treatment"]=="Open"){
plot.level.unique[i,"Treatment"]<-1}else{
plot.level.unique[i,"Treatment"]<-2
}
}
###make the plot data frame. I did not use merge because this project only has one site
plot<-data.frame(plot_id=plot.level.unique$Plot.ID,field_season_id=unique(field_season$field_season_id),
site_id=1,block=plot.level.unique$Block,treatment_id=plot.level.unique$Treatment,
lat=site$lat, long=site$lat)
######making environmental dataframes######
shade_env_variables<-read.csv("raw/2015_plant_level_data_CEW170712.csv")
soil.moisture<-data.frame(soil_moisture_id=seq(1:length(shade_env_variables$Plot.ID)),
plot_id=shade_env_variables$Plot.ID,
soil_moisture_earlyAug_hc=shade_env_variables$Mean.soilmoisture.22.or.23.Aug.hicomp,
soil_moisture_lateAug_hc=shade_env_variables$Mean.soilmoisture.22.or.23.Aug.hicomp,
soil_moisture_earlySep_hc=shade_env_variables$Mean.soilmoisture.3Sep.hicomp,
soil_moisture_earlyAug_solo=shade_env_variables$Mean.solo.soilmoisture,
soil_moisture_lateAug_solo=shade_env_variables$Mean.solo.soilmoisture.22or23.Aug,
soil_moisture_earlySep_solo=shade_env_variables$Mean.solo.soilmoisture.3Sep,
date_collected=2015,
notes=NA)
bare_ground<-data.frame(bare_ground_id=seq(1:length(shade_env_variables$Plot.ID)),
plot_id=shade_env_variables$Plot.ID,
bare_ground_percent=shade_env_variables$Bare,
date_collected=2015,
notes=NA)
Moss_cover<-data.frame(moss_cover_id=seq(1:length(shade_env_variables$Plot.ID)),
plot_id=shade_env_variables$Plot.ID,
Moss_cover_percent=shade_env_variables$Moss,
date_collected=2015,
notes=NA)
Crust_cover<-data.frame(Crust_ground_id=seq(1:length(shade_env_variables$Plot.ID)),
plot_id=shade_env_variables$Plot.ID,
Crust_cover_percent=shade_env_variables$Crust,
date_collected=2015,
notes=NA)
Coarse_woody_debri<-data.frame(CWD_id=seq(1:length(shade_env_variables$Plot.ID)),
plot_id=shade_env_variables$Plot.ID,
CWD_percent=shade_env_variables$CWD,
date_collected=2015,
notes=NA)
Rock_cover<-data.frame(Rock_id=seq(1:length(shade_env_variables$Plot.ID)),
plot_id=shade_env_variables$Plot.ID,
rock_percent=shade_env_variables$Rock,
date_collected=2015,
notes=NA)
Log_near<-data.frame(Near_log_id=seq(1:length(shade_env_variables$Plot.ID)),
plot_id=shade_env_variables$Plot.ID,
Log_near=shade_env_variables$Near.under.log,
date_collected=2015,
notes=NA)
Jam_litter<-data.frame(Jam.litter_id=seq(1:length(shade_env_variables$Plot.ID)),
plot_id=shade_env_variables$Plot.ID,
Jam_litter=shade_env_variables$Jam.litter,
date_collected=2015,
notes=NA)
York_gum_cover<-data.frame(York_gum_id=seq(1:length(shade_env_variables$Plot.ID)),
plot_id=shade_env_variables$Plot.ID,
York_gum_percent=shade_env_variables$Euc.litter,
date_collected=2015,
notes=NA)
Colwell_phosphorous<-data.frame(Colwell_p_id=seq(1:length(shade_env_variables$Plot.ID)),
plot_id=shade_env_variables$Plot.ID,
Colwell_P=shade_env_variables$Colwell.P,
date_collected=2015,
notes=NA)
Canopy_cover<-data.frame(Canopy_cover_id=seq(1:length(shade_env_variables$Plot.ID)),
plot_id=shade_env_variables$Plot.ID,
Canopy_cover=shade_env_variables$Canopy.cover.final,
date_collected=2015,
notes=NA)
##############repeat in the same way for all environment variables
#### to make the species-level dataframe
#######################TBA#####################################
####Species level dataframe and all higher-level csvs related to taxonomy are still to come
####Species information will be extracted from a common SLQ database and the species IDS
####matched up to the appropriate species in the spreadsheet. At the moment, we are currently
####just using the species name as a placeholder
individual.level<-read.csv("raw/shad1_plant_lvl_focal.csv")
###individual data frame will have the same amount of observations of the raw individual-level data set
###just get the variables we will need
individual.level.shade<-data.frame(plot=individual.level$Plot.ID, species=individual.level$Focal.sp)
#####assign each individual an ID, but paste the name of the project to the front
individual.level.shade$individual_id<-paste(project.name, seq(1:length(individual.level.shade[,1])), sep="_")
####make the individual dataframe
individual<-data.frame(individual_id=individual.level.shade$individual_id
,plot_id=individual.level.shade$plot
,species=individual.level.shade$species)
####remember that above, species could be essentially whatever you like, we are still working on liking the
####the SLq database of species to the R code
###########################
# make trait dataframe
#list of traits = paste in column headers without the "." and then all merged into one string separted by "_"
trait_summary<-data.frame(field_season_id=1,traits =c("Height", "Leaf_length", "Mean-Lat"))
###########################TO MAKE TRAIT CSVs###########################################
######assign the individual ID
individual.level.trait$individual_id<-individual.level.thinned$individual_id
height<-data.frame(height_id=seq(1:length(individual.level$Height))
,individual_id=individual.level.shade$individual_id
,height_mm=individual.level$Height
,date_collected=2015,
notes=NA)
Leaf_length<-data.frame(Leaf_lenght_id=seq(1:length(individual.level$Leaf.length))
,individual_id=individual.level.shade$individual_id
,Leaf_length_mm=individual.level$Leaf.length
,date_collected=2015,
notes=NA)
Mean_lat<-data.frame(Mean_lat_id=seq(1:length(individual.level$Mean.Lat))
,individual_id=individual.level.shade$individual_id
,Mean_lat_mm=individual.level$Mean.Lat
,date_collected=2015,
notes=NA)
write.clean.csv(projects)
write.clean.csv(field_season)
write.clean.csv(site)
write.clean.csv(plot)
write.clean.csv(individual)
write.clean.csv(height)
write.clean.csv(Leaf_length)
write.clean.csv(Mean_lat)
write.clean.csv(trait_summary)
write.clean.csv(treatment)
write.clean.csv(soil.moisture)
write.clean.csv(bare_ground)
write.clean.csv(Moss_cover)
write.clean.csv(Rock_cover)
write.clean.csv(Canopy_cover)
write.clean.csv(Log_near)
write.clean.csv(York_gum_cover)
write.clean.csv(Jam_litter)
write.clean.csv(Colwell_phosphorous)
<file_sep>Files notes
## original location DROPBOX: >Western Australia Coexistence >Experiments_Data> 13-15ringData_wateringExp >2013-ring data
'WA_coexistence_08_13_environdata.xlsx' - has plot ID, soil pH, temperation, and 3 densiometer readings for 280 plots.
'PhD2013_experimentalplots.xlsx' - has plot ID and soil pH taken in September for 315 plots.
## original location DROPBOX: >Western Australia Coexistence >Experiments_Data> 13-15ringData_wateringExp >csv >2013
'2013oct_total_seed.csv' - has seed count, flower collected, number of flower heads, flower herbivory, and total seed
'field_data_2013.csv' - might add month that the data was collected in 2013 to the dataset
'2013oct_total_seed_env.csv' - merges the pH values with the seed count data set in '2013oct_total_seed.csv'
'seed_env_plot_lvl.csv' - has soil pH and final canopy values at the plot level
'pH_canopy.csv' - has upto 3 soil pH readings, 3 densiometer readings, and temperature readings
## original location DROPBOX: >Western Australia Coexistence >Experiments_Data> 13-15ringData_wateringExp >raw >2013
'field_data_all_months_2013_JP.xlsx' - has most of the above combined into one .xlsx with multiple sheets
<file_sep>## In folder
- make.species.db.R = R code from TEM made on 03.05.2018 to combine clean csv's to make species SQLite database
- Species.sqlite = SQLite relation database for plant species, genus, life_form, family, habit, and native status.
<file_sep># notes on creating a database from https://www.r-bloggers.com/r-and-sqlite-part-1/
library(RSQLite)
library(DBI)
library(sqldf)
## extract the home directory
home_dir<-getwd()
## set the working directory
setwd("test_trait_database")
## make a new folder to test R creating databases in
# system("mkdir testing_R_db")
## reset the working directory
setwd("testing_R_db")
#############
## make a fake database to test
## using the RSQLite package
db <- dbConnect(SQLite(), dbname="Test.sqlite")
## using the sqldf pacakge
sqldf("attach 'Test1.sqlite' as new")
###############
## adding data to the database the hard way
dbSendQuery(conn = db, "CREATE TABLE School (SchID INTEGER, Location TEXT,
Authority TEXT, SchSize TEXT)")
dbSendQuery(conn = db, "INSERT INTO School VALUES (1, 'urban', 'state', 'medium')")
dbSendQuery(conn = db, "INSERT INTO School VALUES (2, 'urban', 'independent', 'large')")
dbSendQuery(conn = db, "INSERT INTO School VALUES (3, 'rural', 'state', 'small')")
## list tables in the database
dbListTables(db)
## list columsn in the school table
dbListFields(db, "School")
## look at the data in the table
dbReadTable(db, "School")
## remove the school table
dbRemoveTable(db, "School")
#######################
## adding data to the database the easy way
dbWriteTable(conn = db, name = "Student", value = "student.csv",
row.names = FALSE, header = TRUE)
dbWriteTable(conn = db, name = "Class", value = "class.csv",
row.names = FALSE, header = TRUE)
dbWriteTable(conn = db, name = "School", value = "school.csv",
row.names = FALSE, header = TRUE)
## list tables in the database
dbListTables(db)
## list columsn in the school table
dbListFields(db, "School")
## look at the data in the table
dbReadTable(db, "School")
######################
## also read the csvs in as df first in R
dbRemoveTable(db, "School") # Remove the tables
dbRemoveTable(db, "Class")
dbRemoveTable(db, "Student")
School <- read.csv("school.csv") # Read csv files into R
Class <- read.csv("class.csv")
Student <- read.csv("student.csv")
# Import data frames into database
dbWriteTable(conn = db, name = "Student", value = Student, row.names = FALSE)
dbWriteTable(conn = db, name = "Class", value = Class, row.names = FALSE)
dbWriteTable(conn = db, name = "School", value = School, row.names = FALSE)
dbListTables(db) # The tables in the database
dbListFields(db, "School") # The columns in a table
dbReadTable(db, "School") # The data in a table
# dbGetQuery(conn, "CREATE TABLE Data (DataID integer primary key autoincrement,
# DataTypeID integer, DataName varchar)")
dbGetQuery(db, "SELECT * FROM School CROSS JOIN Student WHERE Gender = 'female' ")
<file_sep>import pandas as pd
import requests
from bs4 import BeautifulSoup
import re
def get_genus_family(soup, id_name):
"""Function to scrape all genus and family names from website,
turn into dataframe"""
genus_list = []
family_list = []
for plant in soup.find_all(id=id_name):
for genus in plant.find_all(class_=re.compile("genus")):
name = genus.get_text()
genus_list.append(name)
for family in plant.find_all(class_="family"):
name2 = family.get_text()
family_list.append(name2)
# join family_list and genus_list into a dataframe.
result = pd.concat([pd.DataFrame(genus_list, columns=['genus']),
pd.DataFrame(family_list, columns=['family'])], axis=1)
return result
def main():
"""Function to get data from URL,
Run get_genus_family function and export it as a csv."""
DATA_URL = 'http://www.theplantlist.org/1.1/browse/-/-/'
r = requests.get(DATA_URL)
soup = BeautifulSoup(r.text, 'html.parser') # get text from data.URL
# Export as csv
pd.DataFrame(get_genus_family(soup, "nametree")).to_csv('genus_family.csv', header=True)
if __name__ == '__main__':
main()
<file_sep>######################################
#### Code written by <NAME> ####
#### Version 1: 28-05-2018 ####
######################################
# clear workspace
rm(list=ls())
##### Cleaning code for WARM1 ####
raw<-read.csv('WaRM_CTD25_05_17_raw.csv')
sites<-droplevels(unique(raw$Site))
projects<-data.frame(project_id=1,researcher="TravisBritton",email="<EMAIL>",study_sites=paste(sites,collapse="_"))
<file_sep># Species and traits list for Trace #
######################################
# author: Malyon
# data: June 2017
# collating what traits we have for which species from the
# LITT1, FACL1, SHAD1 and WATR1 projects so that Trace can
# fill in the blanks in the field
library(reshape2)
library(dplyr)
### The FACL1 project only collected traits on 1 species so I'm entering it manually
facl1 <- data.frame(project = 'FACL1',
species = 'W.acuminata',
traits = c('plant_height', 'biomass', 'flower_number'))
### Add in the LITT1 stuff
# seed mass:
Kunj_seed_mass_per_individual <- read.csv('~/Dropbox/Mayfield Lab/FunctionalTraitDatabase/Projects/LITT1/raw/compiled_Kunj_seed_mass_per_individual.csv',
header = T, stringsAsFactors = F)
litt1 <- data.frame(project = 'LITT1',
species = unique(Kunj_seed_mass_per_individual$Species),
traits = 'seed_mass')
# biomass:
Kunjin_harvest_species <- read.csv('~/Dropbox/Mayfield Lab/FunctionalTraitDatabase/Projects/LITT1/raw/compiled_Kunjin_harvest_species.csv',
header = T, stringsAsFactors = F)
Kunjin_harvest_species <- Kunjin_harvest_species[is.na(Kunjin_harvest_species$Plant.biomass) == F, ] # remove NAs
litt1.2 <- data.frame(project = 'LITT1',
species = unique(Kunjin_harvest_species$Species),
traits = 'biomass')
### Next up is the shade data
plant_level_data <- read.csv('~/Dropbox/Mayfield Lab/FunctionalTraitDatabase/Projects/SHAD1/raw/plant_level_data.csv',
header = T, stringsAsFactors = F)
tom_shade <- read.csv('~/Dropbox/Mayfield Lab/FunctionalTraitDatabase/Projects/SHAD1/raw/tom_shade.csv',
header = T, stringsAsFactors = F)
# in this project, traits were only collected on the focal individuals (and no on the neighbours)
# Claire's shade data
shad1.1 <- plant_level_data[ , c('Focal.sp', 'Height', 'Num.fl.total', 'Seedcount.extrap.integer')]
colnames(shad1.1) <- c('species', 'height', 'flower_number', 'seed_number')
shad1.1 <- melt(shad1.1, id.vars = 'species')
shad1.1 <- data.frame(project = 'SHAD1',
species = shad1.1$species,
traits = shad1.1$variable)
shad1.1 <- unique(shad1.1)
# Tom's shade data
# rename species in tom's data
tom_shade[tom_shade$species == 'h', ]$species <- 'H.glutinosum'
tom_shade[tom_shade$species == 'c', ]$species <- 'A.calendula'
tom_shade[tom_shade$species == 'p', ]$species <- 'P.airoides'
tom_shade[tom_shade$species == 'v', ]$species <- 'V.rosea'
shad1.2 <- tom_shade[ , c('species', 'Height', 'canopy.arch', 'Longest.Leaf', 'no.developed.flowers', 'Mean.seed.per.flower')]
colnames(shad1.2) <- c('species', 'height', 'canopy.arch', 'longest_leaf', 'flower_number', 'mean_seed_number_per_flower')
shad1.2 <- melt(shad1.2, id.vars = 'species')
shad1.2 <- data.frame(project = 'SHAD1',
species = shad1.2$species,
traits = shad1.2$variable)
shad1.2 <- unique(shad1.2)
### And finally for the watering data
# I'm still waiting on Claire to get back to me before collating the raw data into the Project folder, so I'm using the files she sent me
# for the coexistence project
# species_attributes <- read.csv('~/Dropbox/Work/Projects/2017_Coex_Envmt/1.data/raw/watering/species attributes_v2.csv',
# header = T, stringsAsFactors = F)
# species_attributes <- species_attributes[ , c('Correct.species.name', 'Mean.maxheight.Perenjori.2011.mm', 'Mean.maxheight.Bendering.2011.mm',
# 'Phenology.averaged.2011', 'Mean.canopy.shape.Perenjori', 'Mean.canopy.shape.Bendering')]
# I was going to include these traits until I realised they are averaged over the species (no individual trait data available for those)
plot_data <- read.csv('~/Dropbox/Work/Projects/2017_CoexEnvmt/1.data/raw/watering/2014 plot data cleaned up by Claire.csv',
header = T, stringsAsFactors = F)
# rename species
plot_data[plot_data$Focal.sp == 'A', ]$Focal.sp <- 'A.calendula'
plot_data[plot_data$Focal.sp == 'H', ]$Focal.sp <- 'H.glabra'
plot_data[plot_data$Focal.sp == 'W', ]$Focal.sp <- 'W.acuminata'
plot_data[plot_data$Focal.sp == 'T', ]$Focal.sp <- 'T.cyanopetala'
watr1 <- plot_data[ , c('Focal.sp', 'Aboveground.biomass.g', 'Belowground.biomass.g', 'Number.flowers.total', 'Seedcount.extrapolated.integer')]
colnames(watr1) <- c('species', 'above_biomass', 'below_biomass', 'flower_number', 'seed_number')
watr1 <- melt(watr1, id.vars = 'species')
watr1 <- na.omit(watr1)
watr1 <- data.frame(project = 'WATR1',
species = watr1$species,
traits = watr1$variable)
watr1 <- unique(watr1)
### collate everything together:
final.df <- rbind(facl1, litt1, litt1.2, shad1.1, shad1.2, watr1)
write.csv(final.df, '~/Dropbox/Mayfield Lab/FunctionalTraitDatabase/species_traits_list_MB.csv', row.names = F)
<file_sep>
# -------------------------------------------------------------
# Code to combine project csvs for input into SQLite database
#
# by <NAME>7
# -------------------------------------------------------------
## Libraries and Functions
library("reshape") # for merge_recurse()
group_db_data <- function(proj_folder,
table_name,
save_path,
add_proj=FALSE) {
# Combines all files of the same name from different project folders. Only
# works if all folders to be combined have the same name and column names.
#
# Args:
# proj_folder: Path name of the project folder
# table_name: name of tables to be combined (should all be the same name)
# save_path: path name for the save location and name of combined file
# add_proj: if TRUE, adds project column to table, if FALSE, it doesn't.
# Default is FALSE
#
# Returns:
# A csv file in a given directory of the combined files. The .csv has no
# row or solumn names for ease of import into SQLite database
# access all project files with specific name
folder_list <- list.files(proj_folder,
recursive = TRUE,
pattern = table_name,
full.names = TRUE)
# create a list of projects
project_list <- list.files(proj_folder)
#read.csv for each directory
data_files <- lapply(folder_list, read.csv)
# Add project code into table
if (add_proj == TRUE) {
for (i in 1:length(data_files)) {
data_files[[i]]$project_title <- as.character(project_list[i])
}
}
# Merge all data frames
all_projects <- merge_recurse(data_files)
# give each row a unique identifier
all_projects$project_id <- 1:nrow(all_projects)
# Write table without row or column names (for easy import into SQLite db)
write.table(all_projects, file = save_path, sep = ",",
row.names = FALSE, col.names = FALSE)
}
# Run function
# Project, with add_proj = TRUE
group_db_data("/Users/margiemayfield/Google\ Drive/FunctionalTraitDatabase/Construction/projects",
"projects.csv",
"/Users/margiemayfield/Google\ Drive/FunctionalTraitDatabase/Construction/final_tables/projects.csv",
add_proj = TRUE)
# Field season
group_db_data("/Users/margiemayfield/Google\ Drive/FunctionalTraitDatabase/Construction/projects",
"field_season.csv",
"/Users/margiemayfield/Google\ Drive/FunctionalTraitDatabase/Construction/final_tables/field_season.csv",
add_proj = FALSE)
# Site
group_db_data("/Users/margiemayfield/Google\ Drive/FunctionalTraitDatabase/Construction/projects",
"site.csv",
"/Users/margiemayfield/Google\ Drive/FunctionalTraitDatabase/Construction/final_tables/site.csv",
add_proj = FALSE)
# Treatment
group_db_data("/Users/margiemayfield/Google\ Drive/FunctionalTraitDatabase/Construction/projects",
"treatment.csv",
"/Users/margiemayfield/Google\ Drive/FunctionalTraitDatabase/Construction/final_tables/treatment.csv",
add_proj = FALSE)
# Plot
group_db_data("/Users/margiemayfield/Google\ Drive/FunctionalTraitDatabase/Construction/projects",
"plot.csv",
"/Users/margiemayfield/Google\ Drive/FunctionalTraitDatabase/Construction/final_tables/plot.csv",
add_proj = FALSE)<file_sep>######################################
#### Code written by <NAME> ####
#### Version 1: 15-06-2017 ####
######################################
rm(list=ls())
##### Cleaning code for TIME1 ####
### set working directory
setwd("/home/uqtmart7/data/Dropbox/Mayfield Lab/FunctionalTraitDatabase/Projects/TIME1/RAW")
## projects dataframe
projects<-data.frame(project_id=1,researcher="Trace_Martyn",email="<EMAIL>",study_sites="perenjori")
## field_season dataframe
field_season<-data.frame(field_season_id=1,project_id=1,year=2016,crew="TraceMartyn_JulieGuenat_MargaretMayfield")
## site dataframe
site<-data.frame(site_id=1,site="perenjori",area=3.5,units="km.sq",lat=0,long=0,max_temp=20.0,min_temp=7.5,ann_precip=298.3)
## treatment dataframe
treatment<-data.frame(treatment_id=1,treatment="control")
########################
##### function to scrub TEM's H###D### code for plot id number #####
scrub.TEM<- function(x) {
den<-sapply(strsplit(as.character(x),"D"),"[[",2)
code.scrub<-gsub("H","",x=as.character(x))
code<-sapply(strsplit(gsub("D","_",code.scrub),"_"),"[[",1)
dm<-data.frame(cbind(den,code))
return(dm) }
###########################
##### function to add TEM's block id based on plot.number ####
block.TEM<- function(x) {
vc.bl<-data.frame(plot=as.numeric(x),block=0)
for (i in 1:length(x)) {
pt<-vc.bl$plot[i]
if(findInterval(pt,c(1,21))==T) {vc.bl$block[i]<-1}
else if(findInterval(pt,c(21,41))==T) {vc.bl$block[i]<-2}
else if(findInterval(pt,c(41,61))==T) {vc.bl$block[i]<-3}
else if(findInterval(pt,c(61,81))==T) {vc.bl$block[i]<-4}
else if(findInterval(pt,c(81,101))==T) {vc.bl$block[i]<-5}
}
return(vc.bl)
}
###########################
## read in raw file
raw<-read.csv('TIME1.csv')
## make plot dataframe
# extract the plot numbers from raw file
plot.code<-scrub.TEM(raw$ID)
# plot dataframe
plot<-data.frame(plot_id=unique(plot.code$code),field_season_id=1,site_id=1,block=1,treatment_id=1)
# add block numbers
plot$block<-block.TEM(plot$plot_id)[,2]
## make trait summary dataframe
# look for what traits are available
head(raw)
# list traits seperated by "_"
traits<-"NumberOfBuds_NumberOfFlowers_NumberOfFruits_MaxHeightmm_ShapeLong_Shape90_MeanLateralShape_ShapeRatio"
trait_summary<-data.frame(field_season_id=1,trait_summary=traits)
#####################
## write out csv's
setwd("/home/uqtmart7/data/Dropbox/Mayfield Lab/FunctionalTraitDatabase/Projects/TIME1/CLEAN")
write.csv(projects,"projects.csv",row.names=F)
write.csv(field_season,"field_season.csv",row.names=F)
write.csv(site,"site.csv",row.names=F)
write.csv(treatment,"treatment.csv",row.names=F)
write.csv(plot,"plot.csv",row.names=F)
write.csv(trait_summary,"trait_summary.csv")
<file_sep># ########################################
# Project: Traits database
# Script to clean BROM1 project data
#
# author: <NAME>
# date: July 2017
# #######################################
# Import the original datafile from 2014 ----
BROM1 <- read.csv("/Users/margiemayfield/Dropbox/Mayfield\ Lab/FunctionalTraitDatabase/Projects/BROM1/RAW/2014_bromus_plots.csv")
colnames(BROM1)
nrow(BROM1)
# Project Table ----
make_project <- function(id, researcher, email, study_site) {
project <- data.frame("project_id"=id,
"researcher"= researcher,
"email"= email,
"study_site" = study_site)
return(project)
}
make_project("1", "Hao Ran", "", "Kunjin")
# Field Season Table ----
make_field_season <- function(id, project_id, year, crew) {
field_season <- data.frame("field_season_id"=id,
"project_id" = project_id,
"year" = year,
"crew" = crew)
return(field_season)
}
make_field_season("1", "1", "2014", "Hao Ran")
<file_sep>README BROM1
The original file is from WA dropbox, in experiments_data -> 14_bromusPlots -> 2014 bromus plots.xlsx
Is this all the brooms data?
<file_sep>---------------------------------------------
-- Mayfield Lab Functional Trait database
-- example queries
---------------------------------------------
-- Summary table of project, field season and traits
select projects.project_id, researcher, email, site, trait_summary.fs_id, year, crew_list, traits from projects
join field_season on projects.project_id = field_season.project_id
join trait_summary on trait_summary.fs_id = field_season.fs_id;
-- add this to be site specific
WHERE site = 'Tasmania';
-- Select plots based on site and treatment
-- Select the column names you want in format table.column (if not from base table)
-- select where to join (this is the primary and foreign key talking to each other)
select plot_id, fs_id, site.site, block, treatment.treatment from plot
join site on plot.site = site.id
join treatment on plot.treatment = treatment.id;
select family.family, genus.genus, species, invasive.invasive, habit.habit, life_form.life_form from species
join family on species.family = family.family_id
join genus on species.genus = genus.genus_id
join invasive on species.invasive = invasive.invasive_id
join habit on species.habit = habit.habit_id
join life_form on species.life_form = life_form.life_form_id;
SELECT table1.col1, table1.col2, col3 FROM table1
JOIN col3 on table1.col3 = table2.col2;
--table1 = species
col1 = id
col2 = species
col3 = traits
--table2 = traits
col1 = traits_id
col2 = traits
<file_sep>This project involved one field season in 2013
Data collected by <NAME> and <NAME>
Methods should be described in the publication listed below.
### Files:
publication1.pdf: Claire, JD and MM's publication for this data. Contains methods. Full reference at the bottom
# /raw folder:
/claire_IEM_assays_2013.xls: results from deploying ion exchange membranes in each plot (IEMs) to test whether nitrate and ammonium cycling rates differed among treatment and control plots
/IEM extraction.xlsx: list of plot names and corresponding sample labels for the experiment above
*** those 2 files contain IEM data for plots from both the FACL1 and LITT1 projects - we will have to match plot numbers to figure out which are from which ***
note: the IEM data seems to be repeated in some of the sheets from the Litter_expt_Wainwright_compiled_170619.xlsx file ??
/Litter_expt_Wainwright_compiled_170619.xlsx
/Litter plot inventory Wainwright.xlsx
/litter plot level Wainwright 20aug14.xlsx
All the field data (plants & traits) for this project is contained in the 3 files above - any other 'litter project' files present in the Dropbox are redundant.
All files were copied from Mayfield Lab/Master Data Vault/Western Australia/Wainwright/Litter on 21/06/2017
Those files were then saved as .csv files for cleaning in R.
The .xlsx and .csv file names match.
Any 'compiled_xxx.csv' file is a sheet saved from the /Litter_expt_Wainwright_compiled_170619.xlsx, with 'xxx' standing for the sheet name
# /clean folder:
/cleaning_LITT1.R: script to clean raw data files for input into database
database-ready data are saved as .csv, with one file for each database table.
see databaseschema.png for a reference of table names and what they each contain
** Claire is (hopefully) writing up some metadata **
Publications:
Wainwright, <NAME>., <NAME>, and <NAME>. "Effects of exotic annual grass litter and local environmental gradients on annual plant community structure." Biological Invasions 19.2 (2017): 479-491.
-- Malyon 21/06/2017
-- extra comments Malyon 22/06/2017
<file_sep>This was a growth chamber experiment run once in 2013.
Data was collected solely by Claire
** Add to database at a later date **
Still I've collected all the relevant data files here for later.
Files:
/2012_densitydata.xlsx
/survival_data_01_08_12.xlsx
both of these were copied from Mayfield Lab/Master Data Vault/Western Australia/Wainwright/Density on 21/06/2017
They contain all the relevant data for the project
Raw data:
/2012_densitydata.xlsx: all sheets except “Sheet1”, “Sheet2”, “Margie comp coeffs”, “Biomass output”, and “repro output”
/survivaldata_08_01_12.xlsx: All sheets
Publications:
<NAME>, <NAME>, <NAME>, <NAME>; Diverse outcomes of species interactions in an invaded annual plant community. J Plant Ecol 2016 rtw102. doi: 10.1093/jpe/rtw102
-- Malyon 21/06/2017
<file_sep>{\rtf1\ansi\ansicpg1252\cocoartf1561\cocoasubrtf400
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;}
{\*\expandedcolortbl;;}
\paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh8080\viewkind0
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0
\f0\fs24 \cf0 2014_Germination data_from burried bags \
\
cals for watering paper \
- focal = species 4 letter code WA annuals \
- resv = reserve (Perenjori or Kunjin\
- bag marked = bag identifier?\
- bag = different bag identifier?\
- buried = number of seeds buried in ground \
- recovered = how many seeds were recovered\
- field seedling = visible seedlings that germinated in the bags whilst in the field \
- fielded = seeds that died in the field \
- seedtest = non-dead seeds that underwent lab germination and viability tests \
- labseedling = seeds that germinated in lab conditions \
- labstained = seeds that did not germinate in lab conditions but stained red in TZ solution \
- landed = seeds that did not germinate in lab or stain red in TZ\
- totalviability\
- p.viable.recovered = percentage\
- p.viable.buried = percentage\
- p.germ.field - percentage\
-
\b num.fieldgerm = fieldseedling\
- pgerm.field = num.fieldgerm/30 = percentage that germinated in the field\
- num.deadinfieldandlab = fielddead + labdead\
- num.recovered = recovered\
- num.lost = 30-number recovered (number of seeds recovered from the field)\
- num.surv.ungerm = labseedling + labstained \
- surv.ungerm = num.surv.ungerm/(30-num.fieldgerm) = survived but didn\'92t germinate
\b0 \
Note - metadata included \
\
\
\
2015 focal species germ and viability rates\
Sheet1\
- Species = WA annual species, full genus species name \
- germination = data from 2014_Germination data_from burried bags?\
- viability = same?\
- Germination = name of person\'92s honours thesis \
- Viability.datasource = same as Germination \
- Notes\
No metadata file \
Sheets 2 and 3 empty \
\
\
\
Copy of RSB 14 - 28 Germination data all species \
- honestly no clue \
\
\
\
germination_bags2014\
\
Sheet1\
- species = WA annual species full genus species names given \
- Seed per bag = number of seeds in each bag \
- Bag number (total) = number of bags out in the field \
- Bag number Kunjin = the number of bags placed in the field in Kunjin\
- Bag number Perenjori = the number of bags placed in the field in Kunjin\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
}<file_sep>##################################
# Code to subset species based on Johns 2010 and 2011 survey data.
# Species data will be used for Fuctional trait database
# by <NAME> 2017
# Load libraries #####
library(stringr) ## For str_split_fixed function
# Upload data and subset into required columns ####
#------------------------------------------------
john_species <-read.csv("/Users/cme/Google\ Drive/FunctionalTraitDatabase/Species/species_in_quadrat_scale_data_June_2017.csv")
john_species <- data.frame("species" = john_species$species,
"life.form"=john_species$life.form,
"invasive"=john_species$exotic)
head(john_species)
# Select only the rows with unique species ####
#-----------------------------------------
j_sub <-subset(john_species, !duplicated(species))
head(j_sub)
# Split "species" column to "Genus" and "Species" ####
#------------------------------------------------
genus_species <- data.frame(str_split_fixed(j_sub$species, "\\.", 2))
colnames(genus_species) <- c("genus", "species")
head(genus_species)
# Split "life.form" into "life_form" and "habit" ####
#------------------------------------------------
### Some species have three eg. "tuberous.perennial.forb"
lf_habit <- data.frame(str_split_fixed(j_sub$life.form, "\\.", 3))
colnames(lf_habit) <- c("life_form", "habit", "habit2")
lf_habit
# fill in empty values with NA's and then omit them.
lf_habit$habit2[lf_habit$habit2 == ""] <- NA
no_nas <- na.omit(lf_habit)
no_nas
# get row numbers of those to delete later
row_nums <- rownames(no_nas)
row_nums
# reformat to ensure columns are named correctly
reformat_lf_habit <- data.frame("life_form" = no_nas$habit,
"habit" = paste(no_nas$habit2, no_nas$life_form, sep="+"))
# delete original rows where the data is wrong based on the rownames
update_lf_hab<- lf_habit[!rownames(lf_habit) %in% row_nums, ]
length(update_lf_hab$life_form)
# delete last column, and add new rows
clean_lf_hab <- data.frame("life_form"=update_lf_hab$life_form,
"habit"=update_lf_hab$habit)
# rbind the reformated lf_hab data to the clean_lf_hab data
clean_lf_hab <- rbind(clean_lf_hab, reformat_lf_habit)
length(clean_lf_hab$habit)
# Exotic: change all 1 to exotic, and 0 to native
#------------------------------------------------
j_sub$invasive[j_sub$invasive == 0] <- "native"
j_sub$invasive[j_sub$invasive == 1] <- "exotic"
head(j_sub, n=50)
# Final Species table ####
#---------------------
species <- data.frame("species_id",
"family",
"genus" =,
"species",
"invasive",
"habit",
"life_form")
family <- data.frame("family_id",
"family")
genus <-data.frame("genus_id" = 1:length(unique(genus_species$genus)),
"genus" = unique(genus_species$genus))
genus
invasive <- data.frame("invasive_id" = c(1, 2),
"invasive" = c("native", "exotic"))
habit <- data.frame("habit_id" = 1:length(unique(clean_lf_hab$life_form)),
"habit" = unique(clean_lf_hab$life_form))
head(habit)
life_form <- data.frame("life_form_id"= 1:length(unique(clean_lf_hab$habit)),
"life_form"=unique(clean_lf_hab$habit))
life_form
# Function to get a list of unique species names from 'x' dataframe, and 'y' column name.
unique_species <- function(df, y) {
sub = subset(df, !duplicated(y))
}
unique_species(john_species, species)
## CLAIRE's species data
#-----------------------
claire_species <-read.csv("/Users/cme/Google\ Drive/FunctionalTraitDatabase/Species/Claire_species_20attributes_v2.csv")
claire_species2 <-read.csv("/Users/cme/Google\ Drive/FunctionalTraitDatabase/Species/TEM.Species.List_15_06_2017.csv")
colnames(john_species)
colnames(claire_species)
colnames(claire_species2)
|
72f8e366778885191fd165f996165b9c2a7bf954
|
[
"SQL",
"Markdown",
"Python",
"Text",
"R",
"RMarkdown"
] | 44
|
Text
|
Mayfieldlab/FunctionalTraitDB
|
b098041b74056cc63c6f79898a783f81cab18212
|
c4c0d7e3ffb7cc711ffcd88f2d824ec02f9abb10
|
refs/heads/master
|
<repo_name>ff0000-ad-tech/cs-plugin-msnbc-apple-news<file_sep>/README.md
##### RED Interactive Agency - Ad Technology
[](https://www.npmjs.com/package/@ff0000-ad-tech%2Fcs-plugin-msnbc-apple-news)
[](https://github.com/ff0000-ad-tech/cs-plugin-msnbc-apple-news)
[](https://www.npmjs.com/package/@ff0000-ad-tech%2Fcs-plugin-msnbc-apple-news)
[](https://github.com/ff0000-ad-tech/cs-plugin-msnbc-apple-news/graphs/contributors/)
[](https://github.com/ff0000-ad-tech/cs-plugin-msnbc-apple-news/commits/master)
[](https://github.com/ff0000-ad-tech/cs-plugin-msnbc-apple-news/blob/master/LICENSE)
[](http://makeapullrequest.com)
# Creative Server Plugin - Apple News Responsive Ad Builder
This plugin is to assist with building ads to deploy on Apple News.
This means that they must resize to the size associated with the Apple device and orientation defined by the [Apple News HTML spec](https://developer.apple.com/news-publisher/News-Ad-Specifications.pdf).
There are two main Apple News sizes: the **Double Banner** and the **Large Banner**.
For both, you would choose two sizes to designate as either the **Landscape** or **Portrait** creative.
Then the Apple News ad will use the size appropriate for the given device and orientation.
## Important Notes
- __If asked to built another Apple News creative, may be worth building out a size per device instead of just one creative that responds to every listed size__
- then having the parent index choose among a given size instead of just landscape or portrait, like it's currently doing
- __When asked to make a specific size for Apple News (e.g. 1242x699 for Large Banners on iPhones 6-8), be sure to build it to the dimension in points__
- so for the 1242x699 size, build it in __414x233__ instead b/c those are the dimensions of the iframe on that particular form factor
## How It Works
The ad's main `index.html` has an iframe that renders the appropriate size creative based on the device (iPhone 5, 6, X, etc.) and orientation (i.e. landscape vs. portrait).
To enable clickthrough on iOS apps such as the Apple News app, we need to use an `<a>` with the `href` set to the clickthrough URL. The parent `window` has a `message` listener that waits for data that looks something like this:
```js
{
// key-value pair this index uses to update clickTag
type: 'UPDATE_CLICKTAG',
// URL to set clickTag to
message: 'http://msnbc.com/something'
}
```
In the Apple News Responsive Build Source (__TODO__), a `postClickTagURL()` function exists within the `index.html` which gets called in `AdData.js`. In `AdData`, you can call `postClickTagURL()` with the dynamic clickTag URL you need.
## Usage
- __In the Creative Server root interface:__
1. Select the two sizes you'll need for your responsive creative (e.g. 1242x699 and 2208x699 for the Large Banner's portrait and landscape orientations, respectively)
1. In the Plugins dropdown, select __MSNBC Apple News__ and hit the 🔥
- __On the plugin page__:
1. Fill out the fields and choose the appropriate sizes for the landscape/portrait orientations
1. Hit __Render Ad__ when ready
1. You will get a prompt telling you that the ads have been built successfully
1. files will be in the `_apple-news-output` directory of project root
- _note about underscore in directory name: not having the underscore will cause a nested Creative Server to pop up_
<file_sep>/lib/consts.js
exports.DEFAULT_CLICKTAG = 'https://msnbc.com'
<file_sep>/source/js/main.js
import superagent from 'superagent'
import { getQueryParams } from 'ad-global'
const query = getQueryParams()
query.targets = JSON.parse(query.targets)
query.folders = JSON.parse(query.folders)
console.log('query', query)
let form, submitBtn
const sizesToTargets = {}
const textInputs = {}
const checkboxInputs = {}
const selects = {}
init()
//
function init() {
processDOM()
// parse sizes
Object.keys(query.targets).forEach(target => {
const size = target.match(/\d+x\d+/)[0]
sizesToTargets[size] = query.targets[target]
})
// populate size options
Object.values(selects).forEach(selectEl => {
populateSizeSelect(selectEl, sizesToTargets)
})
// populate default clickTag
textInputs['default-clicktag-input'].value = 'http://msnbc.com'
// add form handlers
setFormListeners()
validateForm()
}
function processDOM() {
form = document.getElementById('main-form')
submitBtn = document.getElementById('submit-btn')
// process diff form inputs
for (let i = 0; i < form.elements.length; i++) {
const input = form.elements[i]
if (input instanceof HTMLInputElement) {
if (input.type === 'checkbox') {
checkboxInputs[input.id] = input
} else {
textInputs[input.id] = input
}
} else if (input instanceof HTMLSelectElement) {
selects[input.id] = input
}
}
}
function populateSizeSelect(selectEl, sizesToTargets) {
const sizes = Object.keys(sizesToTargets)
const sizeEls = sizes.map(size => {
const target = sizesToTargets[size]
const opt = document.createElement('option')
opt.value = opt.innerText = size
selectEl.appendChild(opt)
})
return sizeEls
}
function setFormListeners() {
const inputs = Object.values(textInputs).concat(Object.values(selects))
setCreativeTypeListeners()
inputs.forEach(input => {
input.addEventListener('input', event => {
submitBtn.disabled = !validateForm()
})
})
form.addEventListener('submit', submitForm)
}
function setCreativeTypeListeners() {
const creativeTypeInput = textInputs['creative-type-input']
const radioInputs = Array.prototype.slice.call(document.querySelectorAll('input[type="radio"]'))
// TODO: checking radio populates creative input with its value
radioInputs.forEach((radio, i) => {
const otherRadios = Array.prototype.filter.call(radioInputs, (_, j) => i !== j)
radio.addEventListener('input', event => {
creativeTypeInput.value = radio.value
otherRadios.forEach(otherRadio => {
otherRadio.checked = false
})
})
})
creativeTypeInput.addEventListener('input', event => {
radioInputs.forEach(radio => {
radio.checked = creativeTypeInput.value.trim() === radio.value
})
})
}
function validateForm() {
if (form.reportValidity) {
return form.reportValidity()
}
const inputs = Object.values(textInputs).concat(Object.values(selects))
for (let input of inputs) {
if (!input.value) {
return false
}
}
return true
}
function submitForm(event) {
event.preventDefault()
const data = {
action: 'render',
...constructData()
}
superagent
.post('/@ff0000-ad-tech/cs-plugin-msnbc-apple-news/api/')
.send(data)
.end((err, res) => {
if (err) {
return alert(`Submit error: ${err}`)
}
alert('Ads successfully built. Returning to Creative Server...')
location.href = query.api.replace('/api', '/app')
})
return false
}
function constructData() {
const landscapeSize = selects['landscape-select'].value
const portraitSize = selects['portrait-select'].value
const landscapePath = sizesToTargets[landscapeSize]
const portraitPath = sizesToTargets[portraitSize]
const data = {
creativeType: textInputs['creative-type-input'].value,
clickTag: textInputs['default-clicktag-input'].value,
orientationsToSizePaths: {
landscape: `${query.context}${landscapePath}`,
portrait: `${query.context}${portraitPath}`
},
minify: checkboxInputs['minify-checkbox'].value
}
return data
}
<file_sep>/lib/utils.js
const fsp = require('fs').promises
const recursiveCopy = require('recursive-copy')
function ensureDir(dirpath) {
return fsp.mkdir(dirpath).catch(err => {
if (err.code !== 'EEXIST') {
console.error('Error ensuring directory')
throw err
}
})
}
function copyDir(src, dst) {
const copyOpts = {
overwrite: true,
dot: true
}
return recursiveCopy(src, dst, copyOpts).catch(err => {
console.error('Error copying directory files')
throw err
})
}
function ensureRequiredOptions(argObj, required) {
for (let opt of required) {
if (!argObj[opt]) {
throw new Error('Missing required option: ' + opt)
}
}
}
module.exports = {
ensureDir,
copyDir,
ensureRequiredOptions
}
<file_sep>/lib/package-apple-news.js
const fs = require('fs')
const fsp = fs.promises
const path = require('path')
const templateRenderer = require('./template-renderer')
const { ensureDir, copyDir, ensureRequiredOptions } = require('./utils')
const CONSTS = require('./consts')
async function packageAppleNews(argsObj) {
// prettier-ignore
ensureRequiredOptions(argsObj, [
'targetDir',
'creativeType',
'orientationsToSizePaths',
'templatePath'
])
const {
targetDir,
creativeType,
orientationsToSizePaths: { landscape, portrait },
templatePath,
clickTag = CONSTS.DEFAULT_CLICKTAG,
minify = true
} = argsObj
// create new directory w/ name "creativeType" (either Double or Large Banner)
const creativePath = path.resolve(targetDir, creativeType)
await ensureDir(creativePath)
// copy ad sizes to respective orientation (either Landscape or Portrait)
// * ensure there's a Landscape and Portrait key in sizeToOrientation obj
if (!landscape || !portrait) {
throw new Error('A path to an ad size must be provided for both landscape and portrait orientations in the orientationsToSizePaths arg')
}
await Promise.all([
copyOrientationFiles({
sizePath: landscape,
creativePath,
orientation: 'landscape'
}),
copyOrientationFiles({
sizePath: portrait,
creativePath,
orientation: 'portrait'
})
])
// render EJS template
await templateRenderer.renderTemplate({
templatePath,
creativePath,
minify,
templateVars: {
creativeType,
clickTag
}
})
}
async function copyOrientationFiles({ sizePath, creativePath, orientation }) {
// ensure orientation directory exists in ad
const orientationPath = path.resolve(creativePath, orientation)
await ensureDir(orientationPath)
// copy files from size to orientation
return copyDir(sizePath, orientationPath)
}
module.exports.packageAppleNews = packageAppleNews
<file_sep>/lib/api.js
const _argv = require('minimist')(process.argv.slice(2))
const path = require('path')
const { packageAppleNews } = require('./package-apple-news')
const { ensureDir } = require('./utils')
const debug = require('@ff0000-ad-tech/debug')
var log = debug('cs-plugin-msnbc-apple-news:api')
const CONSTS = require('./consts')
function processArgv(argv) {
const processed = {}
Object.keys(argv).forEach(key => {
let val = argv[key]
try {
val = JSON.parse(val)
} catch (err) {
// ignore parsing exceptions
}
processed[key] = val
})
return processed
}
const api = async () => {
const argv = processArgv(_argv)
switch (argv.action) {
// render responsive ad
case 'render':
const outputDir = path.resolve(argv.context, '_apple-news-output')
ensureDir(outputDir)
await packageAppleNews({
targetDir: outputDir,
creativeType: argv.creativeType,
orientationsToSizePaths: argv.orientationsToSizePaths,
templatePath: path.resolve(__dirname, '../templates/template.ejs'),
clickTag: argv.clickTag,
minify: argv.minify
})
break
default:
break
}
}
api()
|
40ec801b8ec7e744731969f2e42a85d33b5b2e39
|
[
"Markdown",
"JavaScript"
] | 6
|
Markdown
|
ff0000-ad-tech/cs-plugin-msnbc-apple-news
|
da9696a5d6ccd90d9fb8afcf5971e0ae4e4395c9
|
25937273e6af08364cbf2052f46a76de4f6e817c
|
refs/heads/main
|
<file_sep># compile-release
<a href="https://raw.githubusercontent.com/jaid/compile-release/master/license.txt"><img src="https://img.shields.io/github/license/jaid/compile-release?style=flat-square" alt="License"/></a> <a href="https://github.com/sponsors/jaid"><img src="https://img.shields.io/badge/<3-Sponsor-FF45F1?style=flat-square" alt="Sponsor compile-release"/></a>
<a href="https://actions-badge.atrox.dev/jaid/compile-release/goto"><img src="https://img.shields.io/endpoint.svg?style=flat-square&url=https%3A%2F%2Factions-badge.atrox.dev%2Fjaid%2Fcompile-release%2Fbadge" alt="Build status"/></a> <a href="https://github.com/jaid/compile-release/commits"><img src="https://img.shields.io/github/commits-since/jaid/compile-release/v1.3.1?style=flat-square&logo=github" alt="Commits since v1.3.1"/></a> <a href="https://github.com/jaid/compile-release/commits"><img src="https://img.shields.io/github/last-commit/jaid/compile-release?style=flat-square&logo=github" alt="Last commit"/></a> <a href="https://github.com/jaid/compile-release/issues"><img src="https://img.shields.io/github/issues/jaid/compile-release?style=flat-square&logo=github" alt="Issues"/></a>
<a href="https://npmjs.com/package/compile-release"><img src="https://img.shields.io/npm/v/compile-release?style=flat-square&logo=npm&label=latest%20version" alt="Latest version on npm"/></a> <a href="https://github.com/jaid/compile-release/network/dependents"><img src="https://img.shields.io/librariesio/dependents/npm/compile-release?style=flat-square&logo=npm" alt="Dependents"/></a> <a href="https://npmjs.com/package/compile-release"><img src="https://img.shields.io/npm/dm/compile-release?style=flat-square&logo=npm" alt="Downloads"/></a>
**CLI wrapper for zeit/pkg.**
## Installation
<a href="https://npmjs.com/package/compile-release"><img src="https://img.shields.io/badge/npm-compile--release-C23039?style=flat-square&logo=npm" alt="compile-release on npm"/></a>
```bash
npm install --global compile-release@^1.3.1
```
<a href="https://yarnpkg.com/package/compile-release"><img src="https://img.shields.io/badge/Yarn-compile--release-2F8CB7?style=flat-square&logo=yarn&logoColor=white" alt="compile-release on Yarn"/></a>
```bash
yarn global add compile-release@^1.3.1
```
## CLI Usage
After installing package `compile-release` globally, you can use its command line interface.
```bash
compile-release
```
For usage instructions:
```bash
compile-release --help
```
## Development
Setting up:
```bash
git clone git@github.com:jaid/compile-release.git
cd compile-release
npm install
```
Testing:
```bash
npm run test:dev
```
Testing in production environment:
```bash
npm run test
```
## License
```text
MIT License
Copyright © 2020, Jaid <<EMAIL>> (github.com/jaid)
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.
```
<file_sep>import path from "path"
import coffee from "coffee"
const main = path.resolve(process.env.MAIN)
it("should run internal command", () => coffee.fork(main)
.expect("code", 0)
.debug()
.end(), 1000 * 60 * 2)<file_sep>import path from "path"
import fs from "fs"
import yargs from "yargs"
import fsp from "@absolunet/fsp"
import {noop} from "lodash"
import globby from "globby"
import archiver from "archiver"
import {exec} from "pkg"
import promiseSequence from "promise-sequence"
import whichPromise from "which-promise"
import execa from "execa"
import jaidLogger from "jaid-logger"
import stringifyAuthor from "stringify-author"
import moment from "moment"
const logger = jaidLogger(_PKG_TITLE)
const findDpkgDebFile = async () => {
try {
return await whichPromise("dpkg-deb")
} catch {
return false
}
}
const job = async argv => {
const packageFolder = process.cwd()
const buildFolder = path.join(packageFolder, "dist", "package", "production")
const buildFolderExists = await fsp.pathExists(buildFolder)
if (!buildFolderExists) {
logger.warn(`Build folder ${buildFolder} not found`)
process.exit(1)
}
const packageJsonFile = path.join(buildFolder, "package.json")
const packageJsonFileExists = await fsp.pathExists(packageJsonFile)
if (!packageJsonFileExists) {
logger.warn(`${packageJsonFile} not found`)
process.exit(1)
}
const pkg = await fsp.readJson(packageJsonFile)
const packageId = `${pkg.name}_v${pkg.version}`
const getMode = async () => {
for (const knownMode of ["index", "cli", "app"]) {
const exists = await fsp.pathExists(path.join(buildFolder, `${knownMode}.js`))
if (exists) {
logger.info("Mode: %s", knownMode)
return knownMode
}
}
logger.warn("No mode determined")
}
const mode = await getMode()
const prodScript = path.join(buildFolder, `${mode}.js`)
const devScript = path.join(packageFolder, "dist", "package", "development", `${mode}.js`)
const hasDevelopmentBuild = await fsp.pathExists(devScript)
const releaseFolder = path.join(packageFolder, "dist", "github")
const [copyList, miniArchiveList] = await Promise.all([
globby(["readme.*", "*.d.ts", "package.json", "license.*", "thirdPartyLicenses.*"], {
cwd: buildFolder,
case: false,
onlyFiles: true,
}),
globby(["*.{ts,js,jsx}", "package.json", "license.*", "thirdPartyLicenses.*"], {
cwd: buildFolder,
case: false,
onlyFiles: true,
}),
fsp.mkdirp(releaseFolder),
])
await fsp.emptyDir(releaseFolder)
const releaseTasks = []
for (const file of copyList) {
const from = path.join(buildFolder, file)
const to = path.join(releaseFolder, file)
releaseTasks.push(fsp.copy(from, to))
}
const fullArchive = archiver("zip", {level: 9})
fullArchive.directory(buildFolder, false)
fullArchive.pipe(path.join(releaseFolder, `${packageId}.zip`) |> fs.createWriteStream)
releaseTasks.push(fullArchive.finalize())
const miniArchive = archiver("zip", {level: 9})
for (const file of miniArchiveList) {
miniArchive.file(path.join(buildFolder, file), {name: file})
}
miniArchive.pipe(path.join(releaseFolder, `${packageId}_min.zip`) |> fs.createWriteStream)
releaseTasks.push(miniArchive.finalize())
if (mode === "cli" || mode === "app") {
const pkgOptions = [
"--config",
path.join(buildFolder, "package.json"),
"--options",
"max_old_space_size=4000",
"--public",
]
let targets = [
{
id: "latest-win-x64",
input: prodScript,
output: `${packageId}_windows_x64`,
},
{
id: "latest-macos-x64",
input: prodScript,
output: `${packageId}_mac_x64`,
},
{
id: "latest-linux-x64",
input: prodScript,
output: `${packageId}_linux_x64`,
},
{
id: "latest-alpine-x64",
input: prodScript,
output: `${packageId}_alpine_x64`,
},
]
if (hasDevelopmentBuild) {
targets = [
{
id: "latest-win-x64",
input: devScript,
output: `${packageId}_debug_windows_x64`,
},
{
id: "latest-macos-x64",
input: devScript,
output: `${packageId}_debug_mac_x64`,
},
{
id: "latest-linux-x64",
input: devScript,
output: `${packageId}_debug_linux_x64`,
},
{
id: "latest-alpine-x64",
input: devScript,
output: `${packageId}_debug_alpine_x64`,
},
...targets,
]
}
const compileExecutableTasks = targets.map(target => () => exec([...pkgOptions, "--target", target.id, "--output", path.join(releaseFolder, target.output), target.input]))
releaseTasks.push(compileExecutableTasks |> promiseSequence)
}
await Promise.all(releaseTasks)
if (mode === "cli" || mode === "app") {
const dpkgDebFile = await findDpkgDebFile()
if (dpkgDebFile) {
logger.info("Found dpkg-deb binary at %s", dpkgDebFile)
const scriptBinaryFile = `${packageId}_linux_x64`
const debFolder = path.join(packageFolder, "dist", "deb")
const debBinFolder = path.join(debFolder, "usr", "local", "bin")
await fsp.ensureDir(debBinFolder)
const releaseBinFile = path.join(releaseFolder, scriptBinaryFile)
const debBinFile = path.join(debBinFolder, pkg.name)
await fsp.copyFile(releaseBinFile, debBinFile)
logger.info("Copied linux binary %s to %s", releaseBinFile, debBinFile)
const {size} = await fsp.stat(debBinFile)
const debInfo = {
Package: pkg.name,
Version: pkg.version,
"Standards-Version": pkg.version,
Maintainer: pkg.author |> stringifyAuthor,
Description: pkg.description,
"Installed-Size": Math.ceil(size / 1024),
Section: "base",
Priority: "optional",
Architecture: "amd64",
Date: moment().format("ddd, DD MMM YYYY HH:mm:ss ZZ"),
}
if (pkg.homepage) {
debInfo.Homepage = pkg.homepage
}
const controlContent = debInfo
|> Object.entries
|> #.map(([key, value]) => `${key}: ${value}`)
|> #.join("\n")
const controlFile = path.join(debFolder, "DEBIAN", "control")
logger.info("Wrote %s properties to info file %s", Object.keys(debInfo).length, controlFile)
await fsp.outputFile(controlFile, `${controlContent}\n`, "utf8")
await execa(dpkgDebFile, ["--build", debFolder, path.join(releaseFolder, `${packageId}_amd64.deb`)])
} else {
logger.warn("Skipping deb building, dpkg-deb not found")
}
}
}
yargs.command("$0", "Creates some release files", noop, job).argv
|
9bc304ecd6a6d8fb8c66293f9b3119f31764fef1
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
Jaid/compile-release
|
1af1ccafa1c3b76963eb45944eba79f0da3fa6de
|
338a7535870d71fa914b0c9b9b40abdb29f1faa2
|
refs/heads/master
|
<file_sep>import React, { useState, useEffect } from "react";
import ClassInfo from "./ClassInfo";
function ClassForm(props) {
const [classState, setClassState] = useState([]);
useEffect(() => {
fetch("http://localhost:4000/classes/all")
.then(response => response.json())
.then(data => setClassState(data.classResponse));
}, []);
const images = [
"https://media-waterdeep.cursecdn.com/avatars/thumbnails/6/342/420/618/636272680339895080.png",
"https://media-waterdeep.cursecdn.com/avatars/thumbnails/6/369/420/618/636272705936709430.png",
"https://media-waterdeep.cursecdn.com/avatars/thumbnails/6/371/420/618/636272706155064423.png",
"https://media-waterdeep.cursecdn.com/avatars/thumbnails/6/346/420/618/636272691461725405.png",
"https://media-waterdeep.cursecdn.com/avatars/thumbnails/6/359/420/618/636272697874197438.png",
"https://media-waterdeep.cursecdn.com/avatars/thumbnails/6/489/420/618/636274646181411106.png",
"https://media-waterdeep.cursecdn.com/avatars/thumbnails/6/365/420/618/636272701937419552.png",
"https://media-waterdeep.cursecdn.com/avatars/thumbnails/6/367/420/618/636272702826438096.png",
"https://media-waterdeep.cursecdn.com/avatars/thumbnails/6/384/420/618/636272820319276620.png",
"https://media-waterdeep.cursecdn.com/avatars/thumbnails/6/485/420/618/636274643818663058.png",
"https://media-waterdeep.cursecdn.com/avatars/thumbnails/6/375/420/618/636272708661726603.png",
"https://media-waterdeep.cursecdn.com/avatars/thumbnails/6/357/420/618/636272696881281556.png"
];
return (
<div className="class-form-wrapper">
<h1 className="class-form_title">Choose Your Character's Class</h1>
<div className="multiple_class_cards">
{classState.map((item, index) => {
item.image = images[index];
return (
<div className="class_card">
<h1 className="dndClass_name" key={item.classId}>
{item.name}
</h1>
<img className="dndClass_image" src={item.image} />
<ClassInfo
index={index + 1}
classSelect={props.handleClassSelect}
/>
<div className="classLearn_button_wrapper">
<a
className="classLearn_button"
href={"https://www.dndbeyond.com/classes/" + item.name}
target="_blank"
>
Learn More
</a>
</div>
<button
id={classState[index].classId}
className="select-class_button"
name="dndClass"
onClick={props.onclick}
value="4"
>
{`Select ${item.name}`}
</button>
</div>
);
})}
</div>
<button
className="generic_button class_back-button"
onClick={props.onclick}
value="2"
>
Go Back
</button>
</div>
);
}
export default ClassForm;
<file_sep>D&D&U
Dungeons and Dragons today isn’t your parents’ RPG. Celebrating its 45th anniversary this year, D&D’s popularity and visibility continue to grow, as does its potential user base. However, this increased visibility comes with potential new players who are scared off by the perceived barrier to entry - specifically, building their first character, which can be intimidating when you’re faced with a blank character sheet. D&D&U is here to streamline that process: users can build out a character’s stats, race, class, and alignment, ensuring they don’t forget a vital part of character creation, and tracking their current character build along the way. D&D&U is the quickest way to get off of the paper and onto your next adventure.
© 2019<file_sep>import React, { useState } from "react";
import "../styles/main.css";
function Landing(props) {
return (
<div className="landing-div">
<h1 className="landing_title">Welcome Adventurer!</h1>
<h2 className="landing_title">Let's create your D&D champion!</h2>
<center>
<br></br>
<button
className="generic_button"
type="submit"
value="2"
name="next"
onClick={props.onclick}
>
Get Started
</button>
</center>
</div>
);
}
export default Landing;
<file_sep>class ModifierCalculator {
constructor (statValue) {
this.initialValue = statValue;
this.modifierValue = this.calculateModifier(statValue);
}
static calculateModifier (statValue) {
if (statValue < 3) {
return -4;
} else if (statValue > 18) {
return 4;
} else {
return modifierReference[statValue];
}
}
}
const modifierReference = {
3: -4,
4: -3,
5: -3,
6: -2,
7: -2,
8: -1,
9: -1,
10: 0,
11: 0,
12: 1,
13: 1,
14: 2,
15: 2,
16: 3,
17: 3,
18: 4,
}
module.exports = ModifierCalculator;<file_sep>import React, { useState, useEffect } from "react";
import "./styles/main.css";
import "./App.css";
import Landing from "./Components/Landing";
import Nav from "./Components/nav";
import Main from "./Components/Main";
function App() {
const [navState, setNavState] = useState("");
const handleClick = event => {
const val = event.target.value;
setNavState(val);
};
return (
<div className="main-wrapper">
<header>
<Nav onclick={handleClick} />
</header>
<div className="main-content">
<Main props={navState} />
</div>
{navState}
</div>
);
}
export default App;
<file_sep>import React, { useState, useEffect } from "react";
function ClassInfo(props) {
const [classInfo, setClassInfo] = useState([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
fetch(`http://localhost:4000/classes/${props.index}`)
.then(res => res.json())
.then(response => {
setClassInfo(response);
setIsLoading(false);
props.classSelect(response);
})
.catch(error => console.log(error));
}, []);
return (
<div>
{isLoading && <p>Please Wait</p>}
<div color="white">
<label>
<h3 className="class-info_hit-die">Hit Die: {classInfo.hit_die}</h3>
</label>
</div>
</div>
);
}
export default ClassInfo;
<file_sep>import React, { useState, useEffect } from "react";
import useFetchGet from "../utils/utils";
import ModifierCalculator from "../utils/modifier-calculator";
import DiceRoll from "../utils/dice-roll";
import "../styles/stat.css";
// Dice Rolls
const DiceRow = ({ diceRollArray = [] }) => {
return (
<table className="diceroll">
<tbody>
<tr>
{diceRollArray.map((roll, index) => (
<td className="die-value selection" key={index}>
{roll}
</td>
))}
</tr>
</tbody>
</table>
);
};
// Row of Stats in StatForm Table
const StatRow = ({ attribute, bonus, statechange }) => {
const [modifier, setModifier] = useState(0);
const [stat, setStat] = useState(0);
const [total, setTotal] = useState(0);
function formatSelectedRolls() {
const diceRollList = document.querySelectorAll(".die-value");
const statInputs = document.querySelectorAll(".stat-value");
let matchIndex = {};
for (let x = 0; x < diceRollList.length; x++) {
let findCount = 0;
let die = diceRollList[x];
for (let i = 0; i < statInputs.length; i++) {
let stat = statInputs[i];
if (findCount > 0) {
continue;
}
if (stat.value === die.textContent) {
if (matchIndex[die.textContent] === i) {
continue;
} else {
matchIndex[die.textContent] = i;
die.classList.add("selected");
findCount += 1;
}
}
}
}
const selectedRolls = document.querySelectorAll(".selected");
let duplicateSet = {};
if (selectedRolls.length && selectedRolls.length > 0) {
selectedRolls.forEach(selected => {
let selectCount = 0;
statInputs.forEach((stat, index) => {
if (selected.textContent === stat.value) {
if (duplicateSet[selected.textContent] === index) {
} else {
selectCount += 1;
duplicateSet[selected.textContent] = index;
}
}
});
if (selectCount === 0) {
selected.classList.remove("selected");
}
});
}
}
function handleChange(event) {
const statValue = event.target.value;
setStat(statValue);
formatSelectedRolls();
statechange(event);
}
useEffect(() => {
const total = Number(stat) + Number(bonus);
const mod = ModifierCalculator.calculateModifier(total);
setModifier(mod);
setTotal(total);
}, [stat, bonus]);
return (
<tr className="stat-table_row">
<th>{attribute}</th>
<td>
<label className="attribute-value">
<input
type="number"
className="stat-value"
name={attribute}
onChange={handleChange}
defaultValue="0"
></input>
</label>
</td>
<td>
<label className="bonus-value">{bonus}</label>
</td>
<td>
<label className="total-value">{total}</label>
</td>
<td>
<label className="modifier-value">{modifier}</label>
</td>
</tr>
);
};
// Character stat form
function StatForm(props) {
const [statRolls, setStatRolls] = useState([]);
const [bonusArray, setBonusArray] = useState([]);
const attributes = [
{ attribute: "strength", bonus: bonusArray[0] },
{ attribute: "dexterity", bonus: bonusArray[1] },
{ attribute: "constitution", bonus: bonusArray[2] },
{ attribute: "intelligence", bonus: bonusArray[3] },
{ attribute: "wisdom", bonus: bonusArray[4] },
{ attribute: "charisma", bonus: bonusArray[5] }
];
useEffect(() => {
async function getRolls() {
const statRolls = [];
for (let i = 0; i < attributes.length; i++) {
let roll = await DiceRoll.rollStats();
statRolls.push(roll);
}
setStatRolls(statRolls);
props.race && setBonusArray(props.race);
}
getRolls();
}, [props.race]);
return (
<div className="heading">
<h1 className="stat-form_title">Assign Your Stat Rolls</h1>
<div className="statform-wrapper">
<DiceRow diceRollArray={statRolls} />
<form className="statform">
<table className="stat-table">
<thead>
<tr>
{tableHeaders.map((i, index) => (
<th key={index}>{i}</th>
))}
</tr>
</thead>
<tbody>
{attributes.map((item, index) => {
return (
<StatRow
key={index}
attribute={item.attribute}
bonus={item.bonus}
diceRollArray={statRolls}
statechange={props.onchange}
/>
);
})}
</tbody>
</table>
</form>
<div className="learn-button_wrapper">
<a
className="stat-form_learn-button"
href={
"https://www.dndbeyond.com/sources/basic-rules/using-ability-scores"
}
target="_blank"
>
Learn More
</a>
</div>
<div className="button-wrapper">
<button className="generic_button" onClick={props.onclick} value="5">
Back
</button>
<button className="generic_button" onClick={props.onclick} value="7">
Next
</button>
</div>
</div>
</div>
);
}
const tableHeaders = ["Attribute", "Value", "Bonus", "Total", "Modifier"];
export default StatForm;
<file_sep>import ModifierCalculator from './modifier-calculator';
describe('ModifierCalculator', () => {
describe('calculateModifier', () => {
test('Should return negative 2 when given 6', () => {
// Arrange
let testVal = 6;
//Act
let modifier = ModifierCalculator.calculateModifier(testVal);
//Assert
expect(modifier).toEqual(-2);
})
})
})<file_sep>import React, { useState, useEffect } from "react";
function UserForm(props) {
return (
<div className="main_userform">
<form className="userForm">
<h1 className="userform_title">Sign Up!</h1>
<label className="userform_form_card">
<h3>
Enter your character name:
<input
type="text"
onChange={props.onchange}
name="username"
input
size="60"
/>
</h3>
<br></br>
<h3>
Enter your email:
<input
type="text"
onChange={props.onchange}
name="email"
input
size="60"
/>
</h3>
<br></br>
<section className="userform_subscribe">
{/* <h3>
Subscribe to future newsletters?{" "}
<input
type="checkbox"
onChange={props.onchange}
name="subscribe"
className="subscribe_checkbox"
/>
</h3> */}
</section>
<button
className="userform_button"
type="submit"
value="3"
name="back"
onClick={props.onclick}
>
Continue
</button>
</label>
</form>
</div>
);
}
export default UserForm;
<file_sep>import React, { useState, useEffect } from "react";
import "../styles/alignment.css";
function Alignment(props) {
const [alignmentState, setAlignmentState] = useState();
return (
<div className="alignment_wrapper">
<h1 className="alignment_title">Choose Your Character's Alignment</h1>
<div className="alignment_options">
<button className="alignment" id="lg" onClick={props.onclick} value="6">
Lawful Good
</button>
<button className="alignment" id="ln" onClick={props.onclick} value="6">
Lawful Neutral
</button>
<button className="alignment" id="le" onClick={props.onclick} value="6">
Lawful Evil
</button>
<button className="alignment" id="cg" onClick={props.onclick} value="6">
Chaotic Good
</button>
<button className="alignment" id="cn" onClick={props.onclick} value="6">
Chaotic Neutral
</button>
<button className="alignment" id="ce" onClick={props.onclick} value="6">
Choatic Evil
</button>
<button className="alignment" id="ng" onClick={props.onclick} value="6">
Neutral Good
</button>
<button className="alignment" id="tn" onClick={props.onclick} value="6">
True Neutral
</button>
<button className="alignment" id="ne" onClick={props.onclick} value="6">
Neutral Evil
</button>
</div>
<div className="learn-more">
<br></br>
<br></br>
<a
className="learn-more_button"
href={
"https://www.dndbeyond.com/sources/basic-rules/personality-and-background#Alignment"
}
target="_blank"
>
{" "}
Learn More
</a>
</div>
<button
className="alignment_back-button"
onClick={props.onclick}
value="4"
>
Go Back
</button>
</div>
);
}
export default Alignment;
|
e8bd8a1a36a455cfa1e0eecb234ccdf7761d4c24
|
[
"JavaScript",
"Markdown"
] | 10
|
JavaScript
|
Jalil1103/dnd-character-sheet-frontend
|
035dd4dc017733c5bc32b6be7c995f3eba3fb06c
|
907d277990869b89fbebe940652246186dd9d2b2
|
refs/heads/master
|
<file_sep>#!/usr/bin/python
import bayes
from urllib import unquote_plus
import MySQLdb as mdb
import sys
storage = bayes.Storage("pg_test.dat", 10)
try:
storage.load()
except IOError:
pass # don't fail if bayes.dat doesn't exist, it will be created
bayes = bayes.Bayes(storage)
con = None
con = mdb.connect('localhost', 'root', '<PASSWORD>', 'jobs');
with con:
cur = con.cursor(mdb.cursors.DictCursor)
cur.execute("SELECT a.article_id, like_flag, article_text \
from test_user_activity a, test_article b \
where a.article_id = b.article_id \
and a.like_flag is not null \
order by a.article_id")
rows = cur.fetchall()
total = 0
for row in rows:
t = row["article_text"]
t = unquote_plus(t)
if row["like_flag"] == 1:
bayes.train(t, False)
else:
bayes.train(t, True)
total = total + 1
print total
if (total % 100) == 0:
query = "SELECT a.article_id, a.prediction, a.like_flag, b.article_text from test_user_activity a, \
test_article b where a.article_id = b.article_id and a.article_id between %s and %s and user_name ='brad'" % (row["article_id"] + 1, (row["article_id"] + 101))
print query
cur.execute(query)
rows = cur.fetchall()
for row in rows:
t = row["article_text"]
t = unquote_plus(t)
prediction = bayes.classify(t)
rating = bayes.article_rating(t)
print "Pred: %s, Prob: %.4f" % (prediction, rating)
print "Prediction for: %d is %s, naive predicted %s and I chose %s. CRM probability was %.4f" % (row["article_id"], prediction, row["prediction"], row["like_flag"], rating)
#query = """INSERT into test_predictions (article_id, user_name, like_flag, naive_bayes, crm, crm_prob) VALUES (%s, '%s', %s, '%s', '%s', %s)""" % (row["article_id"], "brad", row["like_flag"], row["prediction"], prediction, probability)
query = """UPDATE test_predictions set pg_bayes = '%s', pg_dislike_score = %.4f where user_name = 'brad' and article_id = '%s'""" % (prediction, rating, row["article_id"])
print query
cur.execute(query)
#spam_message = "Viagra, cialis for $2.59!!! Call 555-54-53"
#bayes.train(spam_message, True)
#
#ham_message = "<NAME> doesn't need Viagra. He is NP-hard."
#bayes.train(ham_message, False)
#
#m1 = "Cheap viagra for 2.59"
#print bayes.classify(m1) # => True
#print bayes.article_rating(m1) # => 0.97
#
#m2 = "I don't use viagra (yet)"
#print bayes.classify(m2) # => False
#print bayes.article_rating(m2) # => 0.16
storage.finish()<file_sep><?php
session_start();
$sesh_id = session_id();
include('/Dropbox/Coding/ShopSimply/db_connect.php');
mysql_select_db('jobs');
$suggestion = $_POST['suggestion_box'];
$suggestion = urlencode($suggestion);
$sql = "INSERT into test_user_suggest (user_name, suggestion_text, session_id, suggestion_time_stamp) VALUES ('$username', '$suggestion', '$sesh_id', now())";
if (!mysql_query($sql))
{
die('error: ' . mysql_error());
}
?><file_sep>smarterdigest
=============
Predictive RSS - available at smarterdigest.com
This project uses bayesian classification to predict which articles I'll like based on the articles I've read and tagged in the past.
I use the open source text extraction tool Goose (https://github.com/jiminoc/goose) to get the article text for my classification engine.
I use the open source RSS library Simplepie (http://simplepie.org/) to process the RSS feed.
The primary classification engine is a modified version of (https://github.com/dhotson/classifier-php), which I modified to allow the classifications to persist between sessions.
I've added a second classification engine that is a modified version of (https://github.com/dchest/pybayesantispam) to connect to my database and save the predictions.
Finally, I've added a third classification engine, a python interface to CRM114 (http://crm114.sourceforge.net/ and http://www.elegantchaos.com/node/129).
I used project for over a month, classifying over 1000 articles and capturing the predictions for each. The engine worked pretty well for articles it thought I would dislike, with the primary classification being 85% accurate. The likes were less accurate - around 60%. The engine learns pretty quickly - I ranked 30 articles before predictions started kicking in, and the accuracy quickly reached 85%/60% and then plateaued.
However, when I used all three methods, I was able to get the accuracy up to ~93% for the dislikes and ~73% for the likes.
I plan on integrating a popover walkthrough like intro.js soon, but haven't yet. On the site, you can rank articles, star articles, and clicking on the title shows the plain text of the article. Once you've classified 20 articles, reload the page and predictions should kick in.
Right now I'm working on converting the frontend to Meteor.js for more rapid development, and then I'd like to add some sort of latent semantic indexing/analysis to try and improve the predictions even further. I'm also looking to add the ability to have multiple RSS feeds.
<file_sep>#!/usr/bin/php5
<?php
include_once('/Dropbox/Coding/ShopSimply/simplepie/autoloader.php');
include_once('/Dropbox/Coding/ShopSimply/simplepie/idn/idna_convert.class.php');
include('/Dropbox/Coding/ShopSimply/db_connect.php');
$feed = new SimplePie();
/*
if (isset($_GET['js']))
{
SimplePie_Misc::output_javascript();
die();
}
// Make sure that page is getting passed a URL
if (isset($_GET['feed']) && $_GET['feed'] !== '')
{
// Strip slashes if magic quotes is enabled (which automatically escapes certain characters)
if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
$_GET['feed'] = stripslashes($_GET['feed']);
}
// Use the URL that was passed to the page in SimplePie
$feed->set_feed_url($_GET['feed']);
}
// Allow us to choose to not re-order the items by date. (optional)
if (!empty($_GET['orderbydate']) && $_GET['orderbydate'] == 'false')
{
$feed->enable_order_by_date(false);
}
// Trigger force-feed
if (!empty($_GET['force']) && $_GET['force'] == 'true')
{
$feed->force_feed(true);
}
*/
// Initialize the whole SimplePie object. Read the feed, process it, parse it, cache it, and
// all that other good stuff. The feed's information will not be available to SimplePie before
// this is called.
$feed->set_feed_url('http://news.ycombinator.com/rss');
//$feed->force_feed(true);
$success = $feed->init();
// We'll make sure that the right content type and character encoding gets set automatically.
// This function will grab the proper character encoding, as well as set the content type to text/html.
$feed->handle_content_type();
$i = 0;
if ($success)
{
$link = $feed->get_link();
$title = $feed->get_title();
$descrip = $feed->get_description();
foreach($feed->get_items() as $item)
{
mysql_select_db('jobs');
$permalink = $item->get_permalink();
$item_title = $item->get_title();
$item_title = str_replace("'", "", $item_title);
$item_rss_link = $item->get_content();
//$item_rss_link = "Testing";
$item_rss_link = urlencode($item_rss_link);
$sql = "INSERT into HN_RSS (source, item_title, item_url, item_rss_url, item_time_stamp) VALUES ('$title', '$item_title', '$permalink', '$item_rss_link', now())";
//echo "$sql";
$i = $i + 1;
if (!mysql_query($sql))
{
$error = mysql_error();
$log = '/logs/php_errors.log';
$fh = fopen($log, 'a');
fwrite($fh, $error);
fclose($fh);
}
//$result = mysql_query($sql);
}
echo "SQL successful\n";
}
else
{
echo "Feed Load not successful";
}
echo "<html>";
echo "<body>";
echo "<p>";
echo "$i Records inserted into Jobs.HN_RSS\n";
echo "</p>";
echo "</body>";
echo "</html>";
?>
<file_sep><?php
include('/Dropbox/Coding/ShopSimply/db_connect.php');
$testing = '$username';
?>
<file_sep><?php
$start_time = date('Y-m-d H:i:s');
include('/Dropbox/Coding/ShopSimply/db_connect.php');
require_once '/Dropbox/Coding/classifier-php/bayes.php';
mysql_select_db('jobs');
$sql = "SELECT max(article_id) as last_inserted from test_user_activity where user_name = '$username'";
$result = mysql_query($sql);
$last_inserted = 0;
while($row = mysql_fetch_array($result))
{
$last_inserted = $last_inserted + $row["last_inserted"];
}
$sql = "INSERT into test_user_activity (article_id, user_name, like_flag, prediction, star_flag, share_flag, ignore_flag, action_time_stamp) SELECT id, '$username', NULL, NULL, NULL, NULL, NULL, now() from test_unique where id > $last_inserted";
$exec = mysql_query($sql);
$sql = "SELECT case when last_like = last_action then 1 when num_no_prediction > 0 then 1 else 0 end as engine_check from
(select max(action_time_stamp) as last_like from test_user_activity where user_name = '$username' and like_flag is not null) a,
(select max(action_time_stamp) as last_action from test_user_activity where user_name = '$username') b,
(select count(article_id) as num_no_prediction from test_user_activity where prediction is null and like_flag is null and user_name = '$username') c";
$result = mysql_query($sql);
$engine_check = 0;
while($row = mysql_fetch_array($result))
{
$engine_check =$engine_check + $row["engine_check"];
}
if ($engine_check <> 0)
{
$sql = "SELECT count(like_flag) as num_like from test_user_activity
where user_name = '$username' and like_flag is not null";
$result = mysql_query($sql);
$num_like = 0;
while($row = mysql_fetch_array($result))
{
$num_like = $num_like + $row['num_like'];
}
if ($num_like >= 20)
{
//classifier text goes here
$classifier = new Bayes('like','dislike');
$sql = "SELECT a.article_id, a.article_text from test_article a, test_user_activity b where a.article_id = b.article_id and b.like_flag = 1 and user_name = '$username'";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$article_text = urldecode($row["article_text"]);
$classifier->train('like', $article_text);
}
$sql = "SELECT a.article_id, a.article_text from test_article a, test_user_activity b where a.article_id = b.article_id and b.like_flag = 0 and user_name = '$username'";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$article_text = urldecode($row["article_text"]);
$classifier->train('dislike', $article_text);
}
$sql = "SELECT d.article_id, d.article_text from
(SELECT a.article_id, a.article_text from test_article a, test_user b where a.article_id >= b.starting_id and b.user_name = '$username') d
left join (select article_id, sum(ignore_flag) as num_ignore, sum(like_flag) as num_like, count(prediction) as num_predict from test_user_activity where user_name = '$username' group by 1) b
on b.article_id = d.article_id
where num_ignore is null
and num_like is null";
$result = mysql_query($sql);
$num_classified = 0;
while ($row = mysql_fetch_array($result))
{
$article_text = urldecode($row["article_text"]);
//echo $classifier->classify($article_text) . PHP_EOL;
$prediction = $classifier->classify($article_text);
//echo $prediction . PHP_EOL;
//$sql = "UPDATE test_unique SET prediction = '$prediction' where id = '$row[article_id]'";
//$sql = "INSERT INTO test_user_activity (article_id, user_name, like_flag, prediction, star_flag, share_flag, ignore_flag, action_time_stamp) VALUES ('$row[article_id]', '$username', NULL, '$prediction', NULL, NULL, NULL, now())";
$sql = "UPDATE test_user_activity SET prediction = '$prediction', action_time_stamp = now() where article_id = '$row[article_id]' and user_name = '$username'";
//echo $sql . PHP_EOL;
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
$num_classified = $num_classified + 1;
}
$end_time = date('Y-m-d H:i:s');
$sql = "INSERT into test_user_classify_logs (user_name, start_time_stamp, end_time_stamp, num_classified) VALUES ('$username','$start_time', '$end_time', '$num_classified')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
}
else
{
$end_time = date('Y-m-d H:i:s');
$sql = "INSERT into test_user_classify_logs (user_name, start_time_stamp, end_time_stamp, num_classified) VALUES ('$username','$start_time', '$end_time', '$num_classified')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
}
}
else
{
$end_time = date('Y-m-d H:i:s');
$sql = "INSERT into test_user_classify_logs (user_name, start_time_stamp, end_time_stamp, num_classified) VALUES ('$username','$start_time', '$end_time', '0')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
}
?><file_sep>#!/usr/bin/python
from crm import Classifier
from urllib import unquote_plus
import MySQLdb as mdb
import sys
c = Classifier("/Dropbox/Coding/smarterdigest/engine/data", ["like", "dislike"])
con = None
con = mdb.connect('localhost', 'root', '<PASSWORD>', 'jobs');
with con:
cur = con.cursor(mdb.cursors.DictCursor)
cur.execute("SELECT a.article_id, like_flag, article_text \
from test_user_activity a, test_article b \
where a.article_id = b.article_id \
and a.like_flag is not null \
order by a.article_id")
rows = cur.fetchall()
total = 0
for row in rows:
t = row["article_text"]
t = unquote_plus(t)
if row["like_flag"] == 1:
c.learn("like", t)
else:
c.learn("dislike", t)
total = total + 1
print total
if (total % 100) == 0:
query = "SELECT a.article_id, a.prediction, a.like_flag, b.article_text from test_user_activity a, \
test_article b where a.article_id = b.article_id and a.article_id between %s and %s and user_name ='brad'" % (row["article_id"] + 1, (row["article_id"] + 101))
print query
cur.execute(query)
rows = cur.fetchall()
for row in rows:
t = row["article_text"]
t = unquote_plus(t)
(prediction, probability) = c.classify(t)
print "Pred: %s, Prob: %.4f" % (prediction, probability)
print "Prediction for: %d is %s, naive predicted %s and I chose %s. CRM probability was %.4f" % (row["article_id"], prediction, row["prediction"], row["like_flag"], probability)
query = """INSERT into test_predictions (article_id, user_name, like_flag, naive_bayes, crm, crm_prob) VALUES (%s, '%s', %s, '%s', '%s', %s)""" % (row["article_id"], "brad", row["like_flag"], row["prediction"], prediction, probability)
print query
cur.execute(query)
<file_sep><?php
include('/Dropbox/Coding/ShopSimply/db_connect.php');
mysql_select_db('jobs');
$username = $_POST['login_user_name'];
$pwd = $_POST['login_password'];
session_start();
$sesh_id = session_id();
$_SESSION['username'] = $username;
$_SESSION['pwd'] = $pwd;
$sql = "INSERT into test_user_access (user_name, access_type, access_time_stamp, session_id) values ('$username', 'Login Attempt', now(), '$sesh_id')";
$exec = mysql_query($sql);
$redirecturl = "http://smarterdigest.com/users/$username/index.php";
header("Location: ".$redirecturl);
?>
<file_sep>#!/bin/ksh
cd /Dropbox/Coding/smarterdigest/engine/users/
list=`ls *.php`
for script in $list
do
php $script &
done
exit
<file_sep>#!/usr/bin/python
from crm import Classifier
from urllib import unquote_plus
import MySQLdb as mdb
import sys
c = Classifier("/Dropbox/Coding/smarterdigest/engine/data", ["like", "dislike"])
con = None
con = mdb.connect('localhost', 'root', '<PASSWORD>', 'jobs');
with con:
cur = con.cursor(mdb.cursors.DictCursor)
cur.execute("SELECT a.article_id, like_flag, article_text \
from test_user_activity a, test_article b \
where a.article_id = b.article_id \
and a.like_flag is not null \
order by a.article_id \
limit 100")
rows = cur.fetchall()
for row in rows:
t = row["article_text"]
t = unquote_plus(t)
if row["like_flag"] == 1:
c.learn("like", t)
else:
c.learn("dislike", t)
cur.execute("SELECT a.article_id, a.prediction, a.like_flag, b.article_text from test_user_activity a, \
test_article b where a.article_id = b.article_id and a.article_id between 1334 and 1434 and user_name ='brad'")
rows = cur.fetchall()
like_like = 0
like_dislike = 0
dislike_like = 0
dislike_dislike = 0
nblike_like = 0
nblike_dislike = 0
nbdislike_like = 0
nbdislike_dislike = 0
total = 0
for row in rows:
t = row["article_text"]
t = unquote_plus(t)
(prediction, probability) = c.classify(t)
print "Pred: %s, Prob: %.4f" % (prediction, probability)
print "Prediction for: %s is %s, naive predicted %s and I chose %s. CRM probability was %.4f" % (row["article_id"], prediction, row["prediction"], row["like_flag"], probability)
if prediction == "like" and row["like_flag"] == 1:
like_like = like_like + 1
elif prediction == "like" and row["like_flag"] == 0:
like_dislike = like_dislike + 1
elif prediction == "dislike" and row["like_flag"] == 1:
dislike_like = dislike_like + 1
else:
dislike_dislike = dislike_dislike + 1
if row["prediction"] == "like" and row["like_flag"] == 1:
nblike_like = nblike_like + 1
elif row["prediction"] == "like" and row["like_flag"] == 0:
nblike_dislike = nblike_dislike + 1
elif row["prediction"] == "dislike" and row["like_flag"] == 1:
nbdislike_like = nbdislike_like + 1
else:
nbdislike_dislike = nbdislike_dislike + 1
total = total + 1
crm_total = ((like_like + dislike_dislike) / total)
crm_like = (like_like / (like_like + like_dislike))
crm_dislike = (dislike_dislike / (dislike_like + dislike_dislike))
nb_total = ((nblike_like + nbdislike_dislike) / total)
nb_like = (nblike_like / (nblike_like + nblike_dislike))
nb_dislike = (nbdislike_dislike / (nbdislike_like + nbdislike_dislike))
print "CRM Accuracy was: %.4f" % crm_total
print "CRM Like Accuracy was: %.4f" % crm_like
print "CRM Dislike Accuracy was: %.4f" % crm_dislike
print "NB Accuracy was: %.4f" % nb_total
print "NB Like Accuracy was: %.4f" % nb_like
print "NB Dislike Accuracy was: %.4f" % nb_dislike
<file_sep><?php
echo '<p>Feature coming soon!</p>' . PHP_EOL;
?><file_sep><?php
$sesh_id = session_id();
$sql = "INSERT into test_user_access (user_name, access_type, access_time_stamp, session_id) VALUES ('$username', 'logout', now(), '$sesh_id')";
$exec = mysql_query($sql);
session_regenerate_id(FALSE);
session_unset();
$redirectURL = "http://smarterdigest.com/";
header("Location: ".$redirectURL);
?><file_sep><?php
//This is a script to check a link for links related to jobs, careers, opportunities
?><file_sep><?php
include('/Dropbox/Coding/ShopSimply/db_connect.php');
mysql_select_db('jobs');
$username = $_POST['create_user_name'];
$pwd = $_POST['create_password'];
$email = $_POST['create_email'];
$sql = "SELECT max(id) as starting_id from test_unique";
$result = mysql_query($sql);
$starting_id = -29;
while($row = mysql_fetch_array($result))
{
$starting_id = $starting_id + $row['starting_id'];
}
$sql = "SELECT count(id) as existing from test_user where user_name ='$username'";
$result = mysql_query($sql);
$existing = 0;
session_start();
$_SESSION['username'] = $username;
$_SESSION['pwd'] = <PASSWORD>;
$sesh_id = session_id();
while($row = mysql_fetch_array($result))
{
$existing = $existing + $row['existing'];
}
if ($existing == 0)
{
$sql = "INSERT into test_user (user_email, user_name, starting_id) values ('$email', '$username', '$starting_id')";
$exec = mysql_query($sql);
$sql = "INSERT into test_user_access (user_name, access_type, access_time_stamp, session_id) values ('$username', 'create_acct', now(), '$sesh_id')";
$exec = mysql_query($sql);
$sql = "INSERT into test_user_activity (article_id, user_name, like_flag, prediction, star_flag, share_flag, ignore_flag, action_time_stamp) SELECT id, '$username', NULL, NULL, NULL, NULL, NULL, now() from test_unique where id >= $starting_id";
$exec = mysql_query($sql);
$file = '/Dropbox/Coding/smarterdigest/create_acct.sh';
$fh = fopen($file, 'w') or die("cannot open create_acct.sh");
$text = '#!/bin/ksh
username="'.$username.'"
password="'.$pwd.'"
mkdir /Dropbox/Coding/smarterdigest/users/$username
cp /Dropbox/Coding/smarterdigest/default/index.php /Dropbox/Coding/smarterdigest/users/$username/index_1.php
cp /Dropbox/Coding/smarterdigest/default/stars_test.php /Dropbox/Coding/smarterdigest/users/$username/stars_test_1.php
cp /Dropbox/Coding/smarterdigest/default/top_bar.php /Dropbox/Coding/smarterdigest/users/$username/top_bar_1.php
cp /Dropbox/Coding/smarterdigest/default/votes_test.php /Dropbox/Coding/smarterdigest/users/$username/votes_test_1.php
cp /Dropbox/Coding/smarterdigest/default/share_test.php /Dropbox/Coding/smarterdigest/users/$username/share_test_1.php
cp /Dropbox/Coding/smarterdigest/default/submit_suggestion.php /Dropbox/Coding/smarterdigest/users/$username/submit_suggestion_1.php
cp /Dropbox/Coding/smarterdigest/default/acct_mgmt.php /Dropbox/Coding/smarterdigest/users/$username/acct_mgmt_1.php
cp /Dropbox/Coding/smarterdigest/default/last_thirty.php /Dropbox/Coding/smarterdigest/users/$username/last_thirty_1.php
cp /Dropbox/Coding/smarterdigest/default/logout.php /Dropbox/Coding/smarterdigest/users/$username/logout_1.php
cp /Dropbox/Coding/smarterdigest/default/queue.php /Dropbox/Coding/smarterdigest/users/$username/queue_1.php
cp /Dropbox/Coding/smarterdigest/default/show_starred.php /Dropbox/Coding/smarterdigest/users/$username/show_starred_1.php
cp /Dropbox/Coding/smarterdigest/default/top_bar_thirty.php /Dropbox/Coding/smarterdigest/users/$username/top_bar_thirty_1.php
cp /Dropbox/Coding/smarterdigest/default/get_predictions.php /Dropbox/Coding/smarterdigest/users/$username/'.$username.'_predictions_1.php
cd /Dropbox/Coding/smarterdigest/users/$username
cp index_1.php index_2.php
sed -e \'s/$username/'.$username.'/g\' index_2.php > index_1.php
sed -e \'s/$password/'.$pwd.'/g\' index_1.php > index.php
sed -e \'s/$username/'.$username.'/g\' stars_test_1.php > stars_test.php
sed -e \'s/$username/'.$username.'/g\' top_bar_1.php > top_bar.php
sed -e \'s/$username/'.$username.'/g\' votes_test_1.php > votes_test.php
sed -e \'s/$username/'.$username.'/g\' share_test_1.php > share_test.php
sed -e \'s/$username/'.$username.'/g\' submit_suggestion_1.php > submit_suggestion.php
sed -e \'s/$username/'.$username.'/g\' acct_mgmt_1.php > acct_mgmt.php
sed -e \'s/$username/'.$username.'/g\' last_thirty_1.php > last_thirty.php
sed -e \'s/$username/'.$username.'/g\' logout_1.php > logout.php
sed -e \'s/$username/'.$username.'/g\' queue_1.php > queue.php
sed -e \'s/$username/'.$username.'/g\' show_starred_1.php > show_starred.php
sed -e \'s/$username/'.$username.'/g\' top_bar_thirty_1.php > top_bar_thirty.php
sed -e \'s/$username/'.$username.'/g\' '.$username.'_predictions_1.php > '.$username.'_predictions.php
mv '.$username.'_predictions.php /Dropbox/Coding/smarterdigest/engine/users/
rm *_1.php
rm *_2.php
chmod a+rwx -R /Dropbox/Coding/smarterdigest/users/$username/.' . PHP_EOL;
fwrite($fh, $text);
fclose($fh);
$command = "/Dropbox/Coding/smarterdigest/./create_acct.sh";
$create_user = system($command);
$redirectURL = "http://smarterdigest.com/users/$username/";
header("Location: ".$redirectURL);
}
else
{
echo '<h3>Warning: That username is already taken. Please choose a different username and try again</h3>' . PHP_EOL;
include('index.php');
}
?>
<file_sep><?php
include('/Dropbox/Coding/ShopSimply/db_connect.php');
mysql_select_db("jobs");
foreach ($_POST as $key => $value)
{
//$sql = "INSERT INTO test_user_activity (article_id, user_name, like_flag, prediction, star_flag, share_flag, ignore_flag, action_time_stamp) values ($key, '$username', $value, NULL, NULL, NULL, NULL, now())";
$sql = "UPDATE test_user_activity set like_flag = $value, action_time_stamp = now() where article_id = $key and user_name = '$username'";
$result = mysql_query($sql);
}
?>
<file_sep>
if (Meteor.isServer) {
Feeds = new Meteor.Collection("Feeds");
Articles = new Meteor.Collection("Articles");
Meteor.publish('Feeds', function () {
return Feeds.find();
});
Meteor.publish('Articles', function () {
return Articles.find();
});
}
if (Meteor.isClient) {
Session.setDefault("current-feed", "Hacker News");
Session.set("current-feed", "Hacker News");
Feeds = new Meteor.Collection("Feeds");
Articles = new Meteor.Collection("Articles");
Template.sidebar.feed = function() {
return Feeds.find({}, {sort: {feed_name: 1}});
};
Template.feed.current_feed = function() {
console.log(Session.get("current-feed"));
return Session.get("current-feed");
};
Template.feed.feed_articles = function() {
return Articles.find({}, {sort: {article_id: -1}});
};
/*
Template.hello.events({
'click input' : function () {
// template data, if any, is available in 'this'
if (typeof console !== 'undefined')
console.log("You pressed the button");
}
});
*/
}
<file_sep>#!/usr/bin/python
"""
$Id: crm.py 158 2005-06-07 17:45:47Z sam $
Python wrapper classes for the CRM114 Discriminator (http://crm114.sourceforge.net/).
Requires the crm command to be installed and in your command path.
The latest version of this file can be obtained from the Elegant Chaos subversion server (user=guest, pass=guest) at:
$URL: http://source.elegantchaos.com/projects/com/elegantchaos/libraries/python/crm.py $
This module provides a very simplified interface to crm114. It does not attempt to expose all of crm114's power, instead it
tries to hide almost all of the gory details.
To use the module, create an instance of the Classifier class, giving it a path (where to store the data files), and a list
of category strings (these are the "labels" to classify the text with).
e.g:
c = Classifier("/path/to/my/data", ["good", "bad"])
To teach the classifier object about some text, call the learn method passing in a category (on of the ones that you provided originally),
and the text.
e.g:
c.learn("good", "some good text")
c.learn("bad", "some bad text")
To find out what the classifier things about some text, call the classify method passing in the text. The result of this
method is a pair - the first item being the category best matching the text, and the second item being the probability of the match.
e.g:
(classification, probability) = c.classify("some text")
TODO: use proper path separator variable in the regular expression instead of assuming that it's a slash
"""
__version__ = "1.0.0a1"
__license__ = """
Copyright (C) 2005 <NAME>.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
"""
import os;
import string;
#constants
kCrmPath = "crm"
kClassificationType = "<osb unique microgroom>"
kClassificationExtension = ".css"
kLearnCommand = " '-{ learn %s ( %s ) }'"
kClassifyCommand = " '-{ isolate (:stats:); classify %s ( %s ) (:stats:); match [:stats:] (:: :best: :prob:) /Best match to file .. \(%s\/([[:graph:]]+)\\%s\) prob: ([0-9.]+)/; output /:*:best:\\t:*:prob:/ }'"
# wrapper for crm114
class Classifier:
def __init__( self, path, categories = [] ):
self.categories = categories
self.path = path
self.makeFiles()
# learn the classifier what category some new text is in
def learn( self, category, text ):
command = kCrmPath + ( kLearnCommand % ( kClassificationType, os.path.join( self.path, category + kClassificationExtension ) ) )
pipe = os.popen( command, 'w' )
pipe.write( text )
pipe.close()
# ask the classifier what category best matches some text
def classify( self, text ):
path = string.replace(self.path, "/", "\\/") # need to escape path separator for the regexp matching
command = kCrmPath + ( kClassifyCommand % (kClassificationType, self.getFileListString(), path, kClassificationExtension) )
(fin, fout) = os.popen2( command )
fin.write( text )
fin.close()
list = string.split(fout.readline())
fout.close()
if list == None:
return ("", 0.0)
else:
category = list[0]
probability = float(list[1])
return (category, probability)
# ensure that data files exist, by calling learn with an empty string
def makeFiles( self ):
# make directory if necessary
if not os.path.exists( self.path ):
os.mkdir( self.path )
# make category files
for category in self.categories:
self.learn( category, "" )
# return a list of classification files
def getFileList( self ):
# internal method to build a file path given a category
def getFilePath( file ):
return os.path.join( self.path, file + kClassificationExtension )
# return list of all category paths
return map( getFilePath, self.categories )
# return a list of classification files as a string
def getFileListString( self ):
return string.join( self.getFileList(), " " )
# perform some self tests
def test( self ):
print self.getFileList()
self.learn( "good", "this is a test" )
self.learn( "bad", "this is very bad" )
print "class was: %s, prob was:%f" % ( self.classify( "this is a test" ) )
if __name__ == "__main__":
# perform a simple test
c = Classifier( "test/data", [ "good", "bad" ] )
c.test()<file_sep><?php
include('/Dropbox/Coding/ShopSimply/db_connect.php');
mysql_select_db("jobs");
$sql = "SELECT star_flag, count(distinct article_id) as num_starred from test_user_activity where user_name = '$username' and star_flag = 1";
$result = mysql_query($sql);
$num_starred = 0;
while($row = mysql_fetch_array($result))
{
$num_starred = $num_starred + $row["num_starred"];
}
if ($num_starred > 0)
{
//and num_ignore is null and num_like is null
$sql = "SELECT distinct d.id, d.item_title, d.item_url, b.prediction, b.num_ignore, b.num_like from
(select distinct a.id, a.item_title, a.item_url from test_unique a, test_user c
where c.user_name = '$username'
and a.id > (c.starting_id - 30)) d, (select article_id, prediction, sum(ignore_flag) as num_ignore, sum(like_flag) as num_like, sum(star_flag) as num_star from test_user_activity where user_name = '$username' group by 1) b
where b.article_id = d.id
and num_star > 0
order by d.id asc";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
if ($row["prediction"] == "like")
{
echo '<div class="element_like" id="'.$row["id"].'">' . PHP_EOL;
}
elseif (is_null($row["prediction"]))
{
echo '<div class="element" id="'.$row["id"].'">' . PHP_EOL;
}
else
{
echo '<div class="element_dislike" id="'.$row["id"].'">' . PHP_EOL;
}
echo '<div class="element_container">' . PHP_EOL;
echo '<div class="icons">' . PHP_EOL;
echo '</br>'.PHP_EOL;
echo '<div class="rating"><i id="'.$row["id"].'_star" class="icon-star-empty" onclick="star_article(this.id)"></i></div>' . PHP_EOL;
echo '</br>'.PHP_EOL;
echo '<div class="share"><i id="'.$row["id"].'_share" class="icon-share"></i></div>' . PHP_EOL;
echo '</div>' . PHP_EOL;
echo '<div class="element_header">' . PHP_EOL;
echo '<p id="'.$row["id"].'_t" onclick="show_text(this.id)">'.$row["item_title"].'</p>' . PHP_EOL;
echo '<p><a id="'.$row["id"].'_u" href="'.$row["item_url"].'">'.$row["item_url"].'</a></p>' . PHP_EOL;
echo '</div>' . PHP_EOL;
echo '<div class="element_vote">' . PHP_EOL;
if ($row["prediction"] == "like")
{
echo '<p id="'.$row["id"].'_like" class="vote_p" onclick="cast_vote(this.id,1)">Worth It</p>' . PHP_EOL;
echo '<p id="'.$row["id"].'_dislike" class="vote" onclick="cast_vote(this.id,0)">Not Worth It</p>' . PHP_EOL;
}
elseif (is_null($row["prediction"]))
{
echo '<p id="'.$row["id"].'_like" class="vote" onclick="cast_vote(this.id,1)">Worth It</p>' . PHP_EOL;
echo '<p id="'.$row["id"].'_dislike" class="vote" onclick="cast_vote(this.id,0)">Not Worth It</p>' . PHP_EOL;
}
else
{
echo '<p id="'.$row["id"].'_like" class="vote" onclick="cast_vote(this.id,1)">Worth It</p>' . PHP_EOL;
echo '<p id="'.$row["id"].'_dislike" class="vote_p" onclick="cast_vote(this.id,0)">Not Worth It</p>' . PHP_EOL;
}
echo '</div>' . PHP_EOL;
echo '</div>' . PHP_EOL;
echo '<div class="element_text" id="'.$row["id"].'_b"></div>' . PHP_EOL;
echo '</div>' . PHP_EOL;
}
}
else
{
echo '<p>No starred articles yet</p>' . PHP_EOL;
}
?><file_sep>#!/usr/bin/php5
<?php
include('/Dropbox/Coding/ShopSimply/db_connect.php');
include_once('/Dropbox/Coding/ShopSimply/simplepie/autoloader.php');
include_once('/Dropbox/Coding/ShopSimply/simplepie/idn/idna_convert.class.php');
require_once '/Dropbox/Coding/classifier-php/bayes.php';
mysql_select_db('jobs');
$feed = new SimplePie();
$feed->set_feed_url('http://news.ycombinator.com/rss');
$success = $feed->init();
$feed->handle_content_type();
$i = 0;
if ($success)
{
$link = $feed->get_link();
$title = $feed->get_title();
$descrip = $feed->get_description();
foreach($feed->get_items() as $item)
{
mysql_select_db('jobs');
$permalink = $item->get_permalink();
$item_title = $item->get_title();
$item_title = str_replace("'", "", $item_title);
$item_rss_link = $item->get_content();
//$item_rss_link = "Testing";
$item_rss_link = urlencode($item_rss_link);
$sql = "INSERT into test_rss (source, item_title, item_url, item_rss_url, item_time_stamp) VALUES ('$title', '$item_title', '$permalink', '$item_rss_link', now())";
//echo "$sql";
$i = $i + 1;
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
//$result = mysql_query($sql);
}
echo "SQL successful\n";
}
else
{
echo "Feed Load not successful";
}
$sql = "INSERT into test_day (item_title, item_url, item_rss_url, feed_date)
select distinct min(a.item_title), a.item_url, min(a.item_rss_url), left(item_time_stamp,10) as feed_date from test_rss a,
(select item_url, sum(processed) as num_occur from test_rss group by 1) b
where a.item_url = b.item_url
and b.num_occur = 0
and a.processed = 0
group by 2, 4";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
//$result = mysql_query($sql);
$sql = "INSERT into test_unique (item_url, item_title, item_rss_url, entry_date)
select distinct min(a.item_url), a.item_title, min(a.item_rss_url), min(left(item_time_stamp,10)) as entry_date from test_rss a,
(select item_url, sum(processed) as num_occur from test_rss group by 1) b
where a.item_url = b.item_url
and b.num_occur = 0
and a.processed = 0
group by 2";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
$sql = "UPDATE test_rss set processed = 1 where processed = 0";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
$get_articles = "/Dropbox/Coding/goose/get_articles.sh";
$fh = fopen($get_articles, 'w') or die("cannot open get_articles.sh");
$sql = 'SELECT distinct id, item_url from test_unique where processed = 0 order by id asc';
$result = mysql_query($sql);
$shebang = "#!/bin/ksh\n";
fwrite($fh, $shebang);
//$shebang = "cd ../goose/";
//fwrite($fh, $shebang);
while($row = mysql_fetch_array($result))
{
$retrieve_article = 'MAVEN_OPTS="-Xms256m -Xmx2000m"; ./mvn exec:java -Dexec.mainClass=com.gravity.goose.TalkToMeGoose -Dexec.args="'.$row["item_url"].'" -e -q > /Dropbox/Coding/goose/article_test/'.$row["id"].'.txt'."\n";
fwrite($fh, $retrieve_article);
$text = 'echo "Article ' . $row["id"] . 'added"' . PHP_EOL;
fwrite($fh, $text);
}
fclose($fh);
$command = 'cd /Dropbox/Coding/goose/; ./get_articles.sh;';
$fetch_articles = system($command);
$sql = "DELETE from test_stats";
$exec = mysql_query($sql);
$sql = "SELECT distinct a.item_title, a.item_url, c.id, a.num_hours, b.num_days from
(select item_title, item_url, item_rss_url, count(id) as num_hours from test_rss group by 1, 2, 3) a, (select distinct id, item_url from test_unique) c,
(select item_url, count(distinct feed_date) as num_days from test_day group by 1) b
where a.item_url = b.item_url
and a.item_url = c.item_url";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$title = str_replace("'", "", $row["item_title"]);
$title_components = explode(" ", $title);
$title_text = "";
foreach($title_components as $value)
{
$title_text = $title_text . "T-" . $value . " ";
}
$url_components = explode(".",$row["item_url"]);
if (count($url_components) == 2)
{
$extra = explode("/",$url_components[1]);
$extra_text = "";
foreach($extra as $value)
{
$extra_text = $extra_text . " DE-" . $value;
}
$extra_text = $extra_text . " ";
$sql = "INSERT into test_stats (article_id, item_title, num_hours, num_days, domain_name, domain_locale) VALUES ('$row[id]', '$title_text', '$row[num_hours]', '$row[num_days]', '$url_components[0]', '$extra_text')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
}
else
{
$extra = explode("/",$url_components[2]);
$extra_text = "";
foreach($extra as $value)
{
$extra_text = $extra_text . " DE-" . $value;
}
$extra_text = $extra_text . " ";
$sql = "INSERT into test_stats (article_id, item_title, num_hours, num_days, domain_name, domain_locale) VALUES ('$row[id]', '$title_text', '$row[num_hours]', '$row[num_days]', '$url_components[0] . $url_components[1]', '$extra_text')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
}
}
$sql = "SELECT a.article_id, a.item_title, a.num_hours, a.num_days, a.domain_name, a.domain_locale from test_stats a, test_unique b where a.article_id = b.id and b.processed = 0";
$article_text = "";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
//"hours-".$row["num_hours"]." days-".$row["num_days"]." ".
$header = $row["domain_name"].$row["domain_locale"].$row["item_title"];
$header = urlencode($header);
$article_text = file_get_contents('/Dropbox/Coding/goose/article_test/'.$row["article_id"].'.txt');
$article_text = urlencode($article_text);
$sql = "INSERT into test_article (article_id, article_text) VALUES ('$row[article_id]', '$header+$article_text')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
}
$cmd = '/Dropbox/Coding/smarterdigest/engine/./run_predictions.sh &';
$get_predictions = system($cmd);
$sql = "UPDATE test_unique set processed = 1 where processed = 0";
$exec = mysql_query($sql);
?>
<file_sep><?php
include('/Dropbox/Coding/ShopSimply/db_connect.php');
mysql_select_db('jobs');
//and num_ignore is null and num_like is null
$sql = "SELECT distinct b.prediction, count(d.id) as num_in_queue from
(select distinct a.id, a.item_title, a.item_url from test_unique a, test_user c
where c.user_name = '$username'
and a.id > (c.starting_id - 30)) d, (select article_id, prediction, sum(ignore_flag) as num_ignore, sum(like_flag) as num_like from test_user_activity where user_name = '$username' group by 1 order by id desc limit 30) b
where b.article_id = d.id
group by 1
order by 1";
$result = mysql_query($sql);
$num_in_queue = 0;
$num_dislike = 0;
$num_like = 0;
while($row = mysql_fetch_array($result))
{
$num_in_queue = $num_in_queue + $row["num_in_queue"];
if ($row["prediction"] == "dislike")
{
$num_dislike = $num_dislike + $row["num_in_queue"];
}
elseif ($row["prediction"] == "like")
{
$num_like = $num_like + $row["num_in_queue"];
}
}
$sql = "SELECT prediction, like_flag, count(like_flag) as num_articles from test_user_activity where user_name = '$username' and like_flag is not null and prediction is not null group by 1,2 order by 1,2";
$result = mysql_query($sql);
$dislike_dislike = 0;
$dislike_like = 0;
$like_dislike = 0;
$like_like = 0;
$total_liked = 0;
$i = 1;
while($row = mysql_fetch_array($result))
{
if ($row["prediction"] == "dislike" && $row["like_flag"] == 0)
{
$dislike_dislike = $row["num_articles"];
}
elseif ($row["prediction"] == "dislike" && $row["like_flag"] == 1)
{
$dislike_like = $row["num_articles"];
}
elseif ($row["prediction"] == "like" && $row["like_flag"] == 0)
{
$like_dislike = $row["num_articles"];
}
elseif ($row["prediction"] == "like" && $row["like_flag"] == 1)
{
$like_like = $row["num_articles"];
}
$total_liked = $total_liked + $row["num_articles"];
$i = $i + 1;
}
if ($total_liked > 0)
{
$total_accuracy = ($dislike_dislike + $like_like) / $total_liked;
$dislike_accuracy = ($dislike_dislike) / ($dislike_dislike + $dislike_like);
$like_accuracy = ($like_like) / ($like_dislike + $like_like);
$like = $like_like + $dislike_like;
$dislike = $dislike_dislike + $like_dislike;
}
else
{
$total_accuracy = 0;
$dislike_accuracy = 0;
$like_accuracy = 0;
}
$sql = "SELECT star_flag, count(distinct article_id) as num_starred from test_user_activity where user_name = '$username' and star_flag = 1";
$result = mysql_query($sql);
$num_starred = 0;
while($row = mysql_fetch_array($result))
{
$num_starred = $num_starred + $row["num_starred"];
}
echo '<div id="cssmenu">'. PHP_EOL;
echo '<ul>' . PHP_EOL;
echo ' <li><a href="#"><span>Welcome, $username</span></a></li>' . PHP_EOL;
echo ' <li class="has-sub"><a href="#"><span>Articles in Queue: '.$num_in_queue.'</span></a>' . PHP_EOL;
echo ' <ul>' . PHP_EOL;
echo ' <li><a href="#"><span onclick="show_likes()"># Worth it: '.$num_like.'</span></a></li>' . PHP_EOL;
echo ' <li class="last"><a href="#"><span onclick="show_dislikes()"># Not worth it: '.$num_dislike.'</span></a></li>' . PHP_EOL;
echo ' </ul>' . PHP_EOL;
echo ' </li>' . PHP_EOL;
echo ' <li class="has-sub"><a href="#"><span>Stats</span></a>' . PHP_EOL;
echo ' <ul>' . PHP_EOL;
echo ' <li><a href="#"><span>Overall Prediction Accuracy: '.round($total_accuracy,2).'%</span></a></li>' . PHP_EOL;
echo ' <li><a href="#"><span>Worth it Accuracy: '.round($like_accuracy,2).'%</span></a></li>' . PHP_EOL;
echo ' <li><a href="#"><span>Not Worth it Accuracy: '.round($dislike_accuracy,2).'%</span></a></li>' . PHP_EOL;
echo ' <li><a href="#"><span>Articles Read: '.$total_liked.'</span></a></li>' . PHP_EOL;
echo ' <li><a href="#"><span>Articles Liked: '.$like.'</span></a></li>' . PHP_EOL;
echo ' <li><a href="#"><span>Articles Disliked: '.$dislike.'</span></a></li>' . PHP_EOL;
echo ' <li class="last"><a href="#"><span onclick="show_starred()">Articles Starred: '.$num_starred.'</span></a></li>' . PHP_EOL;
echo ' </ul>' . PHP_EOL;
echo ' </li>' . PHP_EOL;
echo ' <li class="has-sub"><a href="#"><span>Options</span></a>' . PHP_EOL;
echo ' <ul>' . PHP_EOL;
echo ' <li><a href="#"><span id="hide_dislike" onclick="hide_dislikes()">Only show "Worth it" articles</span></a></li>' . PHP_EOL;
echo ' <li><a href="#"><span onclick="last_thirty()">Only show 30 most recent articles</span></a></li>' . PHP_EOL;
echo ' <li><a href="#"><span onclick="reload_site()">Update feed</span></a></li>' . PHP_EOL;
echo ' <li><a href="#"><span>Load current view of HN</span></a></li>' . PHP_EOL;
echo ' <li onclick="show_suggestion()" class="last"><a href="#"><span>Submit suggestion or bug</span></a></li>' . PHP_EOL;
echo ' </ul>' . PHP_EOL;
echo ' </li>' . PHP_EOL;
echo ' <li onclick="load_acct_mgmt()"><a href="#"><span>Acct Mgmt</span></a></li>' . PHP_EOL;
echo ' <li class="last"><a href="../../index.php"><span onclick="logout();">Logout</span></a></li>' . PHP_EOL;
echo '</ul>' . PHP_EOL;
echo '</div>' . PHP_EOL;
?>
<file_sep>#!/bin/ksh
username="brad3"
password=""
mkdir /Dropbox/Coding/smarterdigest/users/$username
cp /Dropbox/Coding/smarterdigest/default/index.php /Dropbox/Coding/smarterdigest/users/$username/index_1.php
cp /Dropbox/Coding/smarterdigest/default/stars_test.php /Dropbox/Coding/smarterdigest/users/$username/stars_test_1.php
cp /Dropbox/Coding/smarterdigest/default/top_bar.php /Dropbox/Coding/smarterdigest/users/$username/top_bar_1.php
cp /Dropbox/Coding/smarterdigest/default/votes_test.php /Dropbox/Coding/smarterdigest/users/$username/votes_test_1.php
cp /Dropbox/Coding/smarterdigest/default/share_test.php /Dropbox/Coding/smarterdigest/users/$username/share_test_1.php
cp /Dropbox/Coding/smarterdigest/default/submit_suggestion.php /Dropbox/Coding/smarterdigest/users/$username/submit_suggestion_1.php
cp /Dropbox/Coding/smarterdigest/default/acct_mgmt.php /Dropbox/Coding/smarterdigest/users/$username/acct_mgmt_1.php
cp /Dropbox/Coding/smarterdigest/default/last_thirty.php /Dropbox/Coding/smarterdigest/users/$username/last_thirty_1.php
cp /Dropbox/Coding/smarterdigest/default/logout.php /Dropbox/Coding/smarterdigest/users/$username/logout_1.php
cp /Dropbox/Coding/smarterdigest/default/queue.php /Dropbox/Coding/smarterdigest/users/$username/queue_1.php
cp /Dropbox/Coding/smarterdigest/default/show_starred.php /Dropbox/Coding/smarterdigest/users/$username/show_starred_1.php
cp /Dropbox/Coding/smarterdigest/default/top_bar_thirty.php /Dropbox/Coding/smarterdigest/users/$username/top_bar_thirty_1.php
cp /Dropbox/Coding/smarterdigest/default/get_predictions.php /Dropbox/Coding/smarterdigest/users/$username/brad3_predictions_1.php
cd /Dropbox/Coding/smarterdigest/users/$username
cp index_1.php index_2.php
sed -e 's/$username/brad3/g' index_2.php > index_1.php
sed -e 's/$password//g' index_1.php > index.php
sed -e 's/$username/brad3/g' stars_test_1.php > stars_test.php
sed -e 's/$username/brad3/g' top_bar_1.php > top_bar.php
sed -e 's/$username/brad3/g' votes_test_1.php > votes_test.php
sed -e 's/$username/brad3/g' share_test_1.php > share_test.php
sed -e 's/$username/brad3/g' submit_suggestion_1.php > submit_suggestion.php
sed -e 's/$username/brad3/g' acct_mgmt_1.php > acct_mgmt.php
sed -e 's/$username/brad3/g' last_thirty_1.php > last_thirty.php
sed -e 's/$username/brad3/g' logout_1.php > logout.php
sed -e 's/$username/brad3/g' queue_1.php > queue.php
sed -e 's/$username/brad3/g' show_starred_1.php > show_starred.php
sed -e 's/$username/brad3/g' top_bar_thirty_1.php > top_bar_thirty.php
sed -e 's/$username/brad3/g' brad3_predictions_1.php > brad3_predictions.php
mv brad3_predictions.php /Dropbox/Coding/smarterdigest/engine/users/
rm *_1.php
rm *_2.php
chmod a+rwx -R /Dropbox/Coding/smarterdigest/users/$username/.
|
5aac6f818f7dd057374d7e84a070b46c94ed36a0
|
[
"Markdown",
"JavaScript",
"Python",
"PHP",
"Shell"
] | 21
|
Python
|
bradjlarson/smarterdigest
|
861eaf3e42d7c44c6fe6c78172fb13bb1141a825
|
41743d5590dae2442cd2d8e3d50b6f4e7d2ab328
|
refs/heads/master
|
<file_sep>import {action, createStandardAction, createAction} from 'typesafe-actions'
export const updateCategoryState = createAction('UPDATE_CATEGORY_STATE_FIRBASE', resolve => {
return (snapshot: firebase.firestore.QuerySnapshot) => resolve(snapshot)
})
<file_sep>import Category from '../data/category'
export default class State {
categories: Category[] = []
keywordsCount: number = 0
clone(): State {
return Object.assign({}, this)
}
}
<file_sep>import * as firebase from 'firebase'
const config = {
apiKey: '<KEY>',
authDomain: 'my-keyworks.firebaseapp.com',
databaseURL: 'https://my-keyworks.firebaseio.com',
projectId: 'my-keyworks',
storageBucket: 'my-keyworks.appspot.com',
messagingSenderId: '666429890624'
}
firebase.initializeApp(config)
firebase.firestore().enablePersistence()
export default firebase
<file_sep>export default class LocalStorageUtil {
static readonly firebaseAuthKey = 'FIREBASE_AUTH_SUCCESS'
static readonly firebaseAuthUID = 'FIREBASE_AUTH_UID'
}
<file_sep>import {ActionType, getType} from 'typesafe-actions'
import * as actions from './action'
import State from './state'
import Category, {Keyword} from '../data/category'
export type Action = ActionType<typeof actions>
export default function reducer(state: State = new State(), action: Action) {
switch (action.type) {
case getType(actions.updateCategoryState):
const categoryList: Category[] = []
action.payload.docs.forEach(item => {
const category = Object.assign(new Category(), item.data())
category.documentId = item.id
category.keywords = category.keywords.map(keyword => Object.assign(new Keyword(), keyword))
console.log(category)
categoryList.push(category)
})
const keywordcount = categoryList.map(item => item.keywords.length).reduce((sum, itm) => sum += itm, 0)
const statec = Object.assign(new State(), state)
statec.keywordsCount = keywordcount
statec.categories = categoryList
return statec
default:
return state
}
}
<file_sep>import firebase from './config'
import * as Redux from 'redux'
import * as AppAction from '../redux/action'
import Category from '../data/category'
function getCurrentUserDocument() {
return firebase.firestore().doc(`/users/${firebase.auth().currentUser!.uid}/`)
}
let unsubscribe: firebase.Unsubscribe
export async function subscribeDatabaseEvents(dispatch: Redux.Dispatch) {
const document = getCurrentUserDocument()
if (unsubscribe) {
unsubscribe()
}
unsubscribe = document.collection('category').onSnapshot(snapshot => {
dispatch(AppAction.updateCategoryState(snapshot))
})
}
export async function addCategory(category: Category) {
const currentUserDocument = getCurrentUserDocument()
await currentUserDocument.collection('category').add(category.firebaseObject())
}
export async function deleteCategory(documentId: string) {
const currentUserDocument = getCurrentUserDocument()
await currentUserDocument.collection('category').doc(documentId).delete()
}
export async function updateCategory(category: Category) {
const currentUserDocument = getCurrentUserDocument()
await currentUserDocument.collection('category').doc(category.documentId).update(category.firebaseObject())
}
<file_sep>import * as uuidv4 from 'uuid/v4'
export class Keyword {
name?: string
id?: string
order = 0
constructor(name?: string) {
this.name = name
this.id = uuidv4()
}
toPureObject() {
return Object.assign({}, this)
}
clone() {
return Object.assign(new Keyword(), this) as Keyword
}
}
export default class Category {
name?: string
color = '#00000'
order = 0
keywords: Keyword[] = []
documentId?: string
clone() {
return Object.assign(new Category(), this) as Category
}
firebaseObject() {
const cloneobj = Object.assign({}, this)
delete cloneobj.documentId
cloneobj.keywords = this.keywords.map(itm => itm.toPureObject())
return cloneobj
}
}
|
924c701c0144ed9e256a27d3fbf6a341a2a202b0
|
[
"TypeScript"
] | 7
|
TypeScript
|
tumugin/my_keywords
|
c4d7104672f02f1031a39fa0e9cf00c8c94a98f9
|
f70c81e1942f21c6daad8b03e4851dcfa04e4264
|
refs/heads/master
|
<repo_name>naveenkumarkg/routine-NodeJs<file_sep>/Source_code/Section_3/app.js
const http = require("http");
const server = http.createServer((req,res)=>{
// console.log(req.url);
// console.log(req.headers);
// console.log(req.method);
res.setHeader('Content-Type','text/html');
res.write('<html>');
res.write('<head><title>My First NodeJs Program</title></head>');
res.write('<body><input type="text"><button type="submit" method="POST" action="/message">Save</button></body>');
res.write('</html>');
res.end();
})
server.listen(3000);
//process.exit();
<file_sep>/README.md
# routine-NodeJs
We will start a routine on Learning a nodeJs for 1 to 2 hrs and discuss during the weekends
|
ea14eba52e87f52d837d3a2d74f8bc3e5617ca52
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
naveenkumarkg/routine-NodeJs
|
4dd807831fc49139cdeae51a346e705299747d66
|
460aff885228e27da156ad6029f7b56de1d61eb3
|
refs/heads/master
|
<repo_name>ricardoborrull/ExamenSQLite<file_sep>/app/src/main/java/com/example/ricardo/proyectosqlite/AsignaturaAdapter.java
package com.example.ricardo.proyectosqlite;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by 2dam on 22/01/2018.
*/
public class AsignaturaAdapter extends CursorAdapter {
public AsignaturaAdapter(Context context, Cursor c) {
super(context, c);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// The newView method is used to inflate a new view and return it,
// you don't bind any data to the view at this point.
return LayoutInflater.from(context).inflate(R.layout.asignatura, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Obtenemos los views
TextView nombre = (TextView) view.findViewById(R.id.nombre);
TextView horas = (TextView) view.findViewById(R.id.horas);
// Obtenemos la información del cursor
String sNombre = cursor.getString(cursor.getColumnIndexOrThrow("nombre"));
String sHoras = cursor.getString(cursor.getColumnIndexOrThrow("horas"));
nombre.setText("Nombre: " + sNombre);
horas.setText("Horas: "+ sHoras);
}
}
<file_sep>/app/src/main/java/com/example/ricardo/proyectosqlite/Usuario.java
package com.example.ricardo.proyectosqlite;
/**
* Created by Ricardo on 20/01/2018.
*/
public class Usuario {
private String nombre;
private String edad;
private String ciclo;
private String curso;
private String rol;
//Esto es nota media o despacho.
private String variable;
public Usuario(String nombre, String edad, String ciclo, String curso, String rol, String variable) {
this.nombre = nombre;
this.edad = edad;
this.ciclo = ciclo;
this.curso = curso;
this.rol = rol;
this.variable = variable;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getEdad() {
return edad;
}
public void setEdad(String edad) {
this.edad = edad;
}
public String getCiclo() {
return ciclo;
}
public void setCiclo(String ciclo) {
this.ciclo = ciclo;
}
public String getCurso() {
return curso;
}
public void setCurso(String curso) {
this.curso = curso;
}
public String getRol() {
return rol;
}
public void setRol(String rol) {
this.rol = rol;
}
public String getVariable() {
return variable;
}
public void setVariable(String variable) {
this.variable = variable;
}
}
<file_sep>/app/src/main/java/com/example/ricardo/proyectosqlite/VerAsignatura.java
package com.example.ricardo.proyectosqlite;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Spinner;
public class VerAsignatura extends AppCompatActivity {
private ListView lista;
private MyDBAdapter dbAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ver_asignatura);
lista = (ListView) findViewById(R.id.lista);;
dbAdapter = new MyDBAdapter(this);
dbAdapter.open();
Cursor cursor = dbAdapter.recuperarAsignaturas();
//Crea el adapter de la lista y le mete los datos del cursor
final AsignaturaAdapter Adapter = new AsignaturaAdapter(this, cursor);
lista.setAdapter(Adapter);
getWindow().setNavigationBarColor(getResources().getColor(R.color.colorPrimary));
}
}
<file_sep>/app/src/main/java/com/example/ricardo/proyectosqlite/Menu.java
package com.example.ricardo.proyectosqlite;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.database.Cursor;
public class Menu extends AppCompatActivity {
private Button vertodo, asignatura, prof, alum;
private Cursor cursor;
private MyDBAdapter dbAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
vertodo = (Button) findViewById(R.id.vertodo);
alum = (Button) findViewById(R.id.alum);
prof = (Button) findViewById(R.id.prof);
asignatura = (Button) findViewById(R.id.asignatura);
vertodo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(Menu.this, VerBBDD.class);
i.putExtra("Boton", "Todos");
startActivity(i);
}
});
alum.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(Menu.this, VerBBDD.class);
i.putExtra("Boton", "Alumnos");
startActivity(i);
}
});
prof.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(Menu.this, VerBBDD.class);
i.putExtra("Boton", "Profesores");
startActivity(i);
}
});
asignatura.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(Menu.this, VerAsignatura.class);
startActivity(i);
}
});
}
}
<file_sep>/app/src/main/java/com/example/ricardo/proyectosqlite/NuevoUsuario.java
package com.example.ricardo.proyectosqlite;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class NuevoUsuario extends AppCompatActivity {
private MyDBAdapter dbAdapter;
private EditText nombre, edad, curso, ciclo, variable;
private RadioButton alumno, profesor;
private RadioGroup rol;
private Button ok;
private String opcion, sID, sNom, sEdad, sRol, sCiclo, sCurso, sVar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nuevo_usuario);
dbAdapter = new MyDBAdapter(this);
dbAdapter.open();
getWindow().setNavigationBarColor(getResources().getColor(R.color.colorPrimary));
nombre = (EditText) findViewById(R.id.nombre);
edad = (EditText) findViewById(R.id.edad);
curso = (EditText) findViewById(R.id.curso);
ciclo = (EditText) findViewById(R.id.ciclo);
variable = (EditText) findViewById(R.id.var);
ok = (Button) findViewById(R.id.ok);
rol = (RadioGroup) findViewById(R.id.rol);
alumno = (RadioButton) findViewById(R.id.alumno);
profesor = (RadioButton) findViewById(R.id.profesor);
rol.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.alumno){
opcion = alumno.getText().toString();
sRol = opcion;
}else if (checkedId == R.id.profesor) {
opcion = profesor.getText().toString();
sRol = opcion;
}
}
});
ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sNom = nombre.getText().toString();
sEdad = edad.getText().toString();
sCiclo = ciclo.getText().toString();
sCurso = curso.getText().toString();
sVar = variable.getText().toString();
Usuario u = new Usuario(sNom, sEdad, sCiclo, sCurso, sRol, sVar); // Creamos un nuevo usuario
dbAdapter.nuevoUsuario(u);
Toast.makeText(NuevoUsuario.this, "Usuario creado", Toast.LENGTH_SHORT).show();
finish();
}
});
}
}
<file_sep>/app/src/main/java/com/example/ricardo/proyectosqlite/NuevaAsignatura.java
package com.example.ricardo.proyectosqlite;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class NuevaAsignatura extends AppCompatActivity {
private MyDBAdapter dbAdapter;
private EditText nombre, horas;
private Button ok;
private String sNom, sAsig;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nueva_asignatura);
dbAdapter = new MyDBAdapter(this);
dbAdapter.open();
getWindow().setNavigationBarColor(getResources().getColor(R.color.colorPrimary));
nombre = (EditText) findViewById(R.id.nombre);
horas = (EditText) findViewById(R.id.horas);
ok = (Button) findViewById(R.id.ok);
ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sNom = nombre.getText().toString();
sAsig = horas.getText().toString();
Asignatura a = new Asignatura(sNom, sAsig);
dbAdapter.nuevaAsignatura(a);
Toast.makeText(NuevaAsignatura.this, "Usuario creado", Toast.LENGTH_SHORT).show();
finish();
}
});
}
}
|
3f5c4928119795b8804224d1fa5b4d6009333efc
|
[
"Java"
] | 6
|
Java
|
ricardoborrull/ExamenSQLite
|
3c264b69e1e5f9257d8853faff5c334e4280a93a
|
2a3620099620fb9e9d9473c271adf24859bba9a3
|
refs/heads/master
|
<file_sep><?php
$userId=$id;
$firstName='';
$lastName='';
$email='';
$userName='';
if(isset($this->session->userdata['error'])){
$sessionFlashErr=$this->session->userdata['error'];
}
else{
$sessionFlashErr='';
}
if(isset($this->session->userdata['firstnameerr'])){
$sessionErrfName=$this->session->userdata['firstnameerr'];
}
else{
$sessionErrfName='';
}
if(isset($this->session->userdata['lastnameerr'])){
$sessionErrlName=$this->session->userdata['lastnameerr'];
}
else{
$sessionErrlName='';
}
if(isset($this->session->userdata['emailiderr'])){
$sessionErremail=$this->session->userdata['emailiderr'];
}
else{
$sessionErremail='';
}
if(isset($users))
{
if(count($users)>0)
{
$userName=$users->firstname." ".$users->lastname;
$firstName=$users->firstname;
$lastName=$users->lastname;
$email=$users->email;
}
}
if(isset($this->session->userdata['fname']))
{
$firstName=$this->session->userdata['fname'];
}
if(isset($this->session->userdata['lname']))
{
$lastName=$this->session->userdata['lname'];
}
if(isset($this->session->userdata['email']))
{
$email=$this->session->userdata['email'];
}
if(isset($this->session->userdata['username']))
{
$userName=$this->session->userdata['username'];
}
?>
<form class="form-horizontal" style="'min-width:500px;max-width:800px;margin: 0 auto" name="form" method="post" action="<?php echo site_url().'/ourpattern/postUser'; ?>">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 id="myModalLabel">
<?php
if($userId!='')
{
echo $userName;
}
else
{
echo 'Add User';
}
?>
</h4>
</div>
<div class="modal-body">
<?php
if($sessionFlashErr!='')
{
?>
<div class="row-fluid">
<div class="offset3 span6 alert alert-error">
<h4>Oops....</h4>
<?php echo $sessionFlashErr; ?>
</div>
</div>
<?php
}
?>
<?php ?>
<input type="hidden" name="userid" value="<?php echo $id; ?>"/>
<input type="hidden" name="userName" value="<?php echo $userName; ?>"/>
<div class="control-group">
<label class="control-label"><a href="#" rel="tooltip" title="Some help message for schema name"><i class="icon-info-sign"></i></a>First Name</label>
<div class="controls">
<input id="entityTable" type="text" name="firstname" value="<?php echo $firstName; ?>" class="input-xlarge">
<span class="help-block" style="color:#FF0000;"><?php echo $sessionErrfName; ?></span>
</div>
</div>
<div class="control-group ${field.errorClass}">
<label class="control-label"><a href="#" rel="tooltip" title="Some help message for schema name"><i class="icon-info-sign"></i></a>Last Name</label>
<div class="controls">
<input id="entityTable" type="text" name="lastname" value="<?php echo $lastName; ?>" class="input-xlarge">
<span class="help-block" style="color:#FF0000;"><?php echo $sessionErrlName; ?></span>
</div>
</div>
<div class="control-group ${field.errorClass}">
<label class="control-label"><a href="#" rel="tooltip" title="Some help message for schema name"><i class="icon-info-sign"></i></a>Email</label>
<div class="controls">
<input id="entityTable" type="text" name="email" value="<?php echo $email; ?>" class="input-xlarge">
<span class="help-block" style="color:#FF0000;"><?php echo $sessionErremail; ?></span>
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" name="submit" value="Save" class="btn btn-primary" />
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
</form>
<?php
$this->session->unset_userdata('error');
$this->session->unset_userdata('firstnameerr');
$this->session->unset_userdata('lastnameerr');
$this->session->unset_userdata('emailiderr');
$this->session->unset_userdata('fname');
$this->session->unset_userdata('lname');
$this->session->unset_userdata('email');
$this->session->unset_userdata('userName');
?><file_sep><form class="form-horizontal" style="'min-width:500px;max-width:800px;margin: 0 auto" method="post" action="<?php echo site_url().'/ourpattern/postDelete'; ?>">
<div id="myDeletePattern" class="modal hide" data-backdrop="true" tabindex="-1" role="dialog" data-backdrop="false" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 id="myModalLabel"><?php echo $users->firstname." ".$users->lastname; ?></h4>
</div>
<input type="hidden" name="userid" value="<?php echo $id; ?>"/>
<div id="deletePattern_content" class="modal-body">
<p>
Are you sure you want to delete "<?php echo $users->email; ?>" ?
</p>
</div>
<div class="modal-footer">
<input type="submit" name="delete" value="delete" class="btn btn-primary" />
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
</div>
</form><file_sep><?php
define('DB_SERVER','usmahwebas11.maquetcv.com');
define('DB_USERNAME','isar_proxy'); //database username isar
define('DB_PASSWORD','<PASSWORD>');//database password isar
define('DB_USERNAME1','ad_proxy'); //database username ad_users
define('DB_PASSWORD1','<PASSWORD>');//database password <PASSWORD>
define('DB_DATABASE','isar');
define('DB_DATABASE1','ad_users');
$link=mysql_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD);
mysql_select_db(DB_DATABASE,$link);
$link1=mysql_connect(DB_SERVER,DB_USERNAME1,DB_PASSWORD1);
mysql_select_db(DB_DATABASE1,$link1);
?><file_sep><div id="content">
<div class="container">
<div class="content rt">
<h4><?php echo $title; ?></h4>
<?php $showPopupSession='';
if(isset($this->session->userdata['showPopup']))
{
$showPopupSession=$this->session->userdata['showPopup'];
}
?>
<div id="addEditPatternModal" class="modal hide <?php if($showPopupSession=='true') { ?>in<?php } ?>" tabindex="-1" role="dialog" data-backdrop="true" aria-labelledby="addEditModalLabel" aria-hidden="<?php if($showPopupSession=='true') { ?>false<?php } else { ?>true<?php } ?>" <?php if($showPopupSession=='true') { ?>style="display: block;"<?php } ?> >
<?php
if($showPopupSession=='true')
{
$data["id"]=$this->session->userdata['userId'];
$data["users"]=array();
?>
<?php $this->load->view('OurPattern/ajaxAddEdit',$data); ?>
<script type="text/javascript">
$(document).ready(function() {
$("#addEditPatternModal").modal('show');
});
</script>
<?php
$this->session->unset_userdata('showPopup');
}
?>
</div>
<div id="deletePatternModal"></div>
<table class="table">
<thead>
<tr>
<th>FirstName</th>
<th>LastName</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
if(count($users)>0)
{
foreach($users as $user)
{
?>
<tr>
<td><?php echo $user->firstname; ?></td>
<td><?php echo $user->lastname; ?></td>
<td><?php echo $user->email; ?></td>
<td>
<a href="#" data-toggle="modal" class="btn" id="editLink_<?php echo $user->id ?>">Edit</a>
<script type="text/javascript">
$(document).ready(function() {
var getAddEditPattern= '<?php echo site_url().'/ourpattern/ajaxAddEdit/'.$user->id; ?>';
$("#editLink_<?php echo $user->id ?>").click(function(e){
$('#addEditPatternModal').load(getAddEditPattern,function(){
$("#addEditPatternModal").modal('show');
});
});
});
</script>
<a href="#" data-toggle="modal" class="btn" id="deletePattern_<?php echo $user->id ?>">Delete</a>
<script type="text/javascript">
$(document).ready(function() {
var getDeletePattern= '<?php echo site_url().'/ourpattern/ajaxDelete/'.$user->id; ?>';
$("#deletePattern_<?php echo $user->id; ?>").click(function(e){
$('#deletePatternModal').load(getDeletePattern,function(){
$("#myDeletePattern").modal('show');
});
});
});
</script>
</td>
</tr>
<?php
}
}
else
{
?>
<tr>
<td colspan="4">
There are no users, Add one now please.
</td>
</tr>
<?php
}
?>
</tbody>
</table>
<a href="javaScript:void(0);" class="btn btn-primary" id="addLink">Add User</a>
<p style="clear: both;">
<script type="text/javascript">
$(document).ready(function() {
var getAddEditPattern= '<?php echo site_url().'/ourpattern/ajaxAddEdit/'; ?>';
$("#addLink").click(function(e){
$('#addEditPatternModal').load(getAddEditPattern,function(){
$("#addEditPatternModal").modal('show');
});
});
});
</script>
</p>
</div>
</div>
</div>
<?php
$this->session->unset_userdata('error');
$this->session->unset_userdata('firstnameerr');
$this->session->unset_userdata('lastnameerr');
$this->session->unset_userdata('emailiderr');
$this->session->unset_userdata('fname');
$this->session->unset_userdata('lname');
$this->session->unset_userdata('email');
$this->session->unset_userdata('userName');
?><file_sep><?php
class Ourpattern extends Controller {
public function __construct()
{
parent::Controller();
$this->load->helper('cookie');
$this->load->helper('url');
$this->load->model('Ourpattern_model','',TRUE);
}
public function index()
{
$data['title']='Users';
$data['view']='OurPattern/listUsers';
$data['users']=$this->Ourpattern_model->getUsers();
$this->load->view('userTemplate',$data);
}
public function ajaxDelete($id)
{
$data['id']=$id;
$data['users']=$this->Ourpattern_model->getUsersOne($id);
$this->load->view('OurPattern/ajaxDelete',$data);
}
public function ajaxAddEdit($id='')
{
$data['id']=$id;
if($id!='')
{
$data['users']=$this->Ourpattern_model->getUsersOne($id);
}
$this->load->view('OurPattern/ajaxAddEdit',$data);
}
public function postDelete()
{
$id=$this->input->post('userid');
$data['users']=$this->Ourpattern_model->deleteUser($id);
$sessionSuccess = array('successMessage' => 'Successfully deleted a user.',);
$this->session->set_userdata($sessionSuccess);
redirect('ourpattern');
}
public function postUser()
{
$id=$this->input->post('userid');
$userName=$this->input->post('userName');
$fName=$this->input->post('firstname');
$lName=$this->input->post('lastname');
$email=$this->input->post('email');
$flgErr=0;
if ($fName == '')
{
$sessionfnameErr = array('firstnameerr' => 'Please enter First Name.',);
$this->session->set_userdata($sessionfnameErr);
$flgErr=1;
}
if ($lName == '')
{
$sessionlanmeErr = array('lastnameerr' => 'Please enter Last Name.',);
$this->session->set_userdata($sessionlanmeErr);
$flgErr=1;
}
if ($email == '')
{
$sessionemailErr = array('emailiderr' => 'Please enter Email.',);
$this->session->set_userdata($sessionemailErr);
$flgErr=1;
}
else
{
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if (!preg_match($regex, $email))
{
$sessionemailErr = array('emailiderr' => 'Please enter Valid Email.',);
$this->session->set_userdata($sessionemailErr);
$flgErr=1;
}
$emailExistsCount=$this->Ourpattern_model->emailExistsAlready($email,$id);
if ($emailExistsCount>0)
{
$sessionemailErr = array('emailiderr' => 'Email Already Exists.',);
$this->session->set_userdata($sessionemailErr);
$flgErr=1;
}
}
if($flgErr==1)
{
$sessionUserId = array('userId' => $id,);
$this->session->set_userdata($sessionUserId);
$sessionUserName = array('userName' => $userName,);
$this->session->set_userdata($sessionUserName);
$sessionArray = array('fname' => $fName,);
$this->session->set_userdata($sessionArray);
$sessionlname = array('lname' => $lName,);
$this->session->set_userdata($sessionlname);
$sessionemail = array('email' => $email,);
$this->session->set_userdata($sessionemail);
$sessionErr = array('error' => 'Your form has errors.',);
$this->session->set_userdata($sessionErr);
$sessionPopup = array('showPopup' => 'true',);
$this->session->set_userdata($sessionPopup);
}
else
{
$dataAdd=array(
'firstname'=>$fName,
'lastname'=>$lName,
'email'=>$email
);
if($id=='')
{
$this->Ourpattern_model->insertUser($dataAdd);
$sessionSuccess = array('successMessage' => 'Successfully Added a user.',);
}
else
{
$this->Ourpattern_model->updateUser($dataAdd,$id);
$sessionSuccess = array('successMessage' => 'Successfully Updated a user.',);
}
$this->session->set_userdata($sessionSuccess);
}
redirect('ourpattern');
}
}<file_sep>codeignitercrud
===============
This is the example for the codeigniter CRUD project so we have a good example of how to do CRUD in codeigniter(really list, add/edit, and delete)
<file_sep><?php
include('ajxConfig.php');
$data = '';
$rec_start = $_POST['rec_start'];
$sql1 = "SELECT * FROM userprofile where EmpSeqKey!=0";
if($_POST['division']!='')
$sql1.=" AND `Div` = '".$_POST['division']."'";
if($_POST['department']!='')
$sql1.=" AND `Dept` = '".$_POST['department']."'";
if($_POST['facility']!='')
$sql1.=" AND `Loc` = '".$_POST['facility']."'";
if($_POST['adId']!='')
$sql1.=" AND `ADName` = '".$_POST['adId']."'";
if($_POST['hManager']!='')
$sql1.=" AND `Sup` = '".$_POST['hManager']."'";
if($_POST['stat']!='')
{
$status=explode(",",$_POST["stat"]);
$sql1.=" AND (";
for($s=0; $s<count($status)-1; $s++)
{
if($s==0)
$sql1.=" `Estatus` = '".$status[$s]."' ";
else
$sql1.=" OR `Estatus` = '".$status[$s]."' ";
}
$sql1.=")";
}
if($_POST['type']!='')
{
$type=explode(",",$_POST["type"]);
$sql1.=" AND (";
for($t=0; $t<count($type)-1; $t++)
{
if($t==0)
$sql1.=" `Jtype` = '".$type[$t]."' ";
else
$sql1.=" OR `Jtype` = '".$type[$t]."' ";
}
$sql1.=")";
}
if($_POST['sDate']!='' && $_POST['eDate']!='')
$sql1.=" AND (`Hdate` BETWEEN '" . $_POST['sDate'] . "' and '" . $_POST['eDate'] . "')";
if($_POST['fName']!='')
$sql1.=" AND `Fname` LIKE '%".$_POST['fName']."%'";
if($_POST['lName']!='')
$sql1.=" AND `Lname` LIKE '%".$_POST['lName']."%'";
$q1 = mysql_query($sql1,$link);
$row_count = mysql_num_rows($q1);
if($_POST['rec_per_page']!='All')
$t_rec_per_page= $_POST['rec_per_page'];
else
$t_rec_per_page= $row_count;
$lstrec = $row_count % $t_rec_per_page;
if ($lstrec == 0)
{
$lstrec = $row_count - 1;
}
else
{
$lstrec = $row_count;
}
if($rec_start >= $row_count)
{
$rec_start=$rec_start - $t_rec_per_page;
if($rec_start < 0)
$rec_start = 0;
}
$rstart = $rec_start + 1;
$rend = $rec_start + $t_rec_per_page;
if ($rend > $row_count)
{
$rend = $row_count;
}
$rtot = $row_count;
$sql2="SELECT * FROM userprofile where EmpSeqKey!=0";
if($_POST['division']!='')
$sql2.=" AND `Div` = '".$_POST['division']."'";
if($_POST['department']!='')
$sql2.=" AND `Dept` = '".$_POST['department']."'";
if($_POST['facility']!='')
$sql2.=" AND `Loc` = '".$_POST['facility']."'";
if($_POST['adId']!='')
$sql2.=" AND `ADName` = '".$_POST['adId']."'";
if($_POST['hManager']!='')
$sql2.=" AND `Sup` = '".$_POST['hManager']."'";
if($_POST['stat']!='')
{
$status=explode(",",$_POST["stat"]);
$sql2.=" AND (";
for($s=0; $s<count($status)-1; $s++)
{
if($s==0)
$sql2.=" `Estatus` = '".$status[$s]."' ";
else
$sql2.=" OR `Estatus` = '".$status[$s]."' ";
}
$sql2.=")";
}
if($_POST['type']!='')
{
$type=explode(",",$_POST["type"]);
$sql2.=" AND (";
for($t=0; $t<count($type)-1; $t++)
{
if($t==0)
$sql2.=" `Jtype` = '".$type[$t]."' ";
else
$sql2.=" OR `Jtype` = '".$type[$t]."' ";
}
$sql2.=")";
}
if($_POST['sDate']!='' && $_POST['eDate']!='')
$sql2.=" AND (`Hdate` BETWEEN '" . $_POST['sDate'] . "' and '" . $_POST['eDate'] . "')";
if($_POST['fName']!='')
$sql2.=" AND `Fname` LIKE '%".$_POST['fName']."%'";
if($_POST['lName']!='')
$sql2.=" AND `Lname` LIKE '%".$_POST['lName']."%'";
if($_POST['rec_per_page']!='All')
$sql2.=" ORDER BY Lname ASC LIMIT " . $rec_start . " , " . $t_rec_per_page;
else
$sql2.=" ORDER BY Lname ASC";
$q2 = mysql_query($sql2,$link);
// data result
if($rtot > 0)
{
$data='<div class="Sarbox">';
$data.='<div class="Searhover" id="userGrid">';
$data.='<div style="width:1300px;">';
$data.='<table width="100%" border="0" cellspacing="0" cellpadding="0" class="ListTable">';
$data.='<tr>'.
'<th width="150px">Last Name</th>'.
'<th width="150px">First Name</th>'.
'<th width="100px">A/D Id</th>'.
'<th width="90px">Request Date</th>'.
'<th width="90px">Division</th>'.
'<th width="90px">Department</th>'.
'<th width="90px">Facility</th>'.
'<th width="100px">Manager</th>'.
'<th width="80px">Status</th>'.
'<th width="80px">Type</th>'.
'<th width="280px">Title</th>'.
'</tr>';
$k=1;
while($row = mysql_fetch_array($q2))
{
$r=$k%2;
$c='';
if($r!=0)
$c='class="oddRow"';
if($_POST['empId']==$row["EmpSeqKey"])
$c='class="list_selected"';
$data.='<tr '.$c.' onclick="onSelRow('.$row["EmpSeqKey"].','.$k.');" id="tr_'.$k.'" >'.
'<td id="td_'.$k.'" class="col_selected">'.$row["Lname"].'</td>'.
'<td>'.$row["Fname"].'</td>'.
'<td>';
if($row["ADName"]!="")
{
$data.=$row["ADName"];
}
else
{
$data.='-';
}
$data.='</td>'.
'<td>';
if($row["Hdate"]!="")
{
$data.=$row["Hdate"];
}
else
{
$data.='-';
}
$data.='</td>'.
'<td>';
if($row["Div"]!="")
{
$data.=$row["Div"];
}
else
{
$data.='-';
}
$data.='</td>'.
'<td>';
if($row["Dept"]!="")
{
$data.=$row["Dept"];
}
else
{
$data.='-';
}
$data.='</td>'.
'<td>';
if($row["Loc"]!="")
{
$data.=$row["Loc"];
}
else
{
$data.='-';
}
$data.='</td>'.
'<td>';
if($row["Sup"]!="")
{
$data.=$row["Sup"];
}
else
{
$data.='-';
}
$data.='</td>'.
'<td>';
if($row["Estatus"]!="")
{
$data.=$row["Estatus"];
}
else
{
$data.='-';
}
$data.='</td>'.
'<td>';
if($row["Jtype"]!="")
{
$data.=$row["Jtype"];
}
else
{
$data.='-';
}
$data.='</td>'.
'<td>';
if($row["Title"]!="")
{
$data.=$row["Title"];
}
else
{
$data.='-';
}
$data.='</td>'.
'</tr>';
$k++;
}
$data.='<input type="hidden" id="rec" name="rec" value="'.$k.'"/></table>';
$data.='</div>';
$data.='</div>';
$data.='</div>';
$data.='<div class="Nextbut">';
$data.='<div class="zoom_but padt5">Record Per Page</div>';
$data.='<div class="left padr10">'.
'<Select class="Selectinpu" style="height:24px;" id="rec_per" name="rec_per" onchange="ajxNoPage();" >'.
'<option value="25" ';
if($_POST['rec_per_page']=='25')
{
$data.='selected="selected" ';
}
$data.='>25</option>'.
'<option value="50" ';
if($_POST['rec_per_page']=='50')
{
$data.='selected="selected" ';
}
$data.='>50</option>'.
'<option value="100" ';
if($_POST['rec_per_page']=='100')
{
$data.='selected="selected" ';
}
$data.='>100</option>'.
'<option value="All" ';
if($_POST['rec_per_page']=='All')
{
$data.='selected="selected" ';
}
$data.='>All</option>'.
'</Select>'.
'</div>';
$data.='<div class="left padr5">';
if($rec_start != 0)
{
$start=0;
$data.='<a href="javascript:void(0);" onclick="ajxSearch('.$start.');"><img src="images/prev-1.jpg" alt="" /></a>';
}
else
{
$data.='<img src="images/prev-1.jpg" alt="" />';
}
$data.='</div>';
$data.='<div class="left padr5">';
if($rec_start != 0)
{
$start=$rec_start - $t_rec_per_page;
$data.='<a href="javascript:void(0);" onclick="ajxSearch('.$start.');"><img src="images/prev.jpg" alt="" /></a>';
}
else
{
$data.='<img src="images/prev.jpg" alt="" />';
}
$data.='<input type="hidden" id="rec_start" name="rec_start" value="'.$rec_start.'"/></div>';
$data.='<div class="left padr5 padt5">Page</div>';
$listpages = 8;
$listhalf = $listpages/2;
$rmndr = $row_count % $t_rec_per_page;
$totpage = (int)($row_count/$t_rec_per_page);
if($rmndr > 0)
{
$totpage = $totpage + 1;
}
$stpage = 1;
$cpage = ($rec_start + $t_rec_per_page) / $t_rec_per_page;
if ($cpage - $listhalf <= 1)
{
$stpage = 1;
}
else
{
if ($cpage + $listhalf > $totpage)
{
$balpage = $totpage - $cpage;
if ($cpage - ($listpages - $balpage) <= 1)
{
$stpage = 1;
}
else
{
$stpage = $cpage - ($listpages - $balpage);
}
}
else
{
$stpage = $cpage - $listhalf;
}
}
$endpage = $stpage + $listpages;
if ($totpage < $endpage)
{
$endpage = $totpage;
}
$page_now = 0;
for($i=$stpage;$i<=$endpage;$i++)
{
if ($rstart == ($i * $t_rec_per_page) - $t_rec_per_page + 1)
{
$page_now = $i;
}
}
$data.='<div class="left padr5"><input type="text" id="pno" name="pno" class="Selectinpu" readonly="true" value="'.$page_now.'"/></div>';
$data.='<div class="left padr5 padt5">off-'.$totpage.'</div>';
$data.='<div class="left padr5">';
if($row_count > $rec_start + $t_rec_per_page)
{
$start=$rec_start + $t_rec_per_page;
$data.='<a href="javascript:void(0);" onclick="ajxSearch('.$start.');"><img src="images/next.jpg" alt="" /></a>';
}
else
{
$data.='<img src="images/next.jpg" alt="" />';
}
$data.='</div>';
$data.='<div class="left padr10">';
if($row_count > $rec_start + $t_rec_per_page)
{
$start=(((int)($lstrec/$t_rec_per_page))*$t_rec_per_page);
$data.='<a href="javascript:void(0);" onclick="ajxSearch('.$start.');"><img src="images/next-1.jpg" alt="" /></a>';
}
else
{
$data.='<img src="images/next-1.jpg" alt="" />';
}
$data.='</div>';
$data.='<div class="left padr10"><a href="index.php"><img src="images/referace.jpg" alt="" /></a></div>';
$data.='<div class="left padt5">Displaying '.$rstart.' to '.$rend.' of '.$rtot.' users</div>';
$data.='</div>';
}
else
{
$data='<div style="width:880px; font-size:12px; color:#999999; padding:10px; float:left;" align="center">No Record Found<input type="hidden" id="rec_per" name="rec_per" value="'.$_POST['rec_per_page'].'"/></div>';
}
echo $data;
?><file_sep><!DOCTYPE html>
<html>
<head>
<title><?php echo $title; ?></title>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Styles -->
<link rel="stylesheet" href="<?php echo base_url() ?>/public/css/bootstrap.css" />
<link rel="stylesheet" href="<?php echo base_url() ?>/public/css/theme.css" type="text/css" />
<link href='http://fonts.googleapis.com/css?family=Lato:300,400,700,900,300italic,400italic,700italic,900italic' rel='stylesheet' type='text/css'>
<script src="<?php echo base_url() ?>/public/javascripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="<?php echo base_url() ?>/public/css/custom.css" />
</head>
<body>
<?php $successSesion='';
if(isset($this->session->userdata['successMessage']))
{
?>
<div class="row-fluid" id="successMsg">
<div class="offset3 span6 alert alert-success">
<?php echo $this->session->userdata['successMessage']; ?>
</div>
</div>
<?php
$this->session->unset_userdata('successMessage');
}
?>
<?php $this->load->view($view); ?>
<script>
window.onload = function(){
setTimeout(function(){
if(document.getElementById("successMsg"))
{
document.getElementById("successMsg").style.display='none';
}
}, 10000);
};
</script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="<?php echo base_url() ?>/public/js/bootstrap.min.js"></script>
<script src="<?php echo base_url() ?>/public/js/theme.js"></script>
</body>
</html><file_sep><?php
class Ourpattern_model extends Model {
public function __construct()
{
parent::Model();
}
public function getUsers()
{
$data = array();
$query = $this->db->get('users');
foreach ($query->result() as $row)
{
$data[] = $row;
}
return $data;
$q->free_result();
}
public function getUsersOne($id)
{
$data = array();
$query = $this->db->get_where('users', array('id' => $id));
foreach ($query->result() as $row)
{
$data = $row;
}
return $data;
$q->free_result();
}
public function deleteUser($id)
{
$this->db->where('id', $id);
$this->db->delete('users');
}
public function insertUser($data)
{
$this->db->insert('users', $data);
}
public function updateUser($data,$id)
{
$this->db->where('id', $id);
$this->db->update('users' ,$data);
}
public function emailExistsAlready($email,$id)
{
if($id=='')
{
$query = $this->db->get_where('users', array('email' => $email));
}
else
{
$this->db->where('email =', $email);
$this->db->where('id !=', $id);
$query = $this->db->get('users');
}
$rowcount = $query->num_rows();
return $rowcount;
}
}
|
6783105721e34ca9c0a5961ac67a5dc45cf859fe
|
[
"Markdown",
"PHP"
] | 9
|
PHP
|
sanacode/codeignitercrud
|
6b74e59ec70b43e9504c9680b9ed08643288737f
|
003e05175c4a93bee44cc276c8b679f57f31ad53
|
refs/heads/master
|
<repo_name>justinmauldin7/json-practice<file_sep>/lib/story.rb
require 'json'
class Story
attr_reader :section, :subsection, :title, :abstract, :link, :published, :photo
def initialize(index)
@story_array = Story.story_parser["results"]
@section = @story_array[index]["section"]
@subsection = @story_array[index]["subsection"]
@title = @story_array[index]["title"]
@abstract = @story_array[index]["abstract"]
@link = @story_array[index]["url"]
@published = @story_array[index]["published_date"]
@photo = normal_photo(index)
end
def self.story_parser
data_file = File.read("./data/nytimes.json")
parsed_story = JSON.parse(data_file)
end
def normal_photo(index)
value = 'No Photo Available'
@story_array[index]["multimedia"].each do |photo|
if photo["format"] == "Normal"
value = photo["url"]
end
end
value
end
end
<file_sep>/test/story_test.rb
require 'minitest/autorun'
require 'minitest/pride'
require 'pry'
require './lib/story'
class StoryTest < Minitest::Test
def test_it_exists
story = Story.new(0)
assert_instance_of Story, story
end
# def test_it_returns_stories
# story = Story.story_parser
#
# assert_equal 43, story.count
# end
def test_it_returns_a_stories_attributes
index = 0
story = Story.new(0)
expected_section = "U.S."
expected_subsection = "Politics"
expected_title = "How a Lawyer, a Felon and a Russian General Chased a Moscow Trump Tower Deal"
expected_abstract = "During the presidential campaign, <NAME> and <NAME>, an associate with a criminal past, pursued a new Trump Tower project with a former spymaster’s help."
expected_link = "https://www.nytimes.com/2018/11/29/us/politics/trump-russia-felix-sater-michael-cohen.html"
expected_published = "2018-11-29T18:46:27-05:00"
expected_photo = "https://static01.nyt.com/images/2018/11/30/world/30trumpmoscow-1-print/30trumpmoscow7-articleInline.jpg"
refuted_photo = "https://static01.nyt.com/images/2018/11/30/world/30trumpmoscow-1-print/30trumpmoscow7-thumbStandard.jpg"
assert_equal expected_section, story.section
assert_equal expected_subsection, story.subsection
assert_equal expected_title, story.title
assert_equal expected_abstract, story.abstract
assert_equal expected_link, story.link
assert_equal expected_published, story.published
assert_equal expected_photo, story.photo
end
end
|
ecaaf7a41909314a0036f0c15105a0244f05284a
|
[
"Ruby"
] | 2
|
Ruby
|
justinmauldin7/json-practice
|
fe55a766060ee8dfb7dcd3a32d77334fe52ff445
|
698a02704783d98c0288566059d2868581a1f643
|
refs/heads/master
|
<repo_name>OsvaldasRimkus/final-java-exam-2<file_sep>/src/main/java/lt/akademija/exam/client/ClientRepository.java
package lt.akademija.exam.client;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.io.IOException;
import java.util.List;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
/**
* @author ggrazevicius
* @author orimkus
*/
@Repository
public class ClientRepository {
private static final Logger LOGGER = Logger.getLogger(ClientRepository.class.getName());
Logger logger = Logger.getLogger("MyLog");
FileHandler fh;
@PersistenceContext
private EntityManager entityManager;
/**
* returns a client entity from DB by ID
* @param id
* @return
*/
@Transactional(readOnly = true)
public Client get(Long id) {
LOGGER.log(Level.INFO, "OR LOGGING: client with id " + id + " info returned to program user");
return entityManager.find(Client.class, id);
}
/**
* saves client to the DB
*
* @param client
* @return
*/
@Transactional
public Client save(Client client) {
// gets all clients
List<Client> clients = entityManager.createNamedQuery("findAllClients").getResultList();
// loops through all clients to search for duplicate
for (Client c : clients) {
System.out.println(c.getFirstName() + " " + client.getFirstName());
System.out.println(c.getLastName() + " " + client.getLastName());
System.out.println(c.getDateOfBirth() + " " + client.getDateOfBirth());
if (c.getFirstName().equals(client.getFirstName()) && c.getLastName().equals(client.getLastName())
&& c.getDateOfBirth().equals(client.getDateOfBirth())) {
LOGGER.log(Level.WARNING,
"OR LOGGING: cannot save client, because client with the same name surname and date of birth already exists in the DB");
return null;
}
}
// checks if client has empty fields
if (client.getFirstName().equals("") || client.getLastName().equals("") || client.getDateOfBirth().equals("")
|| client.getPhoneNumber().equals("") || client.getClientType().equals("")) {
LOGGER.log(Level.WARNING, "OR LOGGING: cannot save client, all fields are mandatory");
return null;
}
LOGGER.log(Level.INFO, "OR LOGGING: new client saved");
return entityManager.merge(client);
}
/**
* deletes client from DB by ID
*
* @param id
*/
@Transactional
public void delete(Long id) {
LOGGER.log(Level.INFO, "OR LOGGING: client with id " + id + " removed");
entityManager.remove(entityManager.find(Client.class, id));
}
/**
* finds all Clients that are in DB
*
* @return
*/
@Transactional(readOnly = true)
public List<Client> findAll() {
LOGGER.log(Level.INFO, "OR LOGGING: all clients from DB returned");
return entityManager.createNamedQuery("findAllClients").getResultList();
}
}
<file_sep>/src/main/java/lt/akademija/exam/client/ClientController.java
package lt.akademija.exam.client;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* Controller controls data requests from the application to the server side
*
* @author orimkus
*
*/
@RestController
@RequestMapping(value = "/")
public class ClientController {
@Autowired
private ClientRepository clientRepository;
/**
*
* @return list of all clients in the database
*/
@GetMapping("/api/clients")
@ResponseStatus(HttpStatus.OK)
@ApiOperation(value = "Returns all clients that are currently in the DB list")
public List<Client> getClients() {
return clientRepository.findAll();
}
/**
*
* @param id
* id of Client to delete
*/
@DeleteMapping("/api/clients/{id}")
@ResponseStatus(HttpStatus.OK)
public void deleteClient(@PathVariable Long id) {
clientRepository.delete(id);
}
/**
*
* @param client
* object that holds data for new client creation
* @return
*/
@PostMapping("/api/clients")
@ResponseStatus(HttpStatus.CREATED)
public Client registerClient(@RequestBody Client client) {
return clientRepository.save(client);
}
}
<file_sep>/src/main/resources/static/js/resource_creation_component.jsx
var ResourceCreationComponent = React.createClass({
getInitialState: function() {
return {resourceTitle: '', resourceWeight: '', client:'', resourceKeepingSector: 'N/A', dateOfKeepingStart: 'N/A'};
},
handleTitleChange: function(event) {
this.setState({resourceTitle: event.target.value})
},
handleWeightChange: function(event) {
this.setState({resourceWeight: event.target.value})
},
handleClientChange: function(event) {
this.setState({client: event.target.value})
},
registerResource: function() {
axios.post('http://localhost:8080/api/resources', {
resourceTitle: this.state.resourceTitle,
resourceWeight: this.state.resourceWeight,
client: this.state.client,
resourceKeepingSector: this.state.resourceKeepingSector,
dateOfKeepingStart: this.state.dateOfKeepingStart
}).then(result => window.location = "#/allResources");
},
goHome: function() {
window.location = "#/allResources";
},
render() {
return (
<div>
<h2>Resource Creation Form</h2>
<button onClick={this.goHome}> home</button>
<form>
<fieldset>
<legend>Register new resource</legend>
<div className="form-group">
<label htmlFor="title">Title</label>
<input className="form-control" id="title" name="title" value={this.props.resourceTitle} onChange={this.handleTitleChange}/>
</div>
<div className="form-group">
<label htmlFor="weight">Weight</label>
<input className="form-control" id="weight" name="weight" value={this.props.resourceWeight} onChange={this.handleWeightChange}/>
</div>
<div className="form-group">
<label htmlFor="client">Weight</label>
<input className="form-control" id="client" name="client" value={this.props.client} onChange={this.handleClientChange}/>
</div>
<div className="form-group">
<input className="btn btn-primary" id="registerBtn" type="button" value="Register" onClick={this.registerResource}/>
</div>
</fieldset>
</form>
</div>
)
}
});
window.ResourceCreationComponent = ResourceCreationComponent;
<file_sep>/src/main/resources/static/js/client_creation_component.jsx
var ClientCreationComponent = React.createClass({
getInitialState: function() {
return {firstName: '', lastName: '', dateOfBirth: '', phoneNumber: '', clientType: ''};
},
handleFirstNameChange: function(event) {
this.setState({firstName: event.target.value})
},
handleLastNameChange: function(event) {
this.setState({lastName: event.target.value})
},
handleDateOfBirthChange: function(event) {
this.setState({dateOfBirth: event.target.value})
},
handlePhoneNumberChange: function(event) {
this.setState({phoneNumber: event.target.value})
},
handleClientTypeChange: function(event) {
this.setState({clientType: event.target.value})
},
registerClient: function() {
axios.post('http://localhost:8080/api/clients', {
firstName: this.state.firstName,
lastName: this.state.lastName,
dateOfBirth: this.state.dateOfBirth,
phoneNumber: this.state.phoneNumber,
clientType: this.state.clientType
}).then(result => window.location = "#/");
console.log(response.data);
},
goHome: function() {
window.location = "#/";
},
render() {
return (
<div>
<h2>Client Creation Form</h2>
<button onClick={this.goHome}> home</button>
<form>
<fieldset>
<legend>Register a client</legend>
<div className="form-group">
<label htmlFor="firstName">First Name</label>
<input className="form-control" id="firstName" name="firstName" value={this.props.firstName} onChange={this.handleFirstNameChange}/>
</div>
<div className="form-group">
<label htmlFor="lastName">Last Name</label>
<input className="form-control" id="lastName" name="lastName" value={this.props.lastName} onChange={this.handleLastNameChange}/>
</div>
<div className="form-group">
<label htmlFor="dateOfBirth">Date Of Birth</label>
<input className="form-control" id="dateOfBirth" name="dateOfBirth" value={this.props.dateOfBirth} onChange={this.handleDateOfBirthChange}/>
</div>
<div className="form-group">
<label htmlFor="phoneNumber">Phone Number</label>
<input className="form-control" id="phoneNumber" name="phoneNumber" value={this.props.phoneNumber} onChange={this.handlePhoneNumberChange}/>
</div>
<select onChange={this.handleClientTypeChange}>
<option >Choose client type</option>
<option value="Regular">Regular</option>
<option value="VIP">VIP</option>
</select>
<div className="form-group">
<input className="btn btn-primary" id="registerBtn" type="button" value="Register" onClick={this.registerClient}/>
</div>
</fieldset>
</form>
</div>
)
}
});
window.ClientCreationComponent = ClientCreationComponent;
<file_sep>/src/main/resources/static/js/client_table_component.jsx
var ClientTableComponent = React.createClass({
getInitialState: function() {
return {
clients: []
}
},
componentDidMount: function() {
axios.get('http://localhost:8080/api/clients')
.then(res => {
const clients = res.data;
this.setState({clients});
});
},
removeClient: function(event) {
console.log(event.target.value);
axios.delete('http://localhost:8080/api/clients/' + 1, {
}).then(result => window.location = "#/");
console.log(response.data);
},
render: function () {
return (
<div>
<h2>Table Of All Registered Clients</h2>
<table className="table">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Date Of Birth</th>
<th>Phone Number</th>
<th>Client Type</th>
<th>Inventory count</th>
<th>Client account</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{this.state.clients.map(client =>
<tr key={client.id}>
<td>{client.firstName}</td>
<td>{client.lastName}</td>
<td>{client.dateOfBirth}</td>
<td>{client.phoneNumber}</td>
<td>{client.clientType}</td>
<td>TODO</td>
<td>TODO</td>
<td value={client.id} onClick={this.removeClient}>remove</td>
</tr>
)}
</tbody>
</table>
</div>
);
}
});
window.ClientTableComponent = ClientTableComponent;
<file_sep>/src/main/resources/static/js/resource_table_component.jsx
var ResourceTableComponent = React.createClass({
getInitialState: function() {
return {
resources: []
}
},
componentDidMount: function() {
axios.get('http://localhost:8080/api/resources')
.then(res => {
const resources = res.data;
this.setState({resources});
});
},
render: function () {
return (
<div>
<h2>Table Of All Registered resources</h2>
<table className="table">
<thead>
<tr>
<th>Title</th>
<th>Weight</th>
<th>Resource keeping sector</th>
<th>Start date of keeping</th>
</tr>
</thead>
<tbody>
{this.state.resources.map(resource =>
<tr key={resource.id}>
<td>{resource.firstName}</td>
<td>{resource.lastName}</td>
<td>{resource.dateOfBirth}</td>
<td>{resource.phoneNumber}</td>
<td>{resource.resourceType}</td>
<td>TODO</td>
<td>TODO</td>
<td value={resource.id} onClick={this.removeresource}>remove</td>
</tr>
)}
</tbody>
</table>
</div>
);
}
});
window.ResourceTableComponent = ResourceTableComponent;
|
95ee6332923837b0cda3c1189857335fae819a33
|
[
"JavaScript",
"Java"
] | 6
|
Java
|
OsvaldasRimkus/final-java-exam-2
|
5d1b41c4ca98ebe4d2abf798e7b1d10d405a3121
|
470933fa693e55a8ce475ac37e761fdac6a2fe43
|
refs/heads/master
|
<file_sep>package com.example.demo.model;
import lombok.Data;
import javax.persistence.*;
import java.util.Date;
/**
* Created by huang on 2017/11/10.
*/
@Entity
@Data
public class BlackListDirectory implements NeedsOwner {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
/**
* 企业名称
*/
String enterpriseName;
/**
* 备注
*/
String remark;
/**
* 权限
*/
String username;
@Column(columnDefinition = "TIMESTAMP")
Date createTime;
}
<file_sep>package com.example.demo.controller;
import com.cputech.modules.usermsg.model.SysRole;
import com.cputech.modules.usermsg.model.SysUser;
import com.cputech.modules.usermsg.repository.SysRoleRepository;
import com.cputech.modules.usermsg.repository.SysUserRepository;
import com.cputech.modules.usermsg.service.CustomUserDetailsService;
import com.example.demo.model.RegisterDTO;
import com.example.demo.repository.RecordRepository;
import com.example.demo.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Controller
@CrossOrigin
public class RegisterController {
@Resource
CustomUserDetailsService customUserDetailsService;
@Autowired
SysRoleRepository sysRoleRepository;
@Autowired
SysUserRepository sysUserRepository;
@Autowired
RecordRepository recordRepository;
@PostMapping("/register")
@ResponseBody
public Result register( @RequestBody RegisterDTO registerDTO) {
Result result = new Result();
System.out.println("联系人:"+registerDTO+"电话:"+registerDTO);
//进行加密
SysUser user = new SysUser();
user.setUsername(registerDTO.getUserName());
user.setPassword(registerDTO.getPassWord());
List<SysUser> sysUserList = sysUserRepository.findByUsername(registerDTO.getUserName());
if (sysUserList.size() != 0){
//return"用户已经被注册,请登录.";
result.setFailed("用户已经被注册,请登录.");
}
List<SysRole> sysRoleList = new ArrayList<>();
sysRoleList.add(sysRoleRepository.findOne(2L));
user.setRoles(sysRoleList);
customUserDetailsService.create(user);
result.setFailed("注册成功,请登录.");
//return"注册成功,请登录.";
return result;
}
@GetMapping("/register")
public String registerList() {
return"user/register";
}
}<file_sep>package com.example.demo.controller;
import org.springframework.stereotype.Controller;
/**
* Created by huang on 2017/11/13.
*/
@Controller
public class InputsDirectoryController {
}
|
11f996e1606ded583c4ed243325c88a74c2818a9
|
[
"Java"
] | 3
|
Java
|
huangsongkai/enterprise_manager
|
3ae348ff85f3150387da4d8b4b551cf701678e21
|
9243ed3463fa047d41e4fdfd181a437e65a4b3af
|
refs/heads/main
|
<repo_name>marciopocebon/Jumping-game<file_sep>/script.js
score = 0;
cross = true;
document.onkeydown = function(e){
console.log("Key code is:" , e.keyCode)
if(e.keyCode==38){
sinchan = document.querySelector('.sinchan');
sinchan.classList.add('animateSinchan');
setTimeout(()=> {
sinchan.classList.remove('animateSinchan')
}, 700);
}
if(e.keyCode==39){
sinchan = document.querySelector('.sinchan');
sinchanX = parseInt(window.getComputedStyle(sinchan,null).getPropertyValue('left'));
sinchan.style.left = sinchanX + 112 + "px"
}
if(e.keyCode==37){
sinchan = document.querySelector('.sinchan');
sinchanX = parseInt(window.getComputedStyle(sinchan,null).getPropertyValue('left'));
sinchan.style.left = (sinchanX - 112) + "px"
}
}
setInterval(() => {
sinchan = document.querySelector('.sinchan');
gameOver = document.querySelector('.gameOver');
obstacle = document.querySelector('.obstacle');
sx = parseInt(window.getComputedStyle(sinchan,null).getPropertyValue('left'));
sy = parseInt(window.getComputedStyle(sinchan,null).getPropertyValue('top'));
ox = parseInt(window.getComputedStyle(sinchan,null).getPropertyValue('left'));
oy = parseInt(window.getComputedStyle(sinchan,null).getPropertyValue('top'));
offsetX = Math.abs(sx-ox);
offsetX = Math.abs(sy-oy);
console.log(offsetX, offsetY)
if(offsetX< 93 && offsetY<52){
gameOver.style.visibility = 'visible';
obstacle.classList.remove('obstacleLion')
}
else if(cross){
score+=1;
updateScore(score)
}
}, 100);
function updateScore(score){
scoreCont.innerHTML = "Your score:" + score
}
|
3eb402ba6943803ece32723a27913a43cc85b78d
|
[
"JavaScript"
] | 1
|
JavaScript
|
marciopocebon/Jumping-game
|
9d92a218e5fdf135bcdfae455555e7f2f4207008
|
f7d9a277e1cf956b942dc433564f0af29711d628
|
refs/heads/master
|
<repo_name>boyssimple/PentagonDemo<file_sep>/README.md
# PentagonDemo
雷达图

<file_sep>/PentagonDemo/Podfile
platform :ios, '8.0'
target 'PentagonDemo' do
pod 'AFNetworking', '~> 3.0'
pod 'Masonry'
end
|
e014e9e9b15c2cf6f77f0e4abd9fc4f91a852bd7
|
[
"Markdown",
"Ruby"
] | 2
|
Markdown
|
boyssimple/PentagonDemo
|
f3d4d555c404e6e04e10d753b1e326c479df2d36
|
08fb323801591a40c4c8686fcf6857b19c47234a
|
refs/heads/master
|
<repo_name>castro30/Launch-Checklist-Form<file_sep>/script.js
// Write your JavaScript code here!
window.addEventListener("load", function() {
let form = document.querySelector("form");
let button = document.getElementById("formSubmit");
let resultsArea = document.getElementById("faultyItems");
let pilotStat = document.getElementById("pilotStatus");
let copilotStat = document.getElementById("copilotStatus");
form.addEventListener("submit", function(event) {
let pilotNameInput = document.querySelector("input[name=pilotName]");
let copilotNameInput = document.querySelector("input[name=copilotName]");
let fuelLevelInput = document.querySelector("input[name=fuelLevel]");
let cargoMassInput = document.querySelector("input[name=cargoMass]");
let launchUpdate = document.getElementById("launchStatus");
event.preventDefault();
if (pilotNameInput.value === "" || copilotNameInput.value === "" || fuelLevelInput.value === "" || cargoMassInput.value === "") {
alert("All fields are required!");
}
if (!isNaN(pilotNameInput.value) || !isNaN(copilotNameInput.value)){
alert("Please Enter Text!");
}
if (isNaN(fuelLevelInput.value)||isNaN(cargoMassInput.value)){
alert("Please Enter Numbers!");
}
if(fuelLevelInput.value < 10000){
document.getElementById("fuelStatus").innerHTML = "there is not enough fuel for the journey";
launchUpdate.innerHTML = "Shuttle not ready for launch";
launchUpdate.style.color = "red";
makeVisible();
}
if(cargoMassInput.value>10000){
document.getElementById("cargoStatus").innerHTML = "there is too much mass for the shuttle to take off.";
launchUpdate.innerHTML = "Shuttle not ready for launch";
launchUpdate.style.color = "red";
makeVisible();
}
if (fuelLevelInput.value >= 10000 && cargoMassInput.value < 10000){
pilotStat.innerHTML = `${pilotNameInput.value} is Ready`;
copilotStat.innerHTML = `${copilotNameInput.value} is Ready`;
launchUpdate.innerHTML = "Shuttle is ready for Launch";
launchUpdate.style.color = "green";
makeVisible();
// thePlanet();
}
});
function planetaryInfo(){
const div = document.getElementById("PlantetaryData");
let theData = [];
for (let a = 0; a<5; a++){
fetch("https://handlers.education.launchcode.org/static/planets.json").then(function(response) {
response.json().then(function(json){
theData.push(json[a]);
});
});
return {
name: theData.name,
diameter: theData.diameter,
star: theData.star,
distance: theData.distance,
moons: theData.moons,
}
}
}
function thePlanet(){
planetaryInfo();
window.alert(JSON.stringify(variable))
div.innerHTML=`
<h2>Mission Destination</h2>
<ol>
<li>Name: ${theData.name}</li>
<li>Diameter: ${theData.diameter}</li>
<li>Star: ${theData.star}</li>
<li>Distance from Earth: ${theData.distance}</li>
<li>Number of Moons: ${theData.moons}</li>
</ol>
`;
}
}
function makeVisible(){
resultsArea.style.visibility = "visible";
}
});
/* This block of code shows how to format the HTML once you fetch some planetary JSON!
<h2>Mission Destination</h2>
<ol>
<li>Name: ${}</li>
<li>Diameter: ${}</li>
<li>Star: ${}</li>
<li>Distance from Earth: ${}</li>
<li>Number of Moons: ${}</li>
</ol>
<img src="${}">
*/
|
b6b5d55eaea5a81aaaa506381931b1116018393c
|
[
"JavaScript"
] | 1
|
JavaScript
|
castro30/Launch-Checklist-Form
|
af99092e76003dca125558233ea4a129a325e064
|
a3195cfb2f39dad6e9ce28d649b66a18641e52ce
|
refs/heads/master
|
<file_sep>api_key = "<KEY>"
|
63df2be6c2ba319092c33cffc8bda94a7bd99410
|
[
"Python"
] | 1
|
Python
|
Cfarchmin/ETL-Project
|
01ccd17b551126b8212521dbdb47a690d979d3d7
|
ac393986105c0d74c0fb388c8025e7a62447c825
|
refs/heads/master
|
<file_sep># Tumblr-Live-Queue
<file_sep>/**
* Created by root on 1/28/15.
*/
var http = require ('http');
var util = require('util');
var tumblrOauth = require('tumblr-auto-auth');
var prompt = require('prompt');
//http.createServer (function (req, res){
//Todo make query to db for user's blog name
//console.log(req);
var queryResult = 'true';//insert query here
if (queryResult == 'true'){
tumblrOauth.getAuthorizedClient({
userEmail: email, //TODO replace with result.email
appConsumerKey: appConsumerKey,
appSecretKey: appSecretKey
},
function (err, client) {
getClientQueue(err,client);
});
}
else if (queryResult == 'false' ){
prompt.start();
prompt.get('email',function (err,result){
if (err){console.log(err);}
email = result.email;
tumblrOauth.interactiveAuthorization({
userEmail: email,
appConsumerKey: appConsumerKey,
appSecretKey: appSecretKey,
debug: true
},
function (err, client) {
//client.userInfo.user.blogs[0]name; //TODO insert into database
getClientQueue(err,client);
});
});
}
else{
console.log('bad query');
}
function getClientQueue(err,client){
client.userInfo(function (err, data) {
client.queue(data.user.blogs[0].name, function (err, queue) {
for (var i = 0; i < queue.posts.length;) {
var type = queue.posts[i].type;
var postData = require('./postTypes/'+type+'.js');
postData.register(queue.posts[i]);
i++;
}
//res.writeHead(200, {'Content-Type':'text/plain'});
//res.end('something something stuff');
});
});
}
function deletePost(blogName, postId) {
client.deletePost(blogName, postId, function (err, data) {
if (!err) {
console.log('successfully deleted post');
}
else {
console.log('error: ' + err);
}
});
}
//}).listen(80);
/* next();
};
exports.register.attributes = {
name: 'oAuth',
version: '1.0.0'
};*/
//module.exports = exports;
|
453c8fca986885c604c5bc3e9de5471e96be327a
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
Globolobo/Tumblr-Live-Queue
|
d43140f523b8d3059871828c535cd4665778a66b
|
3179a33f27463ef6cf9dd85a30387d96f68f102b
|
refs/heads/master
|
<file_sep>//<NAME>
//<NAME>
//<NAME>
//Instituto Tecnologico de Costa Rica
//Curso: Sistemas Operativos
#include "my_threads.h"
#include "scheduler.h"
//my_thread_csched
//Funcion que recibe un char del tipo de scheduler
//Asigna a la variable active_sched el valor segun el scheduler enviado
void my_thread_chsched(char *sched){
if(!strcmp(sched,"RoundRobin")){
active_sched = 0;
}
if(!strcmp(sched,"Sorteo")){
active_sched = 1;
}
if(!strcmp(sched,"Real")){
active_sched = 2;
}
}
//scheduler
//Funcion que activa los hilos con el algoritmo de RoundRobin
void scheduler(){
if(active_threads_aux > 0){
curcontext = (curcontext + 1);
if(deadThreads[curcontext% active_threads]){
while(deadThreads[curcontext% active_threads]){
curcontext+=1;
}
}
curcontext = curcontext % active_threads;
current_thread = &threads[curcontext];
setcontext(current_thread); //Activa el nuevo hilo
}
}
//sched_sorteo
//Funcion que activa los hilos con el algoritmo de Sorteo
void sched_sorteo(){
srand(time(NULL));
int aux;
if(active_threads_aux > 0){
int winner = rand()%(total_tickets+1);//Ganador del sorteo
aux = winner;
int i;
for (i = 0; i < active_threads; i++) {//Revisa el ganador
aux -= tickets[i];
if(aux<=0){
if(deadThreads[i% active_threads]){
while(deadThreads[i% active_threads]){
i+=1;
}
}
curcontext = i;
current_thread = &threads[curcontext];
break;
}else{
tickets[i]++;
total_tickets++;
}
}
setcontext(current_thread);//Activa el nuevo hilo
}
}
//sched_real
//Funcion que activa los hilos con el algoritmo de Tiempo Real
void sched_real(){
int aux = -1;
if(active_threads_aux > 0){
int i;
for (i = 0; i < active_threads; i++) {//Busca el hilo de mayor prioridad que aun no haya finalizado
if(aux<priority[i]&&!deadThreads[i] && !priority_aux[i]){
curcontext = i;
aux = priority[i];
}
}
if(aux == -1){
for (i = 0; i < active_threads; i++) {
priority_aux[i] = 0;
}
sched_real();
}else{
priority_aux[curcontext] = 1;//Hilo ya ejecutado
current_thread = &threads[curcontext];
setcontext(current_thread); //Activa el nuevo hilo
}
}
}
//timer_interrupt
//Crea el context segun el tipo de scheduler
void timer_interrupt(){
getcontext(&signal_context);
signal_context.uc_stack.ss_sp = signal_stack;
signal_context.uc_stack.ss_size = STACKSIZE;
signal_context.uc_stack.ss_flags = 0;
sigemptyset(&signal_context.uc_sigmask);
//Si es de round robin
if(active_sched == 0){
makecontext(&signal_context, scheduler, 1);
}
//Si es de sorteo
if(active_sched == 1){
makecontext(&signal_context, sched_sorteo, 1);
}
//Si es de tiempo real
if(active_sched == 2){
makecontext(&signal_context, sched_real, 1);
}
//Cambia el context
swapcontext(current_thread,&signal_context);
}
<file_sep>#ifndef my_threads_h
#define my_threads_h
#include <ucontext.h>
#include <sys/types.h>
#include <sys/time.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define NUMTHREADS 100
#define STACKSIZE 4096
#define INTERVAL 100
sigset_t set;
//ucontext
ucontext_t signal_context;
ucontext_t threads[NUMTHREADS];
ucontext_t *current_thread;
ucontext_t exitContext;
//Variables
int priority[NUMTHREADS];
int priority_aux[NUMTHREADS];
int tickets[NUMTHREADS];
int deadThreads[NUMTHREADS];
int curcontext;
int init;
int active_threads;
int active_threads_aux;
int total_tickets;
int active_sched;
void my_thread_create(void *function,void *args, int tickets_sched, int priority_sched); //Crea el hilo
void my_thread_end(); //Termina el hilo
void my_thread_yield(); //Cede el procesador
void run_threads(); //Corre los hilos
//static void setExitContext();
void *signal_stack; //Signal stack
static void setExitContext(); //Crea el contexto para ejecutarse cuando un hilo termina
void setup(); //Setea los hilos
#endif
<file_sep>#ifndef _cityController_h
#define _cityController_h
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
void *cityController(); //Controla el hilo de la ciudad
#endif
<file_sep>//<NAME>
//<NAME>
//<NAME>
//Instituto Tecnologico de Costa Rica
//Curso: Sistemas Operativos
#include "scheduler.h"
#include "my_threads.h"
#include "my_mutex.h"
//executeExitContext
//Funcion que se ejecuta cuando un hilo termina
static void executeExitContext(){
//printf("Hilo %d terminando\n", curcontext);
deadThreads[curcontext] =1;
total_tickets-=tickets[curcontext];
active_threads_aux--;
timer_interrupt(); //Selecciona el scheduler
}
//setExitContext
//Funcion que crea contexto para ejecutarse cuando un hilo termina
static void setExitContext(){
static int exitContextCreated;
if(!exitContextCreated){
getcontext(&exitContext);
exitContext.uc_link = 0;
exitContext.uc_stack.ss_sp = malloc(STACKSIZE);
exitContext.uc_stack.ss_size = STACKSIZE;
exitContext.uc_stack.ss_flags= 0;
makecontext(&exitContext, (void (*) (void))&executeExitContext, 0);
exitContextCreated = 1;
}
}
//setup
//Funcion que setea los hilos en caso de no haberse creado
void setup(){
int i;
for( i = 0;i <NUMTHREADS ;i++){
deadThreads[i] = 0;
}
setExitContext();
struct itimerval it;
signal_stack = malloc(STACKSIZE);
it.it_interval.tv_sec = 0;
it.it_interval.tv_usec = INTERVAL * 1000;
it.it_value = it.it_interval;
setitimer(ITIMER_REAL, &it, NULL);
struct sigaction act;
act.sa_sigaction = timer_interrupt; //Selecciona el scheduler
sigemptyset(&act.sa_mask);
act.sa_flags = SA_RESTART | SA_SIGINFO;
sigemptyset(&set);
sigaddset(&set, SIGALRM);
sigaction(SIGALRM, &act, NULL);
}
//my_thread_create
//Funcion que se encarga de crear los hilos
void my_thread_create(void *function, void *args, int tickets_sched, int priority_sched){
//Si no se ha creado ningun hilo, primero setea todo
if(!init){
setup(); //Setea el hilos
}
void *stack;
//Crea el contexto del hilo
ucontext_t *uc = &threads[active_threads];
getcontext(uc); //Inicializa el context
stack = malloc(STACKSIZE);
uc->uc_stack.ss_sp = stack;
uc->uc_stack.ss_size = STACKSIZE;
uc->uc_stack.ss_flags = 0;
uc->uc_link = &exitContext; //Se reinicia antes de volver hacer el context
sigemptyset(&uc->uc_sigmask);
printf("%s", uc);
makecontext(uc, function, 1, args);
//Setea los datos para los schedulers
tickets[active_threads] = tickets_sched; //Tickets del scheduler
priority[active_threads] = priority_sched; //Prioridad del scheduler
total_tickets+=tickets_sched;
active_threads++;
active_threads_aux++;
// printf("Se creo un hilo de manera correcta");
}
//my_thread_end
//Funcion que termina el hilo
void my_thread_end(){
deadThreads[curcontext] =1;
total_tickets-=tickets[curcontext];
active_threads_aux--;
timer_interrupt();//Selecciona el scheduler
}
//my_thread_yield
//Funcion que cesde el procesador
void my_thread_yield(){
timer_interrupt();//Selecciona el scheduler
}
//run_threads
//Funcion que pone a correr los hilos
void run_threads(){
current_thread = &threads[0];
setcontext(&threads[0]);
}
<file_sep>//<NAME>
//<NAME>
//<NAME>
//Instituto Tecnologico de Costa Rica
//Curso: Sistemas Operativos
#include "cityController.h"
#include "my_mutex.h"
#include "my_threads.h"
#include "scheduler.h"
#include <math.h>
//Colores
#define ANSI_COLOR_RED "\x1b[31m"
#define ANSI_COLOR_GREEN "\x1b[32m"
#define ANSI_COLOR_YELLOW "\x1b[33m"
#define ANSI_COLOR_BLUE "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN "\x1b[36m"
#define ANSI_COLOR_RESET "\x1b[0m"
#define IN 99
#define N 42
//Variables
my_mutex fieldLock;
char* matriz[6][7];
int semaforo =0;
int bandera=0;
int cronometro =0;
//cityController
//Funcion que se encarga de controlar el hilo de la ciudad
//Inicia los hilos de los carros,ambulancias,planta nuclear y los barcos
//Dentro de un while infinito que va estar actualizando la matriz segun la accion de los distintos hilos
void *cityController(){
//Random
srand(time(NULL));
iniciarMatriz(); //Inicia la matriz
my_mutex_init(&fieldLock); //Inicia el mutex
startCars(); //Inicia los hilos de los carros
startNuclear(); //Inicia el hilo de la planta nuclear
startAmbulance(); //Inicia los hilos de las ambulancias
startShip(); //Inicia los hilos de los barcos
//While infinito
while (1) {
//Si la planta nuclear no ha explotado
if (bandera == 0){
printf("\n--------------------------------------------------\n\n");
matrizImpresion(); //Imprime la matruz
cronometro++; //Suma al cronometro de la planta nuclear
printf("\n\t TIEMPO: %d\n", cronometro);
// printMatriz();
usleep(2500000000); //Sleep
system("clear");
}
else{
bandera=0; //Vuelve a iniciar la planta nuclear
cronometro=0;
printf(" . . . \n");
printf(" ||| \n");
printf(" `--+--' \n");
printf(" ||| \n");
printf(" ' | ' \n");
printf(" | \n");
printf(" | \n");
printf(" ,--'#`--. \n");
printf(" |#######| \n");
printf(" _.-'#######`-._ \n");
printf(" ,-'###############`-. \n");
printf(" ,'#####################`, \n");
printf(" /#########################| \n");
printf(" |###########################| \n");
printf(" |#############################| \n");
printf(" |#############################| \n");
printf(" |#############################| \n");
printf(" |#############################| \n");
printf(" |###########################| \n");
printf(" |#########################/ \n");
printf(" `.#####################,' \n");
printf(" `._###############_,' \n");
printf(" `--..#####..--' \n");
printf(ANSI_COLOR_RESET"\n\n \t\t -> LA PLANTA NUCLEAR HA EXPLOTADO BOOOOOOOOOOOOOOOOOOOOOOOOOOM!\n\n");
sleep(1000000000000);
usleep(250000000000); //Sleep
system("clear");
}
}
}
//matrizImpresion
//Funcion que imprime la matriz representativa
void matrizImpresion(){
char* matrizImpresion[11][7]={{"*_____","*_____","*_____","*_____","*_____","*_____","*\n"},{"| ","| ","| "," ","| ","| ","|\n"},{"*_____","*_____","*_____","©_____","*_____","*_____","*\n\n"},
{"░░░░░░","██░░░░","░░░░░░","█░░░░░","░░░░░░","█░░░░░","░"},{"*_____","*_____","* ","* ","* ","* ","*\n"},{" ","| "," ","| ","| ","| ","|\n"},
{"*_____","*_____","*_____","*_____","*_____","*_____","*\n"},{"| "," ","| ","| "," ","| ","|\n"},{"*_____","*_____","*_____","*_____","*_____","*_____","*\n"},
{"| "," ","| ","| "," ","| ","|\n"},{"*_____","*_____","*_____","*_____","*_____","*_____","*\n"}};
int i,j;
int contador =0;
//For para imprimir la matriz representativa
printf(ANSI_COLOR_YELLOW"\t|_xxxxxx_ |_xxxxxx_ |_xxxxxx_ |_xxxxxx_\n");
printf(ANSI_COLOR_YELLOW"\t| ╔════╗ | ╔════╗ | ╔════╗ | ╔════╗ \n");
printf(ANSI_COLOR_YELLOW"\t| ║ CO ║ | ║ ME ║ | ║ RC ║ | ║ IO ║ |\n");
printf(ANSI_COLOR_YELLOW"\t| ╚════╝ | ╚════╝ | ╚════╝ | ╚════╝ |\n");
printf(ANSI_COLOR_YELLOW"\t|_ ░▓░ _ _ ░▓░ _ _ ░▓░ _ _ ░▓░ _ |\n\n"ANSI_COLOR_RESET);
for(i=0;i<11;i++){
if(i%2 == 0){
printf("\t");
for (j=0;j<7;j++){
//printf("entro en %d",i);
if(matriz[contador][j]== "C "){
printf(ANSI_COLOR_GREEN "%s",matriz[contador][j]);
}
else if(matriz[contador][j]== "A "){
printf(ANSI_COLOR_RED "%s",matriz[contador][j]);
}
else{
printf(ANSI_COLOR_CYAN "%s",matriz[contador][j]);
}
}
//Imprime los rios
if(i == 4){
printf(ANSI_COLOR_BLUE "\n\t░░░░░░██░░░░░░░░░░█░░░░░░░░░░░█░░░░░░");
if (semaforo == 0) { // verde
printf(ANSI_COLOR_GREEN " ©" ANSI_COLOR_YELLOW "©" ANSI_COLOR_RED "©" ANSI_COLOR_RESET " SEMAFORO:" ANSI_COLOR_GREEN" █\n");
}
else{
printf(ANSI_COLOR_GREEN " ©" ANSI_COLOR_YELLOW "©" ANSI_COLOR_RED "©" ANSI_COLOR_RESET " SEMAFORO:" ANSI_COLOR_RED" █\n");
}
}
contador++;
printf("\n");
}
printf("\t");
//Imprime los rios
for( j =0; j<7;j++){
if(i ==3){
printf(ANSI_COLOR_BLUE "%s",matrizImpresion[i][j]);
}
else{
printf(ANSI_COLOR_RESET "%s",matrizImpresion[i][j]);
}
}
//Imprime los semaforos
if(i==3){
if (semaforo == 0) { // verde
printf(ANSI_COLOR_GREEN " ©" ANSI_COLOR_YELLOW "©" ANSI_COLOR_RED "©" ANSI_COLOR_RESET " SEMAFORO:" ANSI_COLOR_GREEN" █\n");
}
else{
printf(ANSI_COLOR_GREEN " ©" ANSI_COLOR_YELLOW "©" ANSI_COLOR_RED "©" ANSI_COLOR_RESET " SEMAFORO:" ANSI_COLOR_RED" █\n");
}
}
}
//Imprime la planta nuclear
printf(" _"ANSI_COLOR_YELLOW"x"ANSI_COLOR_RESET"_░▓░_"ANSI_COLOR_YELLOW"x"ANSI_COLOR_RESET"_\n");
printf(" | ╔════╗ |\n");
printf(" "ANSI_COLOR_YELLOW"x"ANSI_COLOR_RESET" ║ PN ║ "ANSI_COLOR_YELLOW"x"ANSI_COLOR_RESET"\n");
printf(" "ANSI_COLOR_YELLOW"x"ANSI_COLOR_RESET" ╚════╝ "ANSI_COLOR_YELLOW"x"ANSI_COLOR_RESET"\n");
printf(" |_"ANSI_COLOR_YELLOW"xxxxxxx"ANSI_COLOR_RESET"_|\n");
}
//printMatriz
//Print de la matriz
void printMatriz(){
int i,j;
for(i=0;i < 6; i++){
printf("\t");
for(j=0;j < 7; j++){
//matriz[i][j]='c';
printf("%s",matriz[i][j]);
}
printf("\n");
}
printf("\n\n");
}
//nuclearPlantController
//Controller de la planta nuclear
//While infinito para controlar la planta si ha explotado o no
void *nuclearPlantController(){
while(1){
if(cronometro >= 100){
bandera=1;
}
// verificar tiempo e impresion
}
}
//carController
//Funcion que controla los hilos de los carros
//Controla los semaforos, el paso de los puentes (prioridad) y el ceda
void *carController(){
//While infinito para sacar los random donde se va mover los carros(pos inicial y final)
while(1){
//pthread_mutex_lock(&mutex);
int ruta[N];
//my_mutex_lock(&fieldLock);
int r = rand() % 41;
int r2 = rand() % 41;
while(r==r2 || (r>=14 && r<=20) || (r2>=14 && r2<=20)){
r2 = rand() % 41;
r = rand() % 41;
}
//printf("hilo: %i-%i",r,r2);
int len=dijsktra(r,r2,ruta);
int x=0,y=0,z;
int posAnterior=-1;
//For para recorrer la ruta que retorno el dijkstra
for(z=0;z<len+1;z++){
//printf("%d /n",ruta[z]);
usleep(250000);
int pos =ruta[z];
x = pos/7;
y = pos%7;
//Si hay una ambulancia en el nodo del puente y el carro se encuentra en alguno de los extremos, se debera de esperar hasta que dicha ambulancia
//pase por el puente por eso el !=A
if(x ==2 && y ==1 ){ //PRIORIDAD PUENTE1 Y SEMAFORO
while(1){
if(semaforo == 0 && matriz[2][1] != "A " && matriz[3][1] != "A "&& matriz[1][1] != "A "){// esta en verde
break;
}
usleep(10000);
}
}
else if(x ==2 && y ==3 ){ //PRIORIDAD PUENTE2
while(1){
if(matriz[2][3] != "A " && matriz[3][3] != "A " && matriz[1][3] != "A "){// esta en verde
break;
}
usleep(10000);
}
}
else if(x ==2 && y ==5){ //PRIORIDAD PUENTE3 Y SEMAFORO
while(1){
if(matriz[2][5] != "A " && matriz[1][5] != "A " && matriz[3][5] != "A "){// esta en verde
break;
}
usleep(10000);
}
}
if(1){
matriz[posAnterior/7][posAnterior%7]=" ";
}
posAnterior=ruta[z];
matriz[x][y]="C ";
if (x == 5 && y ==2 || x ==5 && y == 3){
cronometro=0;
}
usleep(250000);
my_thread_yield();
//Controla los cedas (matriz[2][3] es el centro del puente)
while(1){
if(matriz[2][3] == "C " || matriz[2][3] == "A "){
//matriz[1][2] =="A "||matriz[1][2]=="C "&&matriz[1][4]=="A "||matriz[1][4]=="C "
if(pos/7 == 1 && pos%7 == 2 || pos/7 == 1 && pos%7 == 4){
//printf("x %d \n",pos/7);
//printf("x %d \n",pos%7);
printf("\n -> CEDA\n");
usleep(9990000);
}
else{
break;
}
}else{
break;
}
}
}
//Pone una x donde termina el recorrido del carro
matriz[x][y]="x ";
usleep(2500000);
//Luego lo pone vacio de nuevo
matriz[x][y]=" ";
}
}
//ambulanceController
//Funcion que controla los hilos de las ambulancias
//Controla los semaforos y el ceda
void *ambulanceController(){
while(1){
//pthread_mutex_lock(&mutex);
int ruta[N];
//my_mutex_lock(&fieldLock);
int r = rand() % 41;
int r2 = rand() % 41;
while(r==r2 || (r>=14 && r<=20) || (r2>=14 && r2<=20)){
r2 = rand() % 41;
r = rand() % 41;
}
//printf("hilo: %i-%i",r,r2);
//Saca ruta mas corta hacia el destino
int len=dijsktra(r,r2,ruta);
int x=0,y=0,z;
//For para recorrer la ruta del dijkstra
int posAnterior=-1;
for(z=0;z<len+1;z++){
//printf("%d /n",ruta[z]);
usleep(250000);
int pos =ruta[z];
x = pos/7;
y = pos%7;
//Controla los semaforos
if(x ==2 && y ==1 && semaforo ==1 ){
while(1){
if(semaforo == 0){
break;
}
usleep(1000);
}
}
if(1){
matriz[posAnterior/7][posAnterior%7]=" ";
}
posAnterior=ruta[z];
//Pone una A donde se va mover la ambulancia
matriz[x][y]="A ";
usleep(250000);
//Cede el procesador
my_thread_yield();
//Ceda
while(1){
if(matriz[2][3] == "C " || matriz[2][3] == "A "){
//matriz[1][2] =="A "||matriz[1][2]=="C "&&matriz[1][4]=="A "||matriz[1][4]=="C "
if(pos/7 == 1 && pos%7 == 2 || pos/7 == 1 && pos%7 == 4){
//printf("x %d \n",pos/7);
//printf("x %d \n",pos%7);
printf("\n -> CEDA\n");
usleep(9990000);
}
else{
break;
}
}else{
break;
}
}
}
matriz[x][y]="x "; //Pone una x por donde termino
usleep(2500000);
matriz[x][y]=" "; //Pone vacio
}
//my_mutex_unlock(&fieldLock);
}
//shipController
//Funcion que controla los hilos de los barcos
void *shipController(){
while(1){
//pthread_mutex_lock(&mutex);
int ruta[N];
int r = 14;
int r2 = 16;
//printf("hilo: %i-%i",r,r2);
int len=dijsktra(r,r2,ruta);
int x=0,y=0,z;
int posAnterior=-1;
//For para recorrer ruta
for(z=0;z<len+1;z++){
//printf("%d /n",ruta[z]);
usleep(250000);
int pos =ruta[z];
if(posAnterior!=-1 && matriz[pos/7][pos%7]!="B "){
matriz[posAnterior/7][posAnterior%7]=" ";
}
posAnterior=ruta[z];
x = pos/7;
y = pos%7;
matriz[x][y]="B ";
//Setea los semaforos si el barco esta en la posicion 2,1 de la matriz (lo pone en rojo el semaforo del puente)
if (x== 2 && y == 1){
semaforo =1;
}
else{
semaforo=0;
}
usleep(250000);
//Cede el procesador
my_thread_yield();
}
matriz[x][y]="x "; //X donde termino el recorrido
usleep(2500000);
matriz[x][y]=" "; //Vuelve a poner en vacio
}
//my_mutex_unlock(&fieldLock);
}
//dijkstra
//Funcion que encuentra la ruta mas corta
//Recine el nodo de inicio, final y un arreglo donde guardara los nodos de la ruta
int dijsktra(int source,int target,int ruta[N]){
//Matriz de adyacencia
int cost[42][42]=
//0 //1 //2 //3 //4 //5 //6//7//8 //9 //10 //11//12//13//14//15//16//17//18//19//20//21//22//23//24//25//26//27//28//29//30//31//32//33//34//35//36//37//38//39//40//41
{{0, 1, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}, //0
{1, 0, 1, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//1
{99, 1, 0, 1, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//2
{99, 99, 1, 0, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//3
{99, 99, 99, 1, 0, 1, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//4
{99, 99, 99, 99, 1, 0, 1, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//5
{99, 99, 99, 99, 99, 1, 0, 99, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//6
{1, 99, 99, 99, 99, 99, 99, 0, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//7
{99, 1, 99, 99, 99, 99, 99, 1, 0, 1, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//8
{99, 99, 1, 99, 99, 99, 99, 99, 1, 0, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//9
{99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 0, 1, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//10
{99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 1, 0, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//11
{99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 1, 0, 1, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//12
{99, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 1, 0, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//13
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 0, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//14
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 0, 1, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//15
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 0, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//16
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 99, 0, 99, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//17
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 0, 99, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//18
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 99, 0, 99, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//19
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 0, 99, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//20
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 0, 1, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//21
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 1, 0, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//22
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 0, 1, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//23
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 1, 0, 1, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//24
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 1, 0, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//25
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 1, 0, 1, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 99, 99, 99},//26
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 1, 0, 99, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 99, 99},//27
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 99, 0, 1, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 99},//28
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 0, 1, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99},//29
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 1, 0, 1, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99},//30
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 1, 0, 1, 99, 99, 99, 99, 99, 1, 99, 99, 99},//31
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 0, 1, 99, 99, 99, 99, 99, 99, 99, 99},//32
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 1, 0, 1, 99, 99, 99, 99, 99, 1, 99},//33
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 1, 0, 99, 99, 99, 99, 99, 99, 1},//34
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 99, 0, 1, 99, 99, 99, 99, 99},//35
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 0, 1, 99, 99, 99, 99},//36
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 1, 0, 1, 99, 99, 99},//37
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 1, 0, 1, 99, 99},//38
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 0, 1, 99},//39
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 1, 0, 1},//40
{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 1, 99, 99, 99, 99, 99, 1, 0}};//41
int dist[N],prev[N],selected[N]={0},i,m,min,start,d,j;
int path[N]={-1};
for(i=0;i< N;i++)
{
dist[i] = IN;
prev[i] = -1;
}
start = source;
selected[start]=1;
dist[start] = 0;
while(selected[target] ==0)
{
min = IN;
m = 0;
for(i=0;i< N;i++)
{
d = dist[start] +cost[start][i];
if(d< dist[i]&&selected[i]==0)
{
dist[i] = d;
prev[i] = start;
}
if(min>dist[i] && selected[i]==0)
{
min = dist[i];
m = i;
}
}
start = m;
selected[start] = 1;
}
start = target;
j = 0;
while(start != -1)
{
path[j] = start;
start = prev[start];
j++;
}
//path[j]='\0';
//strrev(path);
int p,q=0;
for(p=dist[target];p >= 0; p--){
ruta[q] = path[p];
//printf("%i->",path[p]);
q++;
}
printf("\n");
//printf("%s", path);
//Retorna un arreglo con la ruta
return dist[target];
}
//iniciaMatriz
//Funcion que inicia la matriz
void iniciarMatriz(){
int i,j;
for (i=0;i<6;i++){
for(j=0;j<7;j++){
matriz[i][j]=" ";
}
}
}
//verificar
//Verifica si el nodo esta en la ruta
int verficar(int ruta[],int numero){
int i;
for (i=0;i< sizeof(ruta);i++){
if(ruta[i]== numero){
return 1;
}
}
return 0;
}
//startCars
//Crea los hilos de los carros
void startCars(){
my_thread_create(carController, NULL,5,5);
// my_thread_create(carController, NULL,5,5);
// my_thread_create(carController, NULL,5,5);
// my_thread_create(carController, NULL,5,5);
}
//startAmbulance
//Crea los hilos de las ambulancias
void startAmbulance(){
my_thread_create(ambulanceController, NULL,5,1);
// my_thread_create(ambulanceController, NULL,5,1);
}
//startShips
//Crea los hilos de los barcos
void startShip(){
my_thread_create(shipController, NULL,5,1);
}
//startNuclear
//Crea los hilos de la planta nuclear
void startNuclear(){
my_thread_create(nuclearPlantController, NULL,5,5);
}
<file_sep>#ifndef scheduler_h
#define scheduler_h
#include <time.h>
#include <string.h>
void my_thread_chsched(char *sched); //Cambia el scheduler
void run_threads(); //Corre los hilos
void scheduler(); //Scheduler de Round Robin
void sched_sorteo(); //Scheduler de Sorteo
void sched_real(); //Scheduler de Tiempo real
void timer_interrupt(); //Crea el context segun el tipo de scheduler
#endif
<file_sep>//<NAME>
//<NAME>
//<NAME>
//Instituto Tecnologico de Costa Rica
//Curso: Sistemas Operativos
#include "my_mutex.h"
//my_mutex_init
//Funcion que inicializa el mutex
void my_mutex_init(my_mutex *lock){
lock = 0;
}
//atomic_xchg
//xchg que permite hacer la operacion y la asignacion atomica
int atomic_xchg(my_mutex * lock){
unsigned int tmp = 1;
__asm__(
"xchgl %0, %1;\n"
: "=r"(tmp), "+m"(*lock)
: "0"(tmp)
:"memory");
return tmp;
}
//test_and_set
//Funcion que hace el test and set para el lock
int test_and_set(my_mutex *lock){
return atomic_xchg(lock);
}
//my_mutex_destroy
//Funcion que libera o destruye el mutex
void my_mutex_destroy(my_mutex *lock){
//free(lock);
}
//my_mutex_lock
//Funcion que hace el lock del mutex
void my_mutex_lock(my_mutex *lock){
while (*lock){
sleep(1);
}
test_and_set(lock);
}
//my_mutex_trylock
//Funcion para try-lock del mutex
void my_mutex_trylock(my_mutex *lock){
while (*lock){
usleep(1000);
}
test_and_set(lock);
}
//my_mutex_unlock
//Metodo que desbloquea el mutex
void my_mutex_unlock(my_mutex *lock){
unsigned int tmp = 0;
__asm__(
"xchgl %0, %1;\n"
: "=r"(tmp), "+m"(*lock)
: "0"(tmp)
:"memory");
}
<file_sep>#ifndef my_mutex_h
#define my_mutex_h
#include <stdio.h>
#include <unistd.h>
#define my_mutex int
void my_mutex_init(my_mutex *lock); //Inicializa el mutex
void my_mutex_lock(my_mutex *lock); //Lock del mutex
void my_mutex_trylock(my_mutex *lock); //Try lock del mutex
void my_mutex_unlock(my_mutex *lock); //Unlock del mutex
void my_mutex_destroy(my_mutex *lock); //Destuye el mutex
#endif
<file_sep>//<NAME>
//<NAME>
//<NAME>
//Instituto Tecnologico de Costa Rica
//Curso: Sistemas Operativos
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "cityController.h"
#include "my_mutex.h"
#include "my_threads.h"
#include "scheduler.h"
//Main
//Crea el hilo que va controlar la ciudad
//Se cambia el scheduler para que funcione con el scheduler especificado
//Real = Scheduler Tiempo Real
//RoundRobin = Scheduler Round Robin
//Sorteo = Scheduler Sorteo
//Al final pone a correr los distintos hilos con run_threads
int main(int argc, char *argv[]){
my_thread_create(cityController,NULL,5,5); //Crea el hilo que manejara la ciudad
my_thread_chsched("RoundRobin"); //Tipo de scheduler (Para cambiar el scheduler)
run_threads(); //Pone a correr los hilos
return 0;
}
|
0b1568905662394f32ef6ce1250d875a204f53e2
|
[
"C"
] | 9
|
C
|
josueDavid23/ThreadCity
|
2723ea94a63ff42f9f44cd548ffbd84e0b9cf438
|
20a4b8f675dd530a6d5e636015a662d56ab88c05
|
refs/heads/master
|
<file_sep># angular2.io.tutorials<file_sep>//Angular Framework
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
//App
import { HeroDetailComponent } from './hero-detail.component'
import { Hero } from './hero';
import { HeroService } from './hero.service';
@Component({
moduleId: module.id,
selector: 'heroes',
templateUrl: 'heroes.component.html',
styleUrls: ['heroes.component.css'],
directives: [HeroDetailComponent]
})
export class HeroesComponent implements OnInit {
heroes: Hero[];
selectedHero: Hero;
error: any;
addingHero: boolean;
constructor(private heroService:HeroService, private router:Router) {}
ngOnInit() {
this.getHeroes();
}
getHeroes() {
this.heroService.getHeroes().then(heroes => this.heroes = heroes);
}
onSelect(hero:Hero){
this.selectedHero = hero;
}
addHero(){
this.addingHero = true;
this.selectedHero = null;
}
close(savedHero:Hero){
this.addingHero = false;
if (savedHero) {
this.getHeroes();
}
}
deleteHero(deletedHero:Hero, event:any){
event.stopPropagation();
this.heroService.delete(deletedHero)
.then(response=>{
this.heroes = this.heroes.filter(hero => hero !== deletedHero);
if (this.selectedHero === deletedHero){
this.selectedHero = null;
}
})
.catch(error=>this.error = error);
}
gotoDetail(){
let link = ['/detail', this.selectedHero.id];
this.router.navigate(link);
}
}
|
d533b0e89415267700b54666ceb869e07d10991a
|
[
"Markdown",
"TypeScript"
] | 2
|
Markdown
|
Hareuhtee/angular2-io-tutorials
|
e4bbbd7a19ff4a3a87c2f145154d6a1adb1b4037
|
01e8936dcb1fe69be6bbbc759a7343caf119f13c
|
refs/heads/master
|
<repo_name>hariom900182/Simple-Crud-With-Auth-Angular<file_sep>/src/app/listing.service.ts
import { Injectable } from '@angular/core';
import { Signup } from "./models/signup";
import { Listing } from "./models/listing";
import { Broadcaster } from "./broadcaster";
import { StitchClientFactory } from 'mongodb-stitch';
@Injectable()
export class ListingService {
db: any;
appId:string;
stitchClientPromise:any;
public listings:any[] = [];
constructor( private broadcaster: Broadcaster) {
this.appId = 'angapp-zajle';
this.stitchClientPromise = StitchClientFactory.create(this.appId);
}
add(model: Listing,user: any)
{
this.stitchClientPromise .then(client => {
const db = client.service('mongodb', 'mongodb-atlas').db('AngApp');
client.login().then(() =>
db.collection('story').insertOne({owner_id: client.authedId(),title:model.title,detail:model.detail,email:user.email,status:true})
).then(docs => {
this.readForUser(user);
}).catch(err => {
this.broadcaster.broadcast('error', 'some message');
});
});
}
update(model: any,user: any)
{
console.log("update", model);
this.stitchClientPromise .then(client => {
const db = client.service('mongodb', 'mongodb-atlas').db('AngApp');
client.login().then(() =>
db.collection('story').updateOne({ _id: model._id },{ $set: {title:model.title,detail:model.detail}} )
).then(docs => {
this.readForUser(user);
}).catch(err => {
this.broadcaster.broadcast('error', 'some message');
});
});
}
delete(model: any,user: any)
{
this.stitchClientPromise .then(client => {
const db = client.service('mongodb', 'mongodb-atlas').db('AngApp');
client.login().then(() =>
db.collection('story').updateOne({ _id: model._id },{ $set: {status:false}} )
).then(docs => {
this.readForUser(user);
}).catch(err => {
this.broadcaster.broadcast('error', 'some message');
});
});
}
readAll()
{
this.stitchClientPromise .then(client => {
const db = client.service('mongodb', 'mongodb-atlas').db('AngApp');
client.login().then(() =>
db.collection('story').find({status:true}).execute()
).then(docs => {
if(docs)
this.listings = docs
else
this.listings = [];
this.broadcaster.broadcast('reload', docs);
}).catch(err => {
this.broadcaster.broadcast('error', 'some message');
});
});
}
readForUser(user:any)
{
console.log("locals" ,user);
this.stitchClientPromise .then(client => {
const db = client.service('mongodb', 'mongodb-atlas').db('AngApp');
client.login().then(() =>
db.collection('story').find({email:user.email,status:true}).execute()
).then(docs => {
if(docs)
this.listings = docs
else
this.listings = [];
this.broadcaster.broadcast('reload', docs);
}).catch(err => {
this.broadcaster.broadcast('error', 'some message');
});
});
}
getListing()
{
return this.listings;
}
}
<file_sep>/src/app/models/listing.ts
export class Listing
{
public id: any;
public title:string;
public detail:string;
public email:string;
public status:boolean;
constructor() {
this.id = null;
this.title = "";
this.detail= "";
this.email = "";
this.status = true;
}
};<file_sep>/src/app/models/signup.ts
export class Signup
{
public username:string;
public email:string;
public password:string;
public repeatPassword:string;
constructor() {
this.username= "";
this.email = "";
this.password= "";
this.repeatPassword= "";
}
};<file_sep>/src/app/dashboard/dashboard.component.ts
import { Component, OnInit } from '@angular/core';
import { FormControl, FormBuilder, Validators,ReactiveFormsModule } from '@angular/forms';
import { Broadcaster } from "../broadcaster";
import { Listing } from "../models/listing";
import { ListingService } from "../listing.service";
import {Router} from '@angular/router';
import { LocalStorageService } from 'angular-2-local-storage';
import { listener } from '@angular/core/src/render3/instructions';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css'],
providers: [
Listing,
ListingService
]
})
export class DashboardComponent implements OnInit {
public valid: boolean;
public listing: Listing;
public data: any;
public user:any;
public addOrUpdate:boolean;
public selectedListItem: any;
listingForm = this.formBuilder.group({
title: ['', Validators.required],
detail: ['', Validators.required],
});
constructor(private formBuilder:FormBuilder, private router: Router ,private broadcaster: Broadcaster, private listingService: ListingService, private localStorageService: LocalStorageService) {
this.valid = false;
this.listing = new Listing();
this.addOrUpdate = false;
this.registerStringBroadcast()
}
ngOnInit() {
this.setAuth();
this.read();
}
setAuth()
{
this.user = this.localStorageService.get("currentUser");
if(!this.user)
{
this.router.navigate(["/"]);
}
}
submit()
{
this.valid = false;
this.listing.title = this.listingForm.controls.title.value;
this.listing.detail = this.listingForm.controls.detail.value;
if(this.addOrUpdate == false)
var res = this.listingService.add(this.listing,this.user);
else
{
this.selectedListItem.title = this.listingForm.controls.title.value;
this.selectedListItem.detail = this.listingForm.controls.detail.value;
var res = this.listingService.update(this.selectedListItem,this.user);
}
}
delete(listing:any)
{
console.log("delete");
var res = this.listingService.delete(listing,this.user);
}
addnew()
{
this.addOrUpdate = false;
this.listingForm.controls.title.setValue("");
this.listingForm.controls.detail.setValue("");
}
update(listing: any)
{
this.selectedListItem = listing;
this.addOrUpdate = true;
this.listingForm.controls.title.setValue(listing.title);
this.listingForm.controls.detail.setValue(listing.detail);
}
read()
{
this.listingService.readForUser(this.user);
}
registerStringBroadcast() {
this.broadcaster.on<string>('error')
.subscribe(message => {
this.valid = true;
});
this.broadcaster.on<any>('reload')
.subscribe(data => {
this.data = data;
this.listingForm = this.formBuilder.group({
title: ['', Validators.required],
detail: ['', Validators.required],
});
this.selectedListItem = null;
this.addOrUpdate = false;
});
}
}
<file_sep>/src/app/header/header.component.ts
import { Component,TemplateRef ,OnInit } from '@angular/core';
import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';
import { Broadcaster } from "../broadcaster";
import { LocalStorageService } from 'angular-2-local-storage';
import { FormControl, FormBuilder, Validators,ReactiveFormsModule } from '@angular/forms';
import {Router} from '@angular/router';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css'],
})
export class HeaderComponent implements OnInit {
modalRef: BsModalRef;
public modalFor="";
public isGuest = false;
public user: any;
successTemplate:any;
public filterText: string;
public filterForm = this.formBuilder.group({
filterText: ['', Validators.required],
});
constructor(private formBuilder:FormBuilder,private modalService: BsModalService, private router: Router, private broadcaster: Broadcaster, private localStorageService: LocalStorageService) {
this.filterText= "";
this.registerStringBroadcast();
this.setAuth();
}
ngOnInit() {
}
setAuth()
{
this.user = this.localStorageService.get("currentUser");
if(this.user)
{
this.isGuest = true;
}
else
{
this.isGuest = false;
}
}
signup(template: TemplateRef<any>) {
this.modalFor = "Signup";
this.successTemplate = template;
this.modalRef = this.modalService.show(template);
}
login(template: TemplateRef<any>) {
this.modalFor = "Login";
this.modalRef = this.modalService.show(template);
}
submit()
{
var filterText = this.filterForm.controls.filterText.value;
this.broadcaster.broadcast('filter',filterText);
}
logout() {
this.isGuest= false;
this.localStorageService.remove("currentUser");
this.router.navigate(["/"]);
}
registerStringBroadcast() {
this.broadcaster.on<string>('closeModal')
.subscribe(message => {
this.modalRef.hide();
if(this.modalFor == "Signup")
{
this.modalFor = "Success";
this.modalRef = this.modalService.show(this.successTemplate);
}
});
this.broadcaster.on<any>('userMenu')
.subscribe(user => {
this.setAuth();
});
}
}
<file_sep>/src/app/home/home.component.ts
import { Component, OnInit } from '@angular/core';
import { Broadcaster } from "../broadcaster";
import { Listing } from "../models/listing";
import { ListingService } from "../listing.service";
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
providers: [
Listing,
ListingService
]
})
export class HomeComponent implements OnInit {
public data: any;
public viewData: any;
private filter:string;
constructor(private broadcaster: Broadcaster, private listingService: ListingService) {
this.registerStringBroadcast()
}
ngOnInit() {
this.read();
}
read()
{
this.listingService.readAll();
}
applyFilter(msg:string)
{
console.log("ready to filter",msg);
if(msg && msg != "")
{
this.viewData =[];
this.data.forEach(d => {
if(d.title.toLowerCase().indexOf(msg.toLowerCase()) != -1 || d.detail.toLowerCase().indexOf(msg.toLowerCase()) != -1)
{
this.viewData.push(d);
}
});
}
else
{
this.viewData = this.data;
}
}
registerStringBroadcast() {
this.broadcaster.on<any>('reload')
.subscribe(data => {
console.log(" data reload");
this.data = data;
this.applyFilter("");
});
this.broadcaster.on<string>('filter')
.subscribe(message => {
console.log(" data reload");
this.applyFilter(message);
});
}
}
<file_sep>/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ModalModule } from 'ngx-bootstrap';
import { FormsModule, FormBuilder, Validators,ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { LogiinComponent } from './logiin/logiin.component';
import { SignupComponent } from './signup/signup.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { LocalStorageModule } from 'angular-2-local-storage';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
export const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'dashboard', component: DashboardComponent },
];
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
LogiinComponent,
SignupComponent,
DashboardComponent,
HomeComponent
],
imports: [
BrowserModule,
ModalModule,
ModalModule.forRoot(),
FormsModule,
ReactiveFormsModule,
LocalStorageModule.withConfig({
prefix: 'angApp',
storageType: 'localStorage'
}),
RouterModule.forRoot(routes)
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/src/app/user.service.ts
import { Injectable } from '@angular/core';
import { Signup } from "./models/signup";
import { Login } from "./models/login";
import { Broadcaster } from "./broadcaster";
import { StitchClientFactory } from 'mongodb-stitch';
import { LocalStorageService } from 'angular-2-local-storage';
@Injectable()
export class UserService {
db: any;
appId:string;
stitchClientPromise:any;
constructor( private broadcaster: Broadcaster, private localStorageService: LocalStorageService) {
this.appId = 'angapp-zajle';
this.stitchClientPromise = StitchClientFactory.create(this.appId);
}
signup(model: Signup)
{
this.stitchClientPromise .then(client => {
const db = client.service('mongodb', 'mongodb-atlas').db('AngApp');
client.login().then(() =>
db.collection('user').insertOne({owner_id: client.authedId(),email:model.email,username:model.username,password:<PASSWORD>})
).then(docs => {
if(docs)
{
this.broadcaster.broadcast('closeModal', 'some message');
}
else
{
this.broadcaster.broadcast('closeModal', 'some message');
}
}).catch(err => {
this.broadcaster.broadcast('error', 'some message');
});
});
}
login(model:Login)
{
this.stitchClientPromise .then(client => {
const db = client.service('mongodb', 'mongodb-atlas').db('AngApp');
client.login().then(() =>
db.collection('user').findOne({email:model.email})
).then(docs => {
if(docs)
{
this.localStorageService.add("currentUser",{email:docs.email,username:docs.username});
this.broadcaster.broadcast('userMenu', {email:docs.email,username:docs.username});
this.broadcaster.broadcast('closeModal', 'some message');
}
else
this.broadcaster.broadcast('error', 'some message');
}).catch(err => {
this.broadcaster.broadcast('error', 'some message');
});
});
}
}
<file_sep>/src/app/signup/signup.component.ts
import { Component, OnInit } from '@angular/core';
import { FormControl, FormBuilder, Validators,ReactiveFormsModule } from '@angular/forms';
import { Signup } from "../models/signup";
import { UserService } from "../user.service";
import { Broadcaster } from "../broadcaster";
@Component({
selector: 'app-signup',
templateUrl: './signup.component.html',
styleUrls: ['./signup.component.css'],
providers: [
Signup,
UserService
]
})
export class SignupComponent implements OnInit {
private user:Signup;
public valid: boolean;
signupForm = this.formBuilder.group({
username: ['', Validators.required],
email: ['', Validators.required],
password: ['', Validators.required]
});
constructor(private formBuilder:FormBuilder, private userService: UserService, private broadcaster: Broadcaster) {
this.valid = false;
this.registerStringBroadcast();
}
ngOnInit() {
}
submit()
{
this.valid = false;
this.user = new Signup();
this.user.email = this.signupForm.controls.email.value;
this.user.username = this.signupForm.controls.username.value;
this.user.password = this.signupForm.controls.password.value;
var res = this.userService.signup(this.user);
}
registerStringBroadcast() {
this.broadcaster.on<string>('error')
.subscribe(message => {
this.valid = true;
});
}
}
|
960c015a9473b7702258e9c9aad5b75c33e118fc
|
[
"TypeScript"
] | 9
|
TypeScript
|
hariom900182/Simple-Crud-With-Auth-Angular
|
ff2444577502df87086ad9ccea890932567a7154
|
818aab544cdd0025d54e8a6bbb83209acc36c5b9
|
refs/heads/master
|
<repo_name>Appolloyon/Shellfish<file_sep>/makeblastdbProt.sh
#!/bin/bash
##This is an example script MAKEBLASTDB.sh
##These commands set up the Grid Environment for your job:
#PBS -N makeblastdb_Prot
#PBS -l nodes=1,walltime=12:00:00
#PBS -q batch
#PBS -M <EMAIL>
#PBS -m abe
##Print the Host name of Node
echo "Hostname is " $HOSTNAME
##print the time and date
##Print working Direcitory
pwd
##Print Date
date
# Automatically find data file to use
DATAFILE=`ls /home/bioinfor1/cklinger/MAKEBLASTDB/*.fa`
echo "Using query file $DATAFILE"
##send MAKEBLASTDB command to Cluster nodes
makeblastdb -in "$DATAFILE" -dbtype prot
##End Script
<file_sep>/splitfasta.sh
#!/bin/bash
##This is an example script example.sh
##These commands set up the Grid Environment for your job:
#PBS -N splitfasta
#PBS -l nodes=bioinfor3,walltime=120:00:00
#PBS -q batch
#PBS -M <EMAIL>
#PBS -m abe
#print the time and date
echo $HOST
export HHLIB=/usr/lib/hh/lib
date
#run the HHsearch program
splitfasta.pl /home/bioinfor1/cklinger/TgonDB/Tgondii.fa -o /home/bioinfor1/cklinger/TgonDB/ | mv ~/*.seq ~/TgonDB
#print the time and date again
date
<file_sep>/RAxML.sh
#!/bin/bash
##This is a RAxML script
##These commands set up the Grid Environment for your job:
#PBS -N RAxML
#PBS -l nodes=1,walltime=120:00:00
#PBS -q default
#PBS -M <EMAIL>
#PBS -m abe
# Concerning the above code,
# Author: Unknown
#######################################
# Concerning the remainder of this file,
# Author: <NAME>
# Created: December 11, 2014
# Info helpful for debugging
echo "Hostname is " $HOSTNAME
pwd
date
QUERY_DIR=/home/cklinger/RAxML
now=$(date +"%Y%m%d")
# Automatically find query files to use
QUERYFILES=`ls $QUERY_DIR/*.phy`
echo "Using query files:"
echo "$QUERYFILES"
echo
for query in $QUERYFILES; do
##send RAxML command to Cluster nodes
raxmlHPC-HYBRID-SSE3 -n result -s "$query" -m PROTCATLG -N 100 -c 25 -p 12345 -b 12345 -T 10
done
##End Script
<file_sep>/README.md
Shellfish
=========
Scripts for remote bioinformatics execution
<file_sep>/hhbatch13.sh
#! /bin/bash
# Author: <NAME>
# Last Modified: May 31, 2012
#PBS -N HHbatch_13
#PBS -l nodes=bioinfor1,walltime=720:00:00
#PBS -q batch
#PBS -M <EMAIL>
#PBS -m abe
#print the time and date
echo $HOST
export HHLIB=/usr/lib/hh/lib
# Prepend for output filenames
OUTPUTFILE='output'
QUERYDIR=/home/bioinfor1/cklinger/HHsearch
date
echo $HOSTNAME
echo "Starting batch of hmm searches"
# Automatically find afa file to use
AFAFILE=`ls $QUERYDIR/*.afa`
echo "Using afa files:"
echo "$AFAFILE"
echo
for query in $AFAFILE; do
q_short_name=$(basename "$query")
q_short_name="${q_short_name%.*}"
mkdir -p /home/bioinfor1/cklinger/HH_Output3
hhsearch -i "$query" -d /home/bioinfor1/cklinger/UniProt2/uniprot20_2013_03_hhm_db -o "HH_Output3/${q_short_name}.outfile.txt"
done
done
##End Script
<file_sep>/HMMbatchsearchN.sh
#! /bin/bash
# Author: <NAME>
# Updates by: <NAME>
# Last Modified: November 9, 2014
# PBS -l nodes=1,walltime=120:00:00
# Prepend for output filenames
OUTPUTFILE='output'
FASTADIR=/home/cklinger/batch_search_database
QUERYDIR=/home/cklinger/batch_search_queries
now=$(date +"%Y%m%d")
date
echo $HOSTNAME
echo "Starting batch of hmm searches"
# Automatically find hmm file to use
HMMFILE=`ls $QUERYDIR/*.hmm`
echo "Using hmm files:"
echo "$HMMFILE"
echo
# Automatically find data files to use
DATAFILE=`ls $FASTADIR/*.fa`
echo "Using data files:"
echo "$DATAFILE"
echo
for file in $DATAFILE; do
db_short_name=$(basename "$file")
db_short_name="${db_short_name%.*}"
for query in $HMMFILE; do
q_short_name=$(basename "$query")
q_short_name="${q_short_name%.*}"
mkdir -p /home/cklinger/"HMMer_$q_short_name"
hmmsearch -E 0.5 -o "HMMer_$q_short_name/${q_short_name}_${db_short_name}_${now}.outfile.txt" "$query" "$file"
done
done
##End Script
<file_sep>/rblastpg2.sh
#!/bin/bash
##This is a BLAST script
##These commands set up the Grid Environment for your job:
#pbs -n jobname
#pbs -L NODES=1,WALLTIME=60:00:00
#pbs -Q BATCH
#pbs -m email
#pbs -M ABE
# Concerning the above code,
# Author: Unknown
#######################################
# Concerning the remainder of this file,
# Author: <NAME>
# Author: <NAME>
# Updates by: <NAME>
# Last Modified: November 10, 2014
# Info helpful for debugging
echo "Hostname is " $HOSTNAME
pwd
date
QUERY_SUB_DIR=/home/cklinger/BLAST_SEARCHES/rblastpqueries
DATABASE_SUB_DIR=/home/cklinger/BLAST_SEARCHES/rblastpdatabase
BLAST_OPTIONS="-word_size 3 -gapopen 11 -gapextend 1 -evalue 0.1"
now=$(date +"%Y%m%d")
# Automatically find query files to use
QUERYFILES=`ls $QUERY_SUB_DIR/*.fa`
echo "Using query files:"
echo "$QUERYFILES"
echo
# Automatically find data files to use
DATAFILES=`ls $DATABASE_SUB_DIR/*.fa`
echo "Using data files:"
echo "$DATAFILES"
echo
for database in $DATAFILES; do
db_short_name=$(basename "$database")
db_short_name="${db_short_name%.*}"
for query in $QUERYFILES; do
q_short_name=$(basename "$query")
q_short_name="${q_short_name%.*}"
mkdir -p /home/cklinger/"rblastp_$db_short_name"
##send BLAST command to Cluster nodes
blastp -query "$query" -db "$database" -out "rblastp_$db_short_name/${q_short_name}_${db_short_name}_${now}.outfile.txt" $BLAST_OPTIONS
done
done
##End Script
<file_sep>/multithread_2.sh
#!/bin/bash
##This is an example script example.sh
##These commands set up the Grid Environment for your job:
#PBS -N multithread2
#PBS -l nodes=bioinfor3,walltime=4800:00:00
#PBS -q batch
#PBS -M <EMAIL>
#PBS -m abe
#print the time and date
echo $HOST
export HHLIB=/usr/lib/hh/lib
date
#run the HHsearch program
multithread.pl '/home/bioinfor1/cklinger/TgonDB2/*.seq' 'hhblits -i $file -n 2 -d /home/bioinfor1/cklinger/UniProt2/uniprot20_2013_03 -oa3m $name.a3m' -cpu 16
#print the time and date again
date
|
8adce37eaedaccec7592652485b5791f9eebadef
|
[
"Markdown",
"Shell"
] | 8
|
Shell
|
Appolloyon/Shellfish
|
b44f99601517d4d34d77a21d3fc248a6d0d62806
|
61f7746e9db6f25fefb3b74f1d1e7c760f9ce1e9
|
refs/heads/master
|
<file_sep>import numpy as np
import cv2
import pickle
from moviepy.editor import VideoFileClip
from functools import partial
def binary(img, s_thresh=(115, 255), l_thresh=(84, 255), sx_thresh=(25, 100)):
"""This function get an input image and return a binary images with
lane lines detected.
The saturation, lightness, gradient thresholds can be customized
for experimentation. The default values are the one I found the best
choice for the images at hand"""
# copy the input image to avoid changing it
img = np.copy(img)
# convert to HLS color space and separate the lightness
# and saturation channels
hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HLS).astype(np.float)
l_channel = hsv[:, :, 1]
s_channel = hsv[:, :, 2]
# apply sobel filter in the x direction
sobelx = cv2.Sobel(l_channel, cv2.CV_64F, 1, 0)
# get the absolute value because also negative gradients represents
# vertical changes
abs_sobelx = np.absolute(sobelx)
# redistribute values on the entire 0..255 range
scaled_sobel = np.uint8(255 * abs_sobelx / np.max(abs_sobelx))
# threshold the x gradient
sxbinary = np.zeros_like(scaled_sobel)
sxbinary[
(scaled_sobel >= sx_thresh[0]) & (scaled_sobel <= sx_thresh[1])] = 255
# threshold the saturation channel
s_binary = np.zeros_like(s_channel)
s_binary[(s_channel >= s_thresh[0]) & (s_channel <= s_thresh[1])] = 255
# convert to 8 bit
s_binary = s_binary.astype(np.uint8)
# threshold the lightness channel
l_binary = np.zeros_like(l_channel)
l_binary[(l_channel >= l_thresh[0]) & (l_channel <= l_thresh[1])] = 255
l_binary = l_binary.astype(np.uint8)
# convert to binary image where the lightess AND saturation bits have to be
# both present to contribute, together with the gradient on x axes
binary = np.zeros_like(sxbinary)
binary[((l_binary == 255) & (s_binary == 255) | (sxbinary == 255))] = 255
binary = np.dstack((binary, binary, binary))
# return the images
return binary
def change_perspective(corners):
"""Change perspective on the input image, that has to be
undistorted. The corners are sent in the following order:
bottom left, top left, top right, bottom right"""
# create the source region
src = np.float32(corners)
# unpack the corners
bl, tl, tr, br = corners
# adjust top left and top right corner to
# form a rectangle, to be used as destination
tl = (bl[0], 0)
tr = (br[0], 0)
# create the destination rectangle
dst = np.float32([bl, tl, tr, br])
# calculate the matrix to transform from src to dst
M = cv2.getPerspectiveTransform(src, dst)
# and from dst to src
Minv = cv2.getPerspectiveTransform(dst, src)
return M, Minv
def slide_window(image, startx, nonzerox=None, nonzeroy=None, nwindows=9):
"""It slide a window from the bottom, with startx x coordinate.
It returns the indices of the points belonging to the line"""
if nonzerox is None:
# x, y of all nonzero pixels in the image
nonzero = image.nonzero()
nonzeroy = np.array(nonzero[0])
nonzerox = np.array(nonzero[1])
# calculate the height of the windows
window_height = np.int(image.shape[0] / nwindows)
# current positions to be updated for each window
currentx = startx
# set the width of the windows +/- margin
margin = 100
# set minimum number of pixels found to recenter window
minpix = 50
# create empty lists to receive left and right lane pixel indices
lane_inds = []
# step through the windows one by one
for window in range(nwindows):
# calculate window boundaries in x and y (and right and left)
win_y_low = image.shape[0] - (window + 1) * window_height
win_y_high = image.shape[0] - window * window_height
win_x_low = currentx - margin
win_x_high = currentx + margin
# identify the nonzero pixels in x and y within the window
good_inds = ((nonzeroy >= win_y_low) &
(nonzeroy < win_y_high) &
(nonzerox >= win_x_low) &
(nonzerox < win_x_high)).nonzero()[0]
# append these indices to the lists
lane_inds.append(good_inds)
# if you found > minpix pixels, re-center next window
# on their mean position
if len(good_inds) > minpix:
currentx = np.int(np.mean(nonzerox[good_inds]))
# concatenate the arrays of indices
lane_inds = np.concatenate(lane_inds)
return lane_inds
def calculate_curvature_radius(leftx, lefty, rightx, righty):
"""Calculate the curvature radius, but in the world coordinate"""
ym_per_pix = 30 / 720 # meters per pixel in y dimension
xm_per_pix = 3.7 / 700 # meters per pixel in x dimension
y_eval = 720 * ym_per_pix # eval radius at the bottom of the image
# fit new polynomials to x,y in world space
left_fit_cr = np.polyfit(lefty * ym_per_pix, leftx * xm_per_pix, 2)
right_fit_cr = np.polyfit(righty * ym_per_pix, rightx * xm_per_pix, 2)
# calculate the new radii of curvature
left_curve_radius = ((1 + (2*left_fit_cr[0]*y_eval + left_fit_cr[1])**2)**1.5) / np.absolute(2*left_fit_cr[0])
right_curve_radius = ((1 + (2*right_fit_cr[0]*y_eval + right_fit_cr[1])**2)**1.5) / np.absolute(2*right_fit_cr[0])
# calculate offset, difference between center of the car and center of
# the road
# left and right lane x (in meter) calculated at the bottom of the image
left_x = left_fit_cr[0] * y_eval ** 2 + left_fit_cr[1] * y_eval + left_fit_cr[2]
right_x = right_fit_cr[0] * y_eval ** 2 + right_fit_cr[1] * y_eval + right_fit_cr[2]
# the width of the lane, the center of the car, you can calculate the
# offset too
width = right_x - left_x
car_center = 640 * xm_per_pix
offset = car_center - (width / 2 + left_x)
return left_curve_radius, right_curve_radius, offset
def find_lines(image, p_left_fit=None, p_right_fit=None):
"""Returns the lane lines as function fit, given a binary image. It uses
the previous fit to speed up the calculations"""
# if it a 3 channel binary image, make it one channel
if len(image.shape) == 3:
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# x, y of all nonzero pixels in the image
nonzero = image.nonzero()
nonzeroy = np.array(nonzero[0])
nonzerox = np.array(nonzero[1])
if p_left_fit is None:
# no previous frame where to start, let's use the sliding
# window method
# take a histogram of the bottom half of the image
histogram = np.sum(image[int(image.shape[0] / 2):, :], axis=0)
# find the peak of the left and right halves of the histogram
# these will be the starting point for the left and right lines
midpoint = np.int(histogram.shape[0] / 2)
leftx_base = np.argmax(histogram[:midpoint])
rightx_base = np.argmax(histogram[midpoint:]) + midpoint
left_lane_inds = slide_window(image, leftx_base, nonzerox, nonzeroy)
right_lane_inds = slide_window(image, rightx_base, nonzerox, nonzeroy)
else:
# we have a fit from the previous frame, so we use it to calculate
# the points in the +/- margin neighborhood
margin = 100
left_lane_inds = ((nonzerox > (p_left_fit[0] * (nonzeroy ** 2) + p_left_fit[1] * nonzeroy + p_left_fit[2] - margin))
& (nonzerox < (p_left_fit[0] * (nonzeroy ** 2) + p_left_fit[1] * nonzeroy + p_left_fit[2] + margin)))
right_lane_inds = ((nonzerox > (p_right_fit[0] * (nonzeroy ** 2) + p_right_fit[1] * nonzeroy + p_right_fit[2] - margin)) &
(nonzerox < (p_right_fit[0] * (nonzeroy ** 2) + p_right_fit[1] * nonzeroy + p_right_fit[2] + margin)))
# extract left and right line pixel positions
leftx = nonzerox[left_lane_inds]
lefty = nonzeroy[left_lane_inds]
rightx = nonzerox[right_lane_inds]
righty = nonzeroy[right_lane_inds]
# calculate the curvature of the lanes
lc, rc, offset = calculate_curvature_radius(leftx, lefty, rightx, righty)
# fit a second order polynomial to each
left_fit = np.polyfit(lefty, leftx, 2)
right_fit = np.polyfit(righty, rightx, 2)
return left_fit, right_fit, lc, rc, offset
def static_vars(**kwargs):
def decorate(func):
for k in kwargs:
setattr(func, k, kwargs[k])
return func
return decorate
@static_vars(left_fit=None, right_fit=None)
def _pipeline(img, cmx, dist):
# un-distort the frame using camera matrix and distortion coeffs
undistort_img = cv2.undistort(img, cmx, dist, None, cmx)
# get the binary image
bin_img = binary(undistort_img)
# define the trapezoid which encloses the road ahead
corners = [(277, 670), (585, 457), (702, 457), (1028, 670)]
# get the matrix to change perspective and the one to reverse
M, Minv = change_perspective(corners)
# image shape needed
img_shape = (img.shape[1], img.shape[0])
# warp the frame
binary_warped = cv2.warpPerspective(bin_img, M, img_shape, flags=cv2.INTER_LINEAR)
# search for the lines in the frame
_pipeline.left_fit, _pipeline.right_fit, lc, rc, offset = \
find_lines(binary_warped,
_pipeline.left_fit,
_pipeline.right_fit)
# output image
layer = np.zeros_like(binary_warped).astype(np.uint8)
# generate x and y values for plotting
ploty = np.linspace(binary_warped.shape[0] - 1, 0, 30)
left_fitx = _pipeline.left_fit[0] * ploty ** 2 + _pipeline.left_fit[1] * ploty + _pipeline.left_fit[2]
right_fitx = _pipeline.right_fit[0] * ploty ** 2 + _pipeline.right_fit[1] * ploty + _pipeline.right_fit[2]
# zip x and y's to generate array of points
left_pts = np.dstack((left_fitx, ploty))
right_pts = np.flip(np.dstack((right_fitx, ploty)), axis=1)
# create the polygon.
polygon = np.array(np.concatenate((left_pts, right_pts), axis=1), dtype=np.int32)
# draw the polygon in the warped space
cv2.fillPoly(layer, polygon, (0, 255, 0))
# unwarp and add to the original image
layer_unwarp = cv2.warpPerspective(layer, Minv, img_shape, flags=cv2.INTER_LINEAR)
# write curvature and offset
cv2.putText(img, "left radius: {0:9.2f} m".format(lc),
(100, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255))
cv2.putText(img,
"right radius:{0:9.2f} m".format(rc),
(100, 130), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255))
cv2.putText(img,
"offset: {0:9.2f} m".format(offset),
(100, 160), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255))
return cv2.addWeighted(img, 1, layer_unwarp, 0.3, 0)
if __name__ == '__main__':
# load camera matrix
with open(r"cmx.p", "rb") as cmx_file:
cmx = pickle.load(cmx_file)
# load distortion coeffs
with open(r"dist.p", "rb") as dist_file:
dist = pickle.load(dist_file)
# partial application on _pipeline function, so I can
# send in the camera matrix and distortion coeffs without
# relying on globals.
pipeline = partial(_pipeline, cmx=cmx, dist=dist)
# open the clip
clip = VideoFileClip('project_video.mp4')
# process the clip
processed_clip = clip.fl_image(pipeline)
# finally save the clip
processed_clip.write_videofile("project_video.out.mp4", audio=False)
<file_sep>## Writeup
**Advanced Lane Finding Project**
The goals / steps of this project are the following:
* Compute the camera calibration matrix and distortion coefficients given a set of chessboard images.
* Apply a distortion correction to raw images.
* Use color transforms, gradients, etc., to create a thresholded binary image.
* Apply a perspective transform to rectify binary image ("birds-eye view").
* Detect lane pixels and fit to find the lane boundary.
* Determine the curvature of the lane and vehicle position with respect to center.
* Warp the detected lane boundaries back onto the original image.
* Output visual display of the lane boundaries and numerical estimation of lane curvature and vehicle position.
[//]: # (Image References)
[image1]: ./output_images/undistort.png "Undistorted"
[image2]: ./output_images/warped.png "Transformed"
[image3]: ./output_images/util.png "Utility"
[image4]: ./output_images/warped2.png "Warp Example"
[image5]: ./examples/color_fit_lines.jpg "Fit Visual"
[image6]: ./output_images/snapshot.png "Output"
[video1]: ./project_video.mp4 "Video"
## [Rubric](https://review.udacity.com/#!/rubrics/571/view) Points
### Here I will consider the rubric points individually and describe how I addressed each point in my implementation.
---
### Camera Calibration
#### 1. Briefly state how you computed the camera matrix and distortion coefficients. Provide an example of a distortion corrected calibration image.
The code for this step is contained in the notebook `part1_calibration.ipynb`
I start by preparing "object points", which will be the (x, y, z) coordinates of the chessboard corners in the world. Here I am assuming the chessboard is fixed on the (x, y) plane at z=0, such that the object points are the same for each calibration image. Thus, `objp` is just a replicated array of coordinates, and `objpoints` will be appended with a copy of it every time I successfully detect all chessboard corners in a test image. `imgpoints` will be appended with the (x, y) pixel position of each of the corners in the image plane with each successful chessboard detection.
I then used the output `objpoints` and `imgpoints` to compute the camera calibration and distortion coefficients using the `cv2.calibrateCamera()` function. I applied this distortion correction to the test image using the `cv2.undistort()` function and obtained this result:
![alt text][image1]
### Pipeline (single images)
#### 1. Provide an example of a distortion-corrected image.
In the same notebook I also test the perspective change, by reprojecting the corner of the chessboard to a plane parallel to the camera plane. Here's the result
![alt text][image2]
#### 2. Describe how (and identify where in your code) you used color transforms, gradients or other methods to create a thresholded binary image. Provide an example of a binary image result.
I used a combination of lightness, saturation and gradient thresholds to generate a binary image. To decide about the most effective threshold values, I created an quick a dirty app, `test1.py`, with sliders to adjust the thresholds and see the change runtime.
![alt text][image3]
#### 3. Describe how (and identify where in your code) you performed a perspective transform and provide an example of a transformed image.
The code for my perspective transform includes a function called `change_perspective()`, which appears in file `part2_test_pipeline.ipynb`. This function takes as inputs an image (`img`), as well as corners of the trapezoid to project. The destination points are just calculated based on the source input. I chose the hardcode the destination points in the following manner:
```python
corners = [(190, 720), (589, 457), (698, 457), (1145, 720)]
```
This resulted in the following source and destination points:
| Source | Destination |
|:-------------:|:------------:|
| 190, 720 | 190, 720 |
| 589, 457 | 589, 0 |
| 698, 457 | 698, 0 |
| 1145, 720 | 1145, 720 |
I verified that my perspective transform was working as expected by drawing the `src` and `dst` points onto a test image and its warped counterpart to verify that the lines appear parallel in the warped image.
![alt text][image4]
#### 4. Describe how (and identify where in your code) you identified lane-line pixels and fit their positions with a polynomial?
Then I did some other stuff and fit my lane lines with a 2nd order polynomial kinda like this:
![alt text][image5]
#### 5. Describe how (and identify where in your code) you calculated the radius of curvature of the lane and the position of the vehicle with respect to center.
I did this in lines # through # in my code in `my_other_file.py`
#### 6. Provide an example image of your result plotted back down onto the road such that the lane area is identified clearly.
I implemented this step in the notebook `part3_video_processing.ipynb` in the function `calculate_curvature_radius` (5th cell). The code is basically the one from the lessons, not invented here. Here is an example of my result on a test image:
![alt text][image6]
---
### Pipeline (video)
#### 1. Provide a link to your final video output. Your pipeline should perform reasonably well on the entire project video (wobbly lines are ok but no catastrophic failures that would cause the car to drive off the road!).
Here's a [link to my video result](./project_video.out.mp4)
---
### Discussion
#### 1. Briefly discuss any problems / issues you faced in your implementation of this project. Where will your pipeline likely fail? What could you do to make it more robust?
The project was challenging because of all the moving parts. The most difficult stuff was all the errors I had to face due to shape mismatch in images and in arrays. For example, when creating an array of points for `cv2.polyfill`, I struggle to come up with working code (concatenate on the second axe otherwise you have two polygons, and stuff like that)
Another difficult part was to come up with a good binary image. At a certain point I decided to create an app with sliders to accelerate the experiments.
Unfortunately due to lack of time I could not tackle the challenges.
<file_sep>import cv2
import numpy as np
import sys
this = sys.modules[__name__]
min, max, min1, max1, min2, max2 = 0, 0, 0, 0, 0, 0
image = np.empty((720, 1280, 3))
window_name = ''
def abs_sobel_thresh(img, orient='x', sobel_kernel=3, thresh_min=0, thresh_max=255):
# convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# apply x or y gradient with the OpenCV Sobel() function
# and take the absolute value
if orient == 'x':
abs_sobel = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel))
if orient == 'y':
abs_sobel = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel))
# rescale back to 8 bit integer
scaled_sobel = np.uint8(255 * abs_sobel / np.max(abs_sobel))
# create a copy and apply the threshold
binary_output = np.zeros_like(scaled_sobel)
# here I'm using inclusive (>=, <=) thresholds, but exclusive is ok too
binary_output[
(scaled_sobel >= thresh_min) & (scaled_sobel <= thresh_max)] = 255
# Return the result
return binary_output
# Define a function that applies Sobel x and y,
# then computes the direction of the gradient
# and applies a threshold.
def dir_threshold(img, sobel_kernel=3, thresh=(0, np.pi / 2)):
# grayscale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# calculate the x and y gradients
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)
# take the absolute value of the gradient direction,
# apply a threshold, and create a binary image result
absgraddir = np.arctan2(np.absolute(sobely), np.absolute(sobelx))
# convert to 8bit int
absgraddir = absgraddir.astype(np.uint8)
binary_output = np.zeros_like(absgraddir)
binary_output[(absgraddir >= thresh[0]) & (absgraddir <= thresh[1])] = 255
# return the binary image
return binary_output
# Define a function that applies Sobel x and y,
# then computes the magnitude of the gradient
# and applies a threshold
def mag_thresh(img, sobel_kernel=3, mag_thresh=(0, 255)):
# convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# take both Sobel x and y gradients
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)
# calculate the gradient magnitude
gradmag = np.sqrt(sobelx ** 2 + sobely ** 2)
# rescale to 8 bit
scale_factor = np.max(gradmag) / 255
gradmag = (gradmag / scale_factor).astype(np.uint8)
# Create a binary image of ones where threshold is met, zeros otherwise
binary_output = np.zeros_like(gradmag)
binary_output[(gradmag >= mag_thresh[0]) & (gradmag <= mag_thresh[1])] = 255
# Return the binary image
return binary_output
def pipeline(img, s_thresh=(115, 255), l_thresh=(25, 100), sx_thresh=(25, 100)):
# copy the input image to avoid changing it
img = np.copy(img)
# convert to HLS color space and separate the lightness
# and saturation channels
hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HLS).astype(np.float)
l_channel = hsv[:, :, 1]
s_channel = hsv[:, :, 2]
# apply sobel filter in the x direction
sobelx = cv2.Sobel(l_channel, cv2.CV_64F, 1, 0)
# get the absolute value because also negative gradients represents
# vertical changes
abs_sobelx = np.absolute(sobelx)
# redistribute values on the entire 0..255 range
scaled_sobel = np.uint8(255 * abs_sobelx / np.max(abs_sobelx))
# threshold the x gradient
sxbinary = np.zeros_like(scaled_sobel)
sxbinary[
(scaled_sobel >= sx_thresh[0]) & (scaled_sobel <= sx_thresh[1])] = 255
# threshold the saturation channel
s_binary = np.zeros_like(s_channel)
s_binary[(s_channel >= s_thresh[0]) & (s_channel <= s_thresh[1])] = 255
# convert to 8 bit
s_binary = s_binary.astype(np.uint8)
# threshold the lightness channel
l_binary = np.zeros_like(l_channel)
l_binary[(l_channel >= l_thresh[0]) & (l_channel <= l_thresh[1])] = 255
l_binary = l_binary.astype(np.uint8)
# stack each channel for debug
colors = np.dstack((sxbinary, s_binary, l_binary))
# convert to binary image where the lightess AND saturation bits have to be
# both present to contribute, together with the gradient on x axes
binary = np.zeros_like(sxbinary)
binary[((l_binary == 255) & (s_binary == 255) | (sxbinary == 255))] = 255
binary = np.dstack((binary, binary, binary))
# return the images
return colors, binary
def redraw():
'''
hls = cv2.cvtColor(image, cv2.COLOR_RGB2HLS)
H = hls[:, :, 0]
L = hls[:, :, 1]
S = hls[:, :, 2]
thresh = (100, 255)
bin = np.zeros_like(S)
bin[(S > thresh[0]) & (S <= thresh[1])] = 255
'''
'''
bin = abs_sobel_thresh(this.image, 'y', 3, this.min, this.max)
fmin = min/1000.0
fmax = max/1000.0
bin = dir_threshold(this.image, 3, (fmin, fmax))
'''
s_thresh = (this.min, this.max)
sx_thresh = (this.min1, this.max1)
l_thresh = (this.min2, this.max2)
_, binary = pipeline(image, s_thresh=s_thresh, l_thresh=l_thresh, sx_thresh=sx_thresh)
# convert from gray (one channel) to 3 channels, to have the
# hstack working
#imgc = cv2.cvtColor(bin, cv2.COLOR_GRAY2BGR)
both = np.hstack((image, binary))
# show in window
cv2.imshow(window_name, both)
# callback function
def set_max(value):
this.max = value
redraw()
# callback function
def set_min(value):
this.min = value
redraw()
def set_max1(value):
this.max1 = value
redraw()
# callback function
def set_min1(value):
this.min1 = value
redraw()
def set_max2(value):
this.max2 = value
redraw()
# callback function
def set_min2(value):
this.min2 = value
redraw()
def SimpleTrackbar():
# create the window
cv2.namedWindow(window_name)
# callback and trackbar
cv2.createTrackbar('sat min', window_name, 0, 255, set_min)
cv2.createTrackbar('sat max', window_name, 0, 255, set_max)
cv2.createTrackbar('grad min', window_name, 0, 255, set_min1)
cv2.createTrackbar('grad max', window_name, 0, 255, set_max1)
cv2.createTrackbar('light min', window_name, 0, 255, set_min2)
cv2.createTrackbar('light max', window_name, 0, 255, set_max2)
# initialise
redraw()
while True:
# if you press "ESC", it will return value 27
ch = cv2.waitKey(5)
if ch == 27:
break
cv2.destroyAllWindows()
if __name__ == '__main__':
image = cv2.imread('images/test5.jpg')
window_name = 'test'
SimpleTrackbar()
|
b2edaa76cb33efd7de0836f965251387b15b7bf3
|
[
"Markdown",
"Python"
] | 3
|
Python
|
kindoblue/CarND-Advanced-Lane-Lines
|
5ca1f841aefddb18dcf8ba841be6be905787405a
|
69ee1bdbc7a1283afcb9d8f5fcefc24c83a2ca99
|
refs/heads/master
|
<repo_name>cmodi-umich/django_ZipHR<file_sep>/airplanes/models.py
from django.db import models
import numpy as np
class Airplane(models.Model):
'''
Model for airplane
Fields include, plane name, id and number of passengers
'''
plane_name = models.CharField(max_length=50)
id = models.PositiveIntegerField(primary_key=True)
num_passengers = models.IntegerField()
def fuel_capacity(self):
'''
Calculate fuel capacity by multiplying id by 200 liters
'''
return 200 * self.id
def fuel_consumption(self):
'''
Find fuel consumption that comes from id by taking the log base 10 of the id multiplied by 0.8
Find fuel onsumption per passenger by multiplying 0.0002 by each passenger
Return sum of both
'''
fuel_c_with_id = round(np.log10(round(self.id * 0.8, 4)), 4)
fuel_c_of_pass = round(0.0002 * self.num_passengers, 4)
return fuel_c_with_id + fuel_c_of_pass
def max_minutes(self):
'''
Return fuel capacity divided by fuel consumption to see the maximum number of minutes the plane can fly
'''
fuel_cap = self.fuel_capacity()
return round(fuel_cap / self.fuel_consumption(), 4)
def __str__(self):
'''
String summary of the airplane model
'''
name = "Summary for Plane: {}".format(self.plane_name)
fuel = "Fuel Capacity: {}".format(self.fuel_capacity())
fuel_consumption_ = "Fuel Consumption: {} liters per minute".format(self.fuel_consumption())
max_mins = "Maximum Flying Time: {} minutes".format(self.max_minutes())
return "{}\n{}\n{}\n{}".format(name, fuel, fuel_consumption_, max_mins)
class Meta:
'''
Done to order the planes by id when they are presented
'''
ordering = ["id"]<file_sep>/airplanes/migrations/0001_initial.py
# Generated by Django 3.0.4 on 2020-03-19 22:18
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Airplane',
fields=[
('plane_name', models.CharField(max_length=50)),
('id', models.IntegerField(primary_key=True, serialize=False)),
('num_passengers', models.IntegerField()),
],
),
]
<file_sep>/airplanes/apps.py
from django.apps import AppConfig
# Just used to configure the airplane
class AirplanesConfig(AppConfig):
name = 'airplanes'
<file_sep>/airplanes/views.py
from django.http import HttpResponse
from .api import airplane_list, airplane_detail
from .models import Airplane
from django.shortcuts import render
def index(request):
'''
inputs list of all airplane objects and renders them into the index.html file to be displayed on the home page
'''
airplanes_list = Airplane.objects.all()
context = {'airplanes_list': airplanes_list}
return render(request, 'airplanes/index.html', context)<file_sep>/env/bin/django-admin.py
#!/Users/chintanmodi/Desktop/djano_zipHR/zip_airlines/env/bin/python3
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
<file_sep>/airplanes/migrations/0002_auto_20200319_2219.py
# Generated by Django 3.0.4 on 2020-03-19 22:19
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('airplanes', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='airplane',
options={'ordering': ['id']},
),
]
<file_sep>/airplanes/api.py
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from airplanes.models import Airplane
from airplanes.serializers import AirplaneSerializer
import json
class airplane_list(APIView):
"""
List all airplanes, or create a new airplane.
"""
serializer_class = AirplaneSerializer
def get(self, request, format=None):
'''
Get and list all airplanes using serializer to put into JSON format
'''
airplanes = Airplane.objects.all()
serializer = AirplaneSerializer(airplanes, many=True)
return Response(serializer.data)
def post(self, request, format=None):
'''
POST (Create) new airplane with data sepcified in the request and save it to the database
'''
serializer = AirplaneSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class airplane_detail(APIView):
"""
Retrieve, update or delete an airplane.
"""
serializer_class = AirplaneSerializer
def get_object(self, pk):
'''
Get airplane with specific id and return if it works
'''
try:
return Airplane.objects.get(pk=pk)
except Airplane.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
'''
Get airplane with specific id
Add fuel capacity, fual consumption and max minutes of fly time into the JSON that is returned
'''
airplane = self.get_object(pk)
serializer = AirplaneSerializer(airplane)
data = serializer.data
data['fuel_capacity'] = airplane.fuel_capacity()
data['fuel_consumption'] = airplane.fuel_consumption()
data['max_minutes'] = airplane.max_minutes()
return Response(data)
def put(self, request, pk, format=None):
'''
Get airplane with specific id
Edit its values if you would like
'''
airplane = self.get_object(pk)
serializer = AirplaneSerializer(airplane, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk, format=None):
'''
Get airplane with specific id, delete it
'''
airplane = self.get_object(pk)
airplane.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
<file_sep>/airplanes/serializers.py
from rest_framework import serializers
from airplanes.models import Airplane
class AirplaneSerializer(serializers.ModelSerializer):
'''
Serializer to turn model entries into JSON objects with fields: plane_name, id, num_passengers
'''
def validate_id(self, value):
if value > 10:
raise serializers.ValidationError("Max number of planes reached")
return value
def validate(self, data):
data = super().validate(data)
temp_plane = Airplane(id=data["id"], num_passengers=data["num_passengers"])
if temp_plane.max_minutes() > 20:
raise serializers.ValidationError("Too many passengers")
return data
class Meta:
model = Airplane
fields = ['plane_name', 'id', 'num_passengers']
<file_sep>/airplanes/tests.py
from django.test import TestCase
from .models import Airplane
class test_cases(TestCase):
def test_immidiates_1(self):
airplane = Airplane(plane_name="test", id=1, num_passengers=0)
self.assertEqual(airplane.plane_name, "test")
self.assertEqual(airplane.id, 1)
self.assertEqual(airplane.num_passengers, 0)
def test_immidiates_2(self):
airplane = Airplane(plane_name="Chintan", id=100, num_passengers=101)
self.assertEqual(airplane.plane_name, "Chintan")
self.assertEqual(airplane.id, 100)
self.assertEqual(airplane.num_passengers, 101)
def test_immidiates_3(self):
airplane = Airplane(plane_name="ZipAir", id=24, num_passengers=99)
self.assertEqual(airplane.plane_name, "ZipAir")
self.assertEqual(airplane.id, 24)
self.assertEqual(airplane.num_passengers, 99)
def test_fuel_1(self):
airplane = Airplane(plane_name="ZipAir", id=5, num_passengers=0)
self.assertEqual(airplane.fuel_capacity(), 1000)
def test_fuel_2(self): # edge case where id is 0
airplane = Airplane(plane_name="Chintan", id=0, num_passengers=101)
self.assertEqual(airplane.fuel_capacity(), 0)
def test_fuel_consumption_1(self): # whole number in log
airplane = Airplane(plane_name="ZipAir", id=5, num_passengers=0)
self.assertEqual(airplane.fuel_consumption(), 0.6021)
def test_fuel_consumption_2(self): # decimal in log
airplane = Airplane(plane_name="ZipAir", id=6, num_passengers=0)
self.assertEqual(airplane.fuel_consumption(), 0.6812)
def test_fuel_consumption_3(self): # adding in number of passengers
airplane = Airplane(plane_name="ZipAir", id=5, num_passengers=5)
self.assertNotEqual(airplane.fuel_consumption(), 0.6021) # make sure that we add number of passengers
self.assertEqual(airplane.fuel_consumption(), 0.6031)
def test_max_minutes_1(self):
airplane = Airplane(plane_name="ZipAir", id=5, num_passengers=0)
self.assertEqual(airplane.max_minutes(), 1660.8537)
def test_max_minutes_2(self):
airplane = Airplane(plane_name="ZipAir", id=5, num_passengers=5) # with passengers
self.assertEqual(airplane.max_minutes(), 1658.0998)
<file_sep>/zip_airlines/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('airplanes.urls')), # redirect to airplane url.py
path('admin/', admin.site.urls), # unused in this project
]
<file_sep>/README.md
# Django ZipHR
Django API made using Rest Framework to keep track of ZipAirlines's airplanes.
## Installation
Download from git, make sure every single file copies over. \
Make sure you have python downloaded
## Usage
Activate the env by using source env/bin/activate \
Make sure you are in the correct directory by using cd and seeing only README.md, airplanes, db.sqlite3, env, manage.py, zip_airlines \
Start server with python manage.py runserver
```bash
source env/bin/activate
python manage.py runserver
```
When you have the server running go to http://127.0.0.1:8000/ and follow the directions on there to input airplanes
<file_sep>/airplanes/urls.py
from django.urls import path
from airplanes import api
from airplanes import views
from rest_framework.urlpatterns import format_suffix_patterns
'''
Shows which routes activate what
'''
urlpatterns = [
path('', views.index), # activates the index html file
path('api/', api.airplane_list.as_view()), # activates intitial GET/POST page
path('api/<int:pk>/', api.airplane_detail.as_view()), # activates GET/PUT/DELETE page
]
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html'])
|
13c46777780c2b6dce2597f8c0716a6f6747350f
|
[
"Markdown",
"Python"
] | 12
|
Python
|
cmodi-umich/django_ZipHR
|
d2ed485a1d9c48267e9a433708d3112a17a9865b
|
f4d984f1353a9b53968a15bcb71556196806edf3
|
refs/heads/master
|
<repo_name>PianoMelody/PianoMelody<file_sep>/PianoMelody.Web/Models/ViewModels/RegistrationViewModel.cs
namespace PianoMelody.Web.Models.ViewModels
{
using System.ComponentModel.DataAnnotations;
using I18N;
public class RegistrationViewModel
{
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
[EmailAddress]
[Display(Name = "_Email", ResourceType = typeof(Resources))]
public string Email { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
[StringLength(100, ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrLenghtValidation",
MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "_Password", ResourceType = typeof(Resources))]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "_ConfirmPassword", ResourceType = typeof(Resources))]
[Compare("Password", ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_PasswordValidation")]
public string ConfirmPassword { get; set; }
}
}<file_sep>/PianoMelody.Web/Controllers/NewsController.cs
namespace PianoMelody.Web.Controllers
{
using System;
using System.Linq;
using System.Web.Mvc;
using AutoMapper.QueryableExtensions;
using OrangeJetpack.Localization;
using Helpers;
using Models.BindingModels;
using Models.ViewModels;
using PianoMelody.Helpers;
using PianoMelody.Models;
[Authorize(Roles = "Admin")]
public class NewsController : BaseController
{
[AllowAnonymous]
public ActionResult Index(int page = 1)
{
if (page < 1)
{
return this.RedirectToAction("Index");
}
var model = new NewsWithPager();
var pager = new Pager(this.Data.News.GetAll().Count(), page);
model.Pager = pager;
var news = this.Data.News.GetAll()
.OrderByDescending(n => n.Created)
.Skip((pager.CurrentPage - 1) * pager.PageSize)
.Take(pager.PageSize)
.ProjectTo<NewsViewModel>()
.Localize(this.CurrentCulture, n => n.Title, n => n.Content);
model.News = news;
return View(model);
}
public ActionResult Create(string returnUrl)
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(string returnUrl, NewsBindingModel newsBindingModel)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
var multimedia = MultimediaHelper.CreateSingle(this.Server, newsBindingModel.Multimedia, this.GetBaseUrl());
if (multimedia != null)
{
this.Data.Multimedia.Add(multimedia);
}
var news = new News()
{
Created = DateTime.Now,
Title = JsonHelper.Serialize(newsBindingModel.EnTitle, newsBindingModel.RuTitle, newsBindingModel.BgTitle),
Content = JsonHelper.Serialize(newsBindingModel.EnContent, newsBindingModel.RuContent, newsBindingModel.BgContent),
Multimedia = multimedia
};
this.Data.News.Add(news);
this.Data.SaveChanges();
return Redirect(returnUrl);
}
public ActionResult Edit(int id, string returnUrl)
{
var currentNews = this.Data.News.Find(id);
if (currentNews == null)
{
return Redirect(returnUrl);
}
var titleLocs = JsonHelper.Deserialize(currentNews.Title);
var contentLocs = JsonHelper.Deserialize(currentNews.Content);
var editNews = new NewsBindingModel()
{
Created = currentNews.Created,
EnTitle = titleLocs[0].v,
RuTitle = titleLocs[1].v,
BgTitle = titleLocs[2].v,
EnContent = contentLocs[0].v,
RuContent = contentLocs[1].v,
BgContent = contentLocs[2].v,
};
if (currentNews.Multimedia != null)
{
editNews.Url = currentNews.Multimedia.Url;
}
return View(editNews);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, string returnUrl, NewsBindingModel newsBindingModel)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
var currentNews = this.Data.News.Find(id);
if (currentNews == null)
{
return this.View();
}
if (newsBindingModel.Multimedia != null)
{
if (currentNews.Multimedia != null)
{
MultimediaHelper.DeleteSingle(this.Server, currentNews.Multimedia);
this.Data.Multimedia.Delete(currentNews.Multimedia);
}
currentNews.Multimedia = MultimediaHelper.CreateSingle(this.Server, newsBindingModel.Multimedia, this.GetBaseUrl());
}
currentNews.Created = newsBindingModel.Created;
currentNews.Title = JsonHelper.Serialize(newsBindingModel.EnTitle, newsBindingModel.RuTitle, newsBindingModel.BgTitle);
currentNews.Content = JsonHelper.Serialize(newsBindingModel.EnContent, newsBindingModel.RuContent, newsBindingModel.BgContent);
this.Data.SaveChanges();
return Redirect(returnUrl);
}
public ActionResult Delete(int id, string returnUrl)
{
var deleteNews = this.Data.News.GetAll().ProjectTo<NewsViewModel>()
.FirstOrDefault(n => n.Id == id)
.Localize(this.CurrentCulture, n => n.Title, n => n.Content);
if (deleteNews == null)
{
return Redirect(returnUrl);
}
return View(deleteNews);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id, string returnUrl, NewsViewModel newsViewModel)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
var currentNews = this.Data.News.Find(id);
if (currentNews == null)
{
return this.View();
}
if (currentNews.Multimedia != null)
{
MultimediaHelper.DeleteSingle(this.Server, currentNews.Multimedia);
this.Data.Multimedia.Delete(currentNews.Multimedia);
}
this.Data.News.Delete(currentNews);
this.Data.SaveChanges();
return Redirect(returnUrl);
}
}
}
<file_sep>/PianoMelody.Web/Multimedia/readme.txt
Multimedia directory contains uploaded by administrator multimedias.
The name of multimedia is unique identifier (Guid) which is related with database object.
It is not recommended changing the name of any multimedia !!!<file_sep>/PianoMelody.Web/Models/BindingModels/EmailBindingModel.cs
using PianoMelody.I18N;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace PianoMelody.Web.Models.BindingModels
{
public class EmailBindingModel
{
[Display(Name = "_Name", ResourceType = typeof(Resources))]
public string Name { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
[EmailAddress]
[Display(Name = "_Email", ResourceType = typeof(Resources))]
public string Email { get; set; }
[Display(Name = "_Phone", ResourceType = typeof(Resources))]
public string Phone { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
[DataType(DataType.MultilineText)]
[Display(Name = "_Message", ResourceType = typeof(Resources))]
public string Message { get; set; }
}
}<file_sep>/PianoMelody.Data/PianoMelodyContext.cs
namespace PianoMelody.Data
{
using System.Data.Entity;
using Contracts;
using Migrations;
using Models;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
public class PianoMelodyContext : IdentityDbContext<User>, IPianoMelodyContext
{
public PianoMelodyContext()
: base("name=PianoMelodyContext")
{
//#if DEBUG
Database.SetInitializer(new MigrateDatabaseToLatestVersion<PianoMelodyContext, Configuration>());
//#endif
}
public IDbSet<ArticleGroup> ArticleGroups { get; set; }
public IDbSet<Product> Products { get; set; }
public IDbSet<Information> Informations { get; set; }
public IDbSet<Manufacturer> Manufacturers { get; set; }
public IDbSet<Multimedia> Multimedia { get; set; }
public IDbSet<News> News { get; set; }
public IDbSet<Reference> References { get; set; }
public IDbSet<Resources> Resources { get; set; }
public IDbSet<Service> Services { get; set; }
public static PianoMelodyContext Create()
{
return new PianoMelodyContext();
}
}
}<file_sep>/PianoMelody.Web/Models/ViewModels/UserViewModel.cs
namespace PianoMelody.Web.Models.ViewModels
{
using Contracts;
using PianoMelody.Models;
public class UserViewModel : IMapFrom<User>
{
public string UserName { get; set; }
public string Email { get; set; }
}
}<file_sep>/PianoMelody.Web/Models/ViewModels/ServiceViewModel.cs
using OrangeJetpack.Localization;
using PianoMelody.Helpers;
using PianoMelody.Models;
using PianoMelody.Web.Contracts;
using System.Collections.Generic;
namespace PianoMelody.Web.Models.ViewModels
{
public class ServiceViewModel : IMapFrom<Service>, ILocalizable
{
public int Id { get; set; }
public int Position { get; set; }
[Localized]
public string Name { get; set; }
[Localized]
public string Description { get; set; }
public decimal? Price { get; set; }
public Multimedia Multimedia { get; set; }
}
public class ServicesWithPager
{
public IEnumerable<ServiceViewModel> Services { get; set; }
public Pager Pager { get; set; }
}
}<file_sep>/PianoMelody.Web/Controllers/ManufacturerController.cs
namespace PianoMelody.Web.Controllers
{
using System.Linq;
using System.Web.Mvc;
using AutoMapper.QueryableExtensions;
using OrangeJetpack.Localization;
using Helpers;
using Models.BindingModels;
using Models.ViewModels;
using PianoMelody.Helpers;
using PianoMelody.Models;
[Authorize(Roles = "Admin")]
public class ManufacturerController : BaseController
{
public ActionResult Index(int page = 1)
{
if (page < 1)
{
return this.RedirectToAction("Index");
}
var model = new ManufacturersWithPager();
var pager = new Pager(this.Data.Manufacturers.GetAll().Count(), page);
model.Pager = pager;
var manufacturers = this.Data.Manufacturers.GetAll()
.OrderBy(m => m.Position)
.Skip((pager.CurrentPage - 1) * pager.PageSize)
.Take(pager.PageSize)
.ProjectTo<ManufacturerViewModel>()
.Localize(this.CurrentCulture, m => m.Name);
model.Manufacturers = manufacturers;
return View(model);
}
public ActionResult Create(string returnUrl)
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(string returnUrl, ManufacturerBindingModel manufacturerBindingModel)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
var multimedia = MultimediaHelper.CreateSingle(this.Server, manufacturerBindingModel.Multimedia, this.GetBaseUrl());
if (multimedia != null)
{
this.Data.Multimedia.Add(multimedia);
}
var manufacturer = new Manufacturer()
{
Name = JsonHelper.Serialize(manufacturerBindingModel.EnName, manufacturerBindingModel.RuName, manufacturerBindingModel.BgName),
AreWeAgent = manufacturerBindingModel.AreWeAgent,
UrlAddress = manufacturerBindingModel.UrlAddress,
Multimedia = multimedia
};
this.Data.Manufacturers.Add(manufacturer);
this.Data.SaveChanges();
return Redirect(returnUrl);
}
public ActionResult Edit(int id, string returnUrl)
{
var currentManufacturer = this.Data.Manufacturers.Find(id);
if (currentManufacturer == null)
{
return Redirect(returnUrl);
}
var nameLocs = JsonHelper.Deserialize(currentManufacturer.Name);
var editManufacturer = new ManufacturerBindingModel()
{
EnName = nameLocs[0].v,
RuName = nameLocs[1].v,
BgName = nameLocs[2].v,
AreWeAgent = currentManufacturer.AreWeAgent,
UrlAddress = currentManufacturer.UrlAddress
};
if (currentManufacturer.Multimedia != null)
{
editManufacturer.Url = currentManufacturer.Multimedia.Url;
}
return View(editManufacturer);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, string returnUrl, ManufacturerBindingModel manufacturerBindingModel)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
var currentManufacturer = this.Data.Manufacturers.Find(id);
if (currentManufacturer == null)
{
return this.View();
}
if (manufacturerBindingModel.Multimedia != null)
{
if (currentManufacturer.Multimedia != null)
{
MultimediaHelper.DeleteSingle(this.Server, currentManufacturer.Multimedia);
this.Data.Multimedia.Delete(currentManufacturer.Multimedia);
}
currentManufacturer.Multimedia = MultimediaHelper.CreateSingle(this.Server, manufacturerBindingModel.Multimedia, this.GetBaseUrl());
}
currentManufacturer.Name = JsonHelper.Serialize(manufacturerBindingModel.EnName, manufacturerBindingModel.RuName, manufacturerBindingModel.BgName);
currentManufacturer.AreWeAgent = manufacturerBindingModel.AreWeAgent;
currentManufacturer.UrlAddress = manufacturerBindingModel.UrlAddress;
this.Data.SaveChanges();
return Redirect(returnUrl);
}
public ActionResult Delete(int id, string returnUrl)
{
var deleteManufacturer = this.Data.Manufacturers.GetAll().ProjectTo<ManufacturerViewModel>()
.FirstOrDefault(m => m.Id == id)
.Localize(this.CurrentCulture, m => m.Name);
if (deleteManufacturer == null)
{
return Redirect(returnUrl);
}
return View(deleteManufacturer);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id, string returnUrl, ManufacturerViewModel manufacturerViewModel)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
var currentManufacturer = this.Data.Manufacturers.Find(id);
if (currentManufacturer == null)
{
return this.View();
}
if (currentManufacturer.Multimedia != null)
{
MultimediaHelper.DeleteSingle(this.Server, currentManufacturer.Multimedia);
this.Data.Multimedia.Delete(currentManufacturer.Multimedia);
}
this.Data.Manufacturers.Delete(currentManufacturer);
this.Data.SaveChanges();
this.RePosition();
return Redirect(returnUrl);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Up(int id, string returnUrl)
{
var up = this.Data.Manufacturers.Find(id);
if (up != null)
{
var down = this.Data.Manufacturers.GetAll().FirstOrDefault(p => p.Position == up.Position - 1);
if (down != null)
{
int temp = up.Position;
up.Position = down.Position;
down.Position = temp;
this.Data.SaveChanges();
}
}
return this.Redirect(returnUrl);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Down(int id, string returnUrl)
{
var down = this.Data.Manufacturers.Find(id);
if (down != null)
{
var up = this.Data.Manufacturers.GetAll().FirstOrDefault(p => p.Position == down.Position + 1);
if (up != null)
{
int temp = up.Position;
up.Position = down.Position;
down.Position = temp;
this.Data.SaveChanges();
}
}
return this.Redirect(returnUrl);
}
private void RePosition()
{
var manufacturers = this.Data.Manufacturers.GetAll().OrderBy(a => a.Position).ToList();
for (int i = 0; i < manufacturers.Count; i++)
{
manufacturers[i].Position = i + 1;
}
this.Data.SaveChanges();
}
}
}
<file_sep>/PianoMelody.Web/Controllers/CarouselController.cs
namespace PianoMelody.Web.Controllers
{
using System.Linq;
using System.Web.Mvc;
using AutoMapper.QueryableExtensions;
using OrangeJetpack.Localization;
using Extensions;
using Helpers;
using I18N;
using Models.BindingModels;
using Models.ViewModels;
using PianoMelody.Models.Enumetations;
[Authorize(Roles = "Admin")]
public class CarouselController : BaseController
{
public ActionResult Index()
{
var carousel = this.Data.Multimedia.GetAll()
.Where(g => g.Type == MultimediaType.CarouselElement)
.ProjectTo<CarouselViewModel>()
.Localize(this.CurrentCulture, g => g.Content);
return View(carousel);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CarouselBindingModel carouselBindingModel)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
if (this.Data.Multimedia.GetAll().Count(c => c.Type == MultimediaType.CarouselElement) >= 5)
{
return this.RedirectToAction("Index");
}
var content = JsonHelper.Serialize(carouselBindingModel.EnContent, carouselBindingModel.RuContent, carouselBindingModel.BgContent);
var multimedia = MultimediaHelper.CreateSingle
(
this.Server,
carouselBindingModel.Multimedia,
this.GetBaseUrl(),
MultimediaType.CarouselElement,
content
);
if (multimedia == null)
{
this.AddNotification(Resources._ErrSelectMultimedia, NotificationType.ERROR);
return this.View();
}
this.Data.Multimedia.Add(multimedia);
this.Data.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult Edit(int id)
{
var currentCarouselElement = this.Data.Multimedia.Find(id);
if (currentCarouselElement == null)
{
return this.RedirectToAction("Index");
}
var contentLocs = JsonHelper.Deserialize(currentCarouselElement.Content);
var editCarouselElement = new CarouselBindingModel()
{
EnContent = contentLocs[0].v,
RuContent = contentLocs[1].v,
BgContent = contentLocs[2].v,
Url = currentCarouselElement.Url
};
return View(editCarouselElement);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, CarouselBindingModel carouselBindingModel)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
var currentCarouselElement = this.Data.Multimedia.Find(id);
if (currentCarouselElement == null)
{
return this.View();
}
currentCarouselElement.Content = JsonHelper.Serialize(carouselBindingModel.EnContent, carouselBindingModel.RuContent, carouselBindingModel.BgContent);
if (carouselBindingModel.Multimedia != null)
{
MultimediaHelper.DeleteSingle(this.Server, currentCarouselElement);
var multimedia = MultimediaHelper.CreateSingle
(
this.Server,
carouselBindingModel.Multimedia,
this.GetBaseUrl(),
MultimediaType.CarouselElement,
currentCarouselElement.Content
);
currentCarouselElement.Url = multimedia.Url;
}
this.Data.SaveChanges();
return RedirectToAction("Index");
}
}
}
<file_sep>/PianoMelody.Web/Controllers/ProfileController.cs
namespace PianoMelody.Web.Controllers
{
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Extensions;
using Models.ViewModels;
[Authorize(Roles = "Admin")]
public class ProfileController : BaseController
{
private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;
public ProfileController()
{
}
public ProfileController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
{
this.UserManager = userManager;
this.SignInManager = signInManager;
}
public ApplicationSignInManager SignInManager
{
get
{
return this._signInManager ?? this.HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set
{
this._signInManager = value;
}
}
public ApplicationUserManager UserManager
{
get
{
return this._userManager ?? this.HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
this._userManager = value;
}
}
// GET: /Profile/Index
public ActionResult Index(ManageMessageId? message)
{
return this.RedirectToAction("Index", "Home");
}
// GET: /Profile/ChangePassword
[HttpGet]
public ActionResult ChangePassword()
{
return this.View();
}
// POST: /Profile/ChangePassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!this.ModelState.IsValid)
{
return this.View(model);
}
var result =
await
this.UserManager.ChangePasswordAsync(
this.User.Identity.GetUserId(),
model.CurrentPassword,
model.NewPassword);
if (result.Succeeded)
{
var user = await this.UserManager.FindByIdAsync(this.User.Identity.GetUserId());
if (user != null)
{
await this.SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
this.AddNotification("Your password has been changed successfull", NotificationType.SUCCESS);
return this.RedirectToAction("Index");
}
this.AddErrors(result);
return this.View(model);
}
protected override void Dispose(bool disposing)
{
if (disposing && this._userManager != null)
{
this._userManager.Dispose();
this._userManager = null;
}
base.Dispose(disposing);
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
this.ModelState.AddModelError("", error);
}
}
public enum ManageMessageId
{
AddPhoneSuccess,
EditProfileSuccess,
ChangePasswordSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error
}
#endregion
}
}<file_sep>/PianoMelody.Web/Extensions/StringExtensions.cs
namespace PianoMelody.Web.Extensions
{
public static class StringExtensions
{
public static string ToFixedLenght(this string str, int lenght)
{
if (str.Length > lenght + 3)
{
return str.Substring(0, lenght - 3) + "...";
}
return str;
}
}
}<file_sep>/PianoMelody.Web/Helpers/MultimediaHelper.cs
using PianoMelody.Models;
using PianoMelody.Models.Enumetations;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
namespace PianoMelody.Web.Helpers
{
public static class MultimediaHelper
{
private static int thumbWidth = int.Parse(ConfigurationManager.AppSettings["thumbWidth"]);
public static Multimedia CreateSingle
(
HttpServerUtilityBase server,
HttpPostedFileBase fileBase,
string baseUrl,
MultimediaType type = MultimediaType.SingleElement,
string content = ""
)
{
string fileName = string.Empty;
if (fileBase != null && fileBase.ContentLength > 0)
{
var realName = Path.GetFileName(fileBase.FileName);
fileName = Guid.NewGuid().ToString() + Path.GetExtension(realName);
var path = "~/Multimedia";
var filePath = Path.Combine(server.MapPath(path), fileName);
fileBase.SaveAs(filePath);
CreateThumbnail(server, filePath, thumbWidth);
var url = baseUrl + "Multimedia/" + fileName;
var multimedia = new Multimedia()
{
Type = type,
Created = DateTime.Now,
Url = url,
DataSize = GetDataSize(filePath),
Content = content
};
return multimedia;
}
return null;
}
public static void DeleteSingle(HttpServerUtilityBase server, Multimedia multimedia)
{
var fileName = multimedia.Url.Split('/').Last();
var filePath = Path.Combine(server.MapPath("~/Multimedia"), fileName);
File.Delete(filePath);
var thumbPath = Path.Combine(server.MapPath("~/Multimedia/thumbs"), fileName);
File.Delete(thumbPath);
}
public static ICollection<Multimedia> CreateMultiple
(
HttpServerUtilityBase server,
IEnumerable<HttpPostedFileBase> fileBases,
string baseUrl,
MultimediaType type = MultimediaType.SingleElement,
string content = ""
)
{
var result = new List<Multimedia>();
foreach (var fileBase in fileBases)
{
string fileName = string.Empty;
if (fileBase != null && fileBase.ContentLength > 0)
{
var realName = Path.GetFileName(fileBase.FileName);
fileName = Guid.NewGuid().ToString() + Path.GetExtension(realName);
var filePath = Path.Combine(server.MapPath("~/Multimedia"), fileName);
fileBase.SaveAs(filePath);
CreateThumbnail(server, filePath, thumbWidth);
var url = baseUrl + "Multimedia/" + fileName;
var multimedia = new Multimedia()
{
Type = type,
Created = DateTime.Now,
Url = url,
DataSize = GetDataSize(filePath),
Content = content
};
result.Add(multimedia);
}
}
return result.Count > 0 ? result : null;
}
public static void DeleteMultiple(HttpServerUtilityBase server, ICollection<Multimedia> multimedias)
{
foreach (var multimedia in multimedias)
{
var fileName = multimedia.Url.Split('/').Last();
var filePath = Path.Combine(server.MapPath("~/Multimedia"), fileName);
File.Delete(filePath);
var thumbPath = Path.Combine(server.MapPath("~/Multimedia/thumbs"), fileName);
File.Delete(thumbPath);
}
}
private static string GetDataSize(string filePath)
{
string dataSize = string.Empty;
using (Image imgPhoto = Image.FromFile(filePath))
{
dataSize = string.Format("{0}x{1}", imgPhoto.Width, imgPhoto.Height);
}
return dataSize;
}
private static void CreateThumbnail(HttpServerUtilityBase server, string filePath, int width)
{
using (Image imgPhoto = Image.FromFile(filePath))
{
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
imgPhoto.RotateFlip(RotateFlipType.Rotate180FlipX);
imgPhoto.RotateFlip(RotateFlipType.Rotate180FlipX);
float ratio = 0;
ratio = (float)sourceWidth / sourceHeight;
int calcHeight = (int)(width / ratio);
using (Image thumbnail = imgPhoto.GetThumbnailImage(width, calcHeight, () => false, IntPtr.Zero))
{
string fileName = filePath.Split('\\').Last();
string path = Path.Combine(server.MapPath("~/Multimedia/thumbs"), fileName);
thumbnail.Save(path);
}
}
}
}
}<file_sep>/PianoMelody.Models/Enumetations/MultimediaType.cs
namespace PianoMelody.Models.Enumetations
{
public enum MultimediaType
{
PhotoElement = 0,
SingleElement = 1,
CarouselElement = 2,
VideoElement = 3
}
}
<file_sep>/PianoMelody.Web/Models/BindingModels/CarouselBindingModel.cs
using PianoMelody.I18N;
using System.ComponentModel.DataAnnotations;
using System.Web;
namespace PianoMelody.Web.Models.BindingModels
{
public class CarouselBindingModel
{
[DataType(DataType.MultilineText)]
[Display(Name = "_EnContent", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string EnContent { get; set; }
[DataType(DataType.MultilineText)]
[Display(Name = "_RuContent", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string RuContent { get; set; }
[DataType(DataType.MultilineText)]
[Display(Name = "_BgContent", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string BgContent { get; set; }
[Display(Name = "_Photo", ResourceType = typeof(Resources))]
public HttpPostedFileBase Multimedia { get; set; }
public string Url { get; set; }
}
}<file_sep>/PianoMelody.Web/Models/BindingModels/NewsBindingModel.cs
using PianoMelody.I18N;
using System;
using System.ComponentModel.DataAnnotations;
using System.Web;
namespace PianoMelody.Web.Models.BindingModels
{
public class NewsBindingModel
{
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
[Display(Name = "_Created", ResourceType = typeof(Resources))]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime Created { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
[Display(Name = "_EnTitle", ResourceType = typeof(Resources))]
public string EnTitle { get; set; }
[Display(Name = "_RuTitle", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string RuTitle { get; set; }
[Display(Name = "_BgTitle", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string BgTitle { get; set; }
[DataType(DataType.MultilineText)]
[Display(Name = "_EnContent", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string EnContent { get; set; }
[DataType(DataType.MultilineText)]
[Display(Name = "_RuContent", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string RuContent { get; set; }
[DataType(DataType.MultilineText)]
[Display(Name = "_BgContent", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string BgContent { get; set; }
[Display(Name = "_Photo", ResourceType = typeof(Resources))]
public HttpPostedFileBase Multimedia { get; set; }
public string Url { get; set; }
}
}<file_sep>/PianoMelody.Web/Controllers/ArticleGroupController.cs
namespace PianoMelody.Web.Controllers
{
using System.Linq;
using System.Web.Mvc;
using AutoMapper.QueryableExtensions;
using OrangeJetpack.Localization;
using Helpers;
using Models.BindingModels;
using Models.ViewModels;
using PianoMelody.Helpers;
using PianoMelody.Models;
[Authorize(Roles = "Admin")]
public class ArticleGroupController : BaseController
{
public ActionResult Index(int page = 1)
{
if (page < 1)
{
return this.RedirectToAction("Index");
}
var model = new ArticleGroupsWithPager();
var pager = new Pager(this.Data.ArticleGroups.GetAll().Count(), page);
model.Pager = pager;
var articleGroups = this.Data.ArticleGroups.GetAll()
.OrderBy(ag => ag.Position)
.Skip((pager.CurrentPage - 1) * pager.PageSize)
.Take(pager.PageSize)
.ProjectTo<ArticleGroupViewModel>()
.Localize(this.CurrentCulture, ag => ag.Name);
model.ArticleGroups = articleGroups;
return View(model);
}
public ActionResult Create(string returnUrl)
{
return View();
}
[HttpPost]
public ActionResult Create(string returnUrl, ArticleGroupBindingModel articleGroupBindingModel)
{
if (!ModelState.IsValid)
{
return this.View();
}
var articleGroup = new ArticleGroup()
{
Name = JsonHelper.Serialize(articleGroupBindingModel.EnName, articleGroupBindingModel.RuName, articleGroupBindingModel.BgName)
};
this.Data.ArticleGroups.Add(articleGroup);
this.Data.SaveChanges();
return Redirect(returnUrl);
}
public ActionResult Edit(int id, string returnUrl)
{
var currentArticleGroup = this.Data.ArticleGroups.Find(id);
if (currentArticleGroup == null)
{
return Redirect(returnUrl);
}
var nameLocs = JsonHelper.Deserialize(currentArticleGroup.Name);
var editArticleGroup = new ArticleGroupBindingModel()
{
EnName = nameLocs[0].v,
RuName = nameLocs[1].v,
BgName = nameLocs[2].v
};
return View(editArticleGroup);
}
[HttpPost]
public ActionResult Edit(int id, string returnUrl, ArticleGroupBindingModel articleGroupBindingModel)
{
if (!ModelState.IsValid)
{
return this.View();
}
var articleGroup = this.Data.ArticleGroups.Find(id);
if (articleGroup == null)
{
return this.View();
}
articleGroup.Name = JsonHelper.Serialize(articleGroupBindingModel.EnName, articleGroupBindingModel.RuName, articleGroupBindingModel.BgName);
this.Data.SaveChanges();
return Redirect(returnUrl);
}
public ActionResult Delete(int id, string returnUrl)
{
var deleteArticleGroup = this.Data.ArticleGroups.GetAll().ProjectTo<ArticleGroupViewModel>()
.FirstOrDefault(ag => ag.Id == id)
.Localize(this.CurrentCulture, ag => ag.Name);
if (deleteArticleGroup == null)
{
return Redirect(returnUrl);
}
return View(deleteArticleGroup);
}
[HttpPost]
public ActionResult Delete(int id, string returnUrl, ArticleGroupViewModel articleGroupViewModel)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
var currentArticleGroup = this.Data.ArticleGroups.Find(id);
if (currentArticleGroup == null)
{
return this.View();
}
this.Data.ArticleGroups.Delete(currentArticleGroup);
this.Data.SaveChanges();
this.RePosition();
return Redirect(returnUrl);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Up(int id, string returnUrl)
{
var up = this.Data.ArticleGroups.Find(id);
if (up != null)
{
var down = this.Data.ArticleGroups.GetAll().FirstOrDefault(p => p.Position == up.Position - 1);
if (down != null)
{
int temp = up.Position;
up.Position = down.Position;
down.Position = temp;
this.Data.SaveChanges();
}
}
return this.Redirect(returnUrl);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Down(int id, string returnUrl)
{
var down = this.Data.ArticleGroups.Find(id);
if (down != null)
{
var up = this.Data.ArticleGroups.GetAll().FirstOrDefault(p => p.Position == down.Position + 1);
if (up != null)
{
int temp = up.Position;
up.Position = down.Position;
down.Position = temp;
this.Data.SaveChanges();
}
}
return this.Redirect(returnUrl);
}
private void RePosition()
{
var articleGroups = this.Data.ArticleGroups.GetAll().OrderBy(a => a.Position).ToList();
for (int i = 0; i < articleGroups.Count; i++)
{
articleGroups[i].Position = i + 1;
}
this.Data.SaveChanges();
}
}
}
<file_sep>/PianoMelody.Web/Controllers/ReferencesController.cs
namespace PianoMelody.Web.Controllers
{
using System;
using System.Linq;
using System.Web.Mvc;
using AutoMapper.QueryableExtensions;
using OrangeJetpack.Localization;
using Helpers;
using Models.BindingModels;
using Models.ViewModels;
using PianoMelody.Helpers;
using PianoMelody.Models;
[Authorize(Roles = "Admin")]
public class ReferencesController : BaseController
{
[AllowAnonymous]
public ActionResult Index(int page = 1)
{
if (page < 1)
{
return this.RedirectToAction("Index");
}
var model = new ReferencesWithPager();
var pager = new Pager(this.Data.References.GetAll().Count(), page);
model.Pager = pager;
var references = this.Data.References.GetAll()
.OrderBy(r => r.Position)
.Skip((pager.CurrentPage - 1) * pager.PageSize)
.Take(pager.PageSize)
.ProjectTo<ReferenceViewModel>()
.Localize(this.CurrentCulture, r => r.Title, r => r.Content);
model.References = references;
return View(model);
}
public ActionResult Create(string returnUrl)
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(string returnUrl, ReferenceBindingModel referenceBindingModel)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
var multimedia = MultimediaHelper.CreateSingle(this.Server, referenceBindingModel.Multimedia, this.GetBaseUrl());
if (multimedia != null)
{
this.Data.Multimedia.Add(multimedia);
}
var reference = new Reference()
{
Created = DateTime.Now,
Title = JsonHelper.Serialize(referenceBindingModel.EnTitle, referenceBindingModel.RuTitle, referenceBindingModel.BgTitle),
Content = JsonHelper.Serialize(referenceBindingModel.EnContent, referenceBindingModel.RuContent, referenceBindingModel.BgContent),
Multimedia = multimedia
};
this.Data.References.Add(reference);
this.Data.SaveChanges();
return Redirect(returnUrl);
}
public ActionResult Edit(int id, string returnUrl)
{
var currentReference = this.Data.References.Find(id);
if (currentReference == null)
{
return Redirect(returnUrl);
}
var titleLocs = JsonHelper.Deserialize(currentReference.Title);
var contentLocs = JsonHelper.Deserialize(currentReference.Content);
var editReference = new ReferenceBindingModel()
{
EnTitle = titleLocs[0].v,
RuTitle = titleLocs[1].v,
BgTitle = titleLocs[2].v,
EnContent = contentLocs[0].v,
RuContent = contentLocs[1].v,
BgContent = contentLocs[2].v
};
if (currentReference.Multimedia != null)
{
editReference.Url = currentReference.Multimedia.Url;
}
return View(editReference);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, string returnUrl, ReferenceBindingModel referenceBindingModel)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
var currentReference = this.Data.References.Find(id);
if (currentReference == null)
{
return this.View();
}
if (referenceBindingModel.Multimedia != null)
{
if (currentReference.Multimedia != null)
{
MultimediaHelper.DeleteSingle(this.Server, currentReference.Multimedia);
this.Data.Multimedia.Delete(currentReference.Multimedia);
}
currentReference.Multimedia = MultimediaHelper.CreateSingle(this.Server, referenceBindingModel.Multimedia, this.GetBaseUrl());
}
currentReference.Title = JsonHelper.Serialize(referenceBindingModel.EnTitle, referenceBindingModel.RuTitle, referenceBindingModel.BgTitle);
currentReference.Content = JsonHelper.Serialize(referenceBindingModel.EnContent, referenceBindingModel.RuContent, referenceBindingModel.BgContent);
this.Data.SaveChanges();
return Redirect(returnUrl);
}
public ActionResult Delete(int id, string returnUrl)
{
var deleteReference = this.Data.References.GetAll().ProjectTo<ReferenceViewModel>()
.FirstOrDefault(r => r.Id == id)
.Localize(this.CurrentCulture, r => r.Title, r => r.Content);
if (deleteReference == null)
{
return Redirect(returnUrl);
}
return View(deleteReference);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id, string returnUrl, ReferenceViewModel referenceViewModel)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
var currentReference = this.Data.References.Find(id);
if (currentReference == null)
{
return this.View();
}
if (currentReference.Multimedia != null)
{
MultimediaHelper.DeleteSingle(this.Server, currentReference.Multimedia);
this.Data.Multimedia.Delete(currentReference.Multimedia);
}
this.Data.References.Delete(currentReference);
this.Data.SaveChanges();
this.RePosition();
return Redirect(returnUrl);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Up(int id, string returnUrl)
{
var up = this.Data.References.Find(id);
if (up != null)
{
var down = this.Data.References.GetAll().FirstOrDefault(p => p.Position == up.Position - 1);
if (down != null)
{
int temp = up.Position;
up.Position = down.Position;
down.Position = temp;
this.Data.SaveChanges();
}
}
return this.Redirect(returnUrl);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Down(int id, string returnUrl)
{
var down = this.Data.References.Find(id);
if (down != null)
{
var up = this.Data.References.GetAll().FirstOrDefault(p => p.Position == down.Position + 1);
if (up != null)
{
int temp = up.Position;
up.Position = down.Position;
down.Position = temp;
this.Data.SaveChanges();
}
}
return this.Redirect(returnUrl);
}
private void RePosition()
{
var references = this.Data.References.GetAll().OrderBy(a => a.Position).ToList();
for (int i = 0; i < references.Count; i++)
{
references[i].Position = i + 1;
}
this.Data.SaveChanges();
}
}
}
<file_sep>/PianoMelody.Web/Models/ViewModels/ProductViewModel.cs
using OrangeJetpack.Localization;
using PianoMelody.Models;
using PianoMelody.Web.Contracts;
using System.Collections.Generic;
using AutoMapper;
using PianoMelody.Helpers;
namespace PianoMelody.Web.Models.ViewModels
{
public class ProductViewModel : IMapFrom<Product>, ICustomMappings, ILocalizable
{
public int Id { get; set; }
public int Position { get; set; }
[Localized]
public string Name { get; set; }
[Localized]
public string Description { get; set; }
public decimal? Price { get; set; }
public decimal? PromoPrice { get; set; }
public bool IsNew { get; set; }
public bool IsSold { get; set; }
[Localized]
public string ArticleGroupName { get; set; }
[Localized]
public string ManufacturerName { get; set; }
public ICollection<Multimedia> Multimedias { get; set; }
public void CreateMappings(IConfiguration configuration)
{
configuration.CreateMap<Product, ProductViewModel>()
.ForMember(
p => p.ArticleGroupName,
opt => opt.MapFrom(p => p.ArtilceGroup.Name))
.ForMember(
p => p.ManufacturerName,
opt => opt.MapFrom(p => p.Manufacturer.Name));
}
}
public class ProductsWithPager
{
public IEnumerable<ProductViewModel> Products { get; set; }
public Pager Pager { get; set; }
}
}<file_sep>/PianoMelody.I18N.Builder/Builder.cs
namespace PianoMelody.I18N.Builder
{
using System;
using System.IO;
using System.Drawing;
using Utility;
using Concrete;
using System.Linq;
class Builder
{
static void Main()
{
var builder = new ResourceBuilder();
var resourceProvider = new DbResourceProvider(@"Data Source=.;Initial Catalog=piano_462;Integrated Security=True;Pooling=False");
string path = Directory.GetCurrentDirectory().Replace(".Builder\\bin\\Debug", "\\Resources.cs");
string filePath = builder.Create(resourceProvider, filePath: path, summaryCulture: "en");
Console.WriteLine("Resource file {0} created.", filePath);
//UpdateThumbnails();
}
/// <summary>
/// Update all thumbnails for all images from Multimedia folder
/// </summary>
static void UpdateThumbnails()
{
var path = Directory.GetCurrentDirectory().Replace("I18N.Builder\\bin\\Debug", "Web\\Multimedia\\");
DirectoryInfo dir = new DirectoryInfo(path);
int newWidth = 300;
foreach (var file in dir.GetFiles().Where(f => !f.ToString().EndsWith(".txt")))
{
var filePath = path + file;
using (Image imgPhoto = Image.FromFile(filePath))
{
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
imgPhoto.RotateFlip(RotateFlipType.Rotate180FlipX);
imgPhoto.RotateFlip(RotateFlipType.Rotate180FlipX);
float ratio = 0;
ratio = (float)sourceWidth / sourceHeight;
int calcHeight = (int)(newWidth / ratio);
using (Image thumbnail = imgPhoto.GetThumbnailImage(newWidth, calcHeight, () => false, IntPtr.Zero))
{
thumbnail.Save(path + "thumbs\\" + file);
}
}
}
Console.WriteLine("Thumbnails has been updated.");
}
}
}
<file_sep>/PianoMelody.Web/Helpers/EmailHelper.cs
namespace PianoMelody.Web.Helpers
{
using System.Configuration;
using System.Net;
using System.Net.Mail;
public class EmailHelper
{
private readonly string host = ConfigurationManager.AppSettings["host"];
private readonly int port = int.Parse(ConfigurationManager.AppSettings["port"]);
private readonly bool ssl = bool.Parse(ConfigurationManager.AppSettings["ssl"]);
private readonly string user = ConfigurationManager.AppSettings["user"];
private readonly string pass = ConfigurationManager.AppSettings["pass"];
public string Name { get; set; }
public string Email { get; set; }
public string Recipient { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public void Send()
{
using (var smtp = new SmtpClient())
{
smtp.Host = this.host;
smtp.Port = this.port;
smtp.EnableSsl = this.ssl;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(this.user, this.pass);
using (var message = new MailMessage(this.user, this.Recipient))
{
message.From = new MailAddress(this.Email);
message.Subject = this.Subject;
message.Body = this.Body;
message.IsBodyHtml = true;
smtp.Send(message);
}
}
}
}
}<file_sep>/PianoMelody.Data/Contracts/IPianoMelodyContext.cs
namespace PianoMelody.Data.Contracts
{
using System.Data.Entity;
using Models;
public interface IPianoMelodyContext
{
IDbSet<User> Users { get; set; }
IDbSet<Resources> Resources { get; set; }
IDbSet<ArticleGroup> ArticleGroups { get; set; }
IDbSet<Product> Products { get; set; }
IDbSet<Service> Services { get; set; }
IDbSet<News> News { get; set; }
IDbSet<Information> Informations { get; set; }
IDbSet<Reference> References { get; set; }
IDbSet<Manufacturer> Manufacturers { get; set; }
IDbSet<Multimedia> Multimedia { get; set; }
}
}<file_sep>/README.md
# PianoMelody
PianoMelody Project
<file_sep>/PianoMelody.Web/Models/ViewModels/InfoViewModel.cs
using OrangeJetpack.Localization;
using PianoMelody.Helpers;
using PianoMelody.Models;
using PianoMelody.Web.Contracts;
using System;
using System.Collections.Generic;
namespace PianoMelody.Web.Models.ViewModels
{
public class InfoViewModel : IMapFrom<Information>, ILocalizable
{
public int Id { get; set; }
public int Position { get; set; }
public DateTime Created { get; set; }
[Localized]
public string Title { get; set; }
[Localized]
public string Content { get; set; }
public Multimedia Multimedia { get; set; }
}
public class InfoWithPager
{
public IEnumerable<InfoViewModel> Informations { get; set; }
public Pager Pager { get; set; }
}
}<file_sep>/PianoMelody.Web/Controllers/LanguageController.cs
namespace PianoMelody.Web.Controllers
{
using System.Linq;
using System.Web.Mvc;
using AutoMapper.QueryableExtensions;
using Extensions;
using I18N;
using Models.BindingModels;
using Models.ViewModels;
[Authorize(Roles = "Admin")]
public class LanguageController : BaseController
{
// GET: Language
public ActionResult Index()
{
Resources.Refresh();
var resources = this.Data.Resources.GetAll()
.Where(r => !r.Name.StartsWith("_"))
.GroupBy(r => r.Name)
.Select(g => g.FirstOrDefault())
.ProjectTo<ResourceViewModel>();
return this.View(resources);
}
// GET: Language/AddLabel
public ActionResult AddLabel()
{
return this.View();
}
// POST: Language/AddLabel
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddLabel(ResourcesBindingModel rbm)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
this.Data.Resources.Add(new PianoMelody.Models.Resources { Culture = "en", Name = rbm.Name, Value = rbm.EnValue });
this.Data.Resources.Add(new PianoMelody.Models.Resources { Culture = "ru", Name = rbm.Name, Value = rbm.RuValue });
this.Data.Resources.Add(new PianoMelody.Models.Resources { Culture = "bg", Name = rbm.Name, Value = rbm.BgValue });
this.Data.SaveChanges();
this.AddNotification(Resources._LabelCreated, NotificationType.SUCCESS);
return this.RedirectToAction("AddLabel");
}
// Get: Language/Edit
public ActionResult Edit(string name)
{
var labels = this.Data.Resources.GetAll().Where(r => r.Name == name).ToArray();
var enLabel = labels.FirstOrDefault(l => l.Culture == "en");
var ruLabel = labels.FirstOrDefault(l => l.Culture == "ru");
var bgLabel = labels.FirstOrDefault(l => l.Culture == "bg");
var rbm = new ResourcesBindingModel()
{
Name = name,
EnValue = enLabel.Value,
RuValue = ruLabel.Value,
BgValue = bgLabel.Value
};
return this.View(rbm);
}
// Post: Language/Edit
[HttpPost]
public ActionResult Edit(ResourcesBindingModel rbm)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
var labels = this.Data.Resources.GetAll().Where(r => r.Name == rbm.Name).ToArray();
var enLabel = labels.FirstOrDefault(l => l.Culture == "en");
var ruLabel = labels.FirstOrDefault(l => l.Culture == "ru");
var bgLabel = labels.FirstOrDefault(l => l.Culture == "bg");
enLabel.Value = rbm.EnValue;
ruLabel.Value = rbm.RuValue;
bgLabel.Value = rbm.BgValue;
this.Data.SaveChanges();
this.AddNotification(Resources._LabelUpdated, NotificationType.SUCCESS);
return this.RedirectToAction("Index");
}
}
}<file_sep>/PianoMelody.Web/Controllers/AccountController.cs
namespace PianoMelody.Web.Controllers
{
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Extensions;
using Models.ViewModels;
using PianoMelody.Models;
[Authorize(Roles = "Admin")]
public class AccountController : BaseController
{
private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;
public AccountController()
{
}
public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
{
this.UserManager = userManager;
this.SignInManager = signInManager;
}
public ApplicationSignInManager SignInManager
{
get
{
return this._signInManager ?? this.HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set
{
this._signInManager = value;
}
}
public ApplicationUserManager UserManager
{
get
{
return this._userManager ?? this.HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
this._userManager = value;
}
}
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
this.ViewBag.ReturnUrl = returnUrl;
return this.View();
}
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!this.ModelState.IsValid)
{
return this.View(model);
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result =
await
this.SignInManager.PasswordSignInAsync(
model.Email,
model.Password,
true,
shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return this.RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return this.View("Lockout");
case SignInStatus.Failure:
default:
this.ModelState.AddModelError(string.Empty, "Invalid login attempt");
return this.View(model);
}
}
// GET: /Account/Register
public ActionResult Register()
{
return this.View();
}
// POST: /Account/Register
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegistrationViewModel model)
{
if (this.ModelState.IsValid)
{
var user = new User
{
UserName = model.Email,
Email = model.Email,
};
var result = await this.UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
result = await this.UserManager.AddToRoleAsync(user.Id, "Admin");
if (result.Succeeded)
{
this.AddNotification("Admin created", NotificationType.SUCCESS);
return this.RedirectToAction("Index", "Home");
}
}
this.AddErrors(result);
}
// If we got this far, something failed, redisplay form
return this.View(model);
}
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
this.AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
return this.RedirectToAction("Index", "Home");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (this._userManager != null)
{
this._userManager.Dispose();
this._userManager = null;
}
if (this._signInManager != null)
{
this._signInManager.Dispose();
this._signInManager = null;
}
}
base.Dispose(disposing);
}
#region Helpers
private IAuthenticationManager AuthenticationManager
{
get
{
return this.HttpContext.GetOwinContext().Authentication;
}
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
this.ModelState.AddModelError("", error);
}
}
private ActionResult RedirectToLocal(string returnUrl)
{
if (this.Url.IsLocalUrl(returnUrl))
{
return this.Redirect(returnUrl);
}
return this.RedirectToAction("Index", "Home");
}
#endregion
}
}<file_sep>/PianoMelody.Web/Controllers/BaseController.cs
namespace PianoMelody.Web.Controllers
{
using System;
using System.Threading;
using System.Web.Mvc;
using Data;
using Data.Contracts;
using Helpers;
public class BaseController : Controller
{
public BaseController()
: this(new PianoMelodyData())
{
}
public BaseController(IPianoMelodyData data)
{
this.Data = data;
}
protected IPianoMelodyData Data { get; set; }
protected string GetBaseUrl()
{
//var request = System.Web.HttpContext.Current.Request;
//var appUrl = HttpRuntime.AppDomainAppVirtualPath;
//var baseUrl = string.Format("{0}://{1}{2}", request.Url.Scheme, request.Url.Authority, appUrl);
var baseUrl = "/";
return baseUrl;
}
public string CurrentCulture { get { return CultureHelper.GetCurrentCulture().Substring(0, 2); } }
protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
{
string cultureName = RouteData.Values["culture"] as string;
// Attempt to read the culture cookie from Request
if (cultureName == null)
cultureName = Request.UserLanguages != null && Request.UserLanguages.Length > 0 ? Request.UserLanguages[0] : null; // obtain it from HTTP header AcceptLanguages
// Validate culture name
cultureName = CultureHelper.GetImplementedCulture(cultureName); // This is safe
if (RouteData.Values["culture"] as string != cultureName)
{
// Force a valid culture in the URL
RouteData.Values["culture"] = cultureName.ToLowerInvariant(); // lower case too
// Redirect user
Response.RedirectToRoute(RouteData.Values);
}
// Modify current thread's cultures
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cultureName);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
return base.BeginExecuteCore(callback, state);
}
}
}<file_sep>/PianoMelody.Web/Controllers/ProductsController.cs
namespace PianoMelody.Web.Controllers
{
using System.Linq;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using AutoMapper.QueryableExtensions;
using OrangeJetpack.Localization;
using Helpers;
using Models.BindingModels;
using Models.ViewModels;
using PianoMelody.Helpers;
using PianoMelody.Models;
[Authorize(Roles = "Admin")]
public class ProductsController : BaseController
{
[AllowAnonymous]
public ActionResult Index(int? group, int? manufacturer, int? condition, int page = 1)
{
this.LoadFilterLists(group, condition);
if (page < 1)
{
return this.RedirectToAction("Index");
}
var model = new ProductsWithPager();
var products = this.Data.Products.GetAll();
if (group != null)
{
products = products.Where(p => p.ArtilceGroup.Id == group);
}
if (manufacturer != null)
{
products = products.Where(p => p.Manufacturer.Id == manufacturer);
}
if (condition != null)
{
bool isNew = condition != 0;
products = products.Where(p => p.IsNew == isNew);
}
var pager = new Pager(products.Count(), page);
model.Pager = pager;
var productsView = products.OrderBy(a => a.Position)
.Skip((pager.CurrentPage - 1) * pager.PageSize)
.Take(pager.PageSize)
.ProjectTo<ProductViewModel>()
.Localize(this.CurrentCulture, a => a.Name, a => a.Description, a => a.ArticleGroupName, a => a.ManufacturerName);
model.Products = productsView;
return View(model);
}
[AllowAnonymous]
public ActionResult Promotions(int? manufacturer, int? condition)
{
this.LoadFilterLists(null, condition);
var products = this.Data.Products.GetAll().Where(p => p.PromoPrice != null);
if (manufacturer != null)
{
products = products.Where(p => p.Manufacturer.Id == manufacturer);
}
if (condition != null)
{
bool isNew = condition != 0;
products = products.Where(p => p.IsNew == isNew);
}
var productsView = products.OrderBy(a => a.Position)
.ProjectTo<ProductViewModel>()
.Localize(this.CurrentCulture, a => a.Name, a => a.Description, a => a.ArticleGroupName, a => a.ManufacturerName);
return View(productsView);
}
[AllowAnonymous]
public ActionResult SetView(string look, string returnUrl)
{
this.Session["look"] = look;
return Redirect(returnUrl);
}
[ChildActionOnly]
[AllowAnonymous]
public ActionResult Menu()
{
var articleGroups = this.Data.ArticleGroups.GetAll().OrderBy(ag => ag.Position)
.ProjectTo<ArticleGroupViewModel>()
.Localize(this.CurrentCulture, ag => ag.Name);
return this.View(articleGroups);
}
public ActionResult Create(string returnUrl)
{
this.LoadDropdownLists();
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(string returnUrl, ProductBindingModel productBindingModel)
{
if (!this.ModelState.IsValid)
{
this.LoadDropdownLists();
return this.View();
}
ReorderPosition(productBindingModel.Position);
var product = new Product()
{
Position = productBindingModel.Position,
Name = JsonHelper.Serialize(productBindingModel.EnName, productBindingModel.RuName, productBindingModel.BgName),
Description = JsonHelper.Serialize(productBindingModel.EnDescription, productBindingModel.RuDescription, productBindingModel.BgDescription),
Price = productBindingModel.Price,
PromoPrice = productBindingModel.PromoPrice,
IsNew = productBindingModel.IsNew,
IsSold = productBindingModel.IsSold,
ArticleGroupId = productBindingModel.ArticleGroupId,
ManufacturerId = productBindingModel.ManufacturerId
};
this.Data.Products.Add(product);
var multimedias = MultimediaHelper.CreateMultiple(this.Server, productBindingModel.Multimedias, this.GetBaseUrl());
if (multimedias != null)
{
foreach (var multimedia in multimedias)
{
multimedia.ProductId = product.Id;
this.Data.Multimedia.Add(multimedia);
}
}
this.Data.SaveChanges();
return Redirect(returnUrl);
}
public ActionResult Edit(int id, string returnUrl)
{
var currentProduct = this.Data.Products.Find(id);
if (currentProduct == null)
{
return this.RedirectToAction("Index");
}
var nameLocs = JsonHelper.Deserialize(currentProduct.Name);
var descriptionLocs = JsonHelper.Deserialize(currentProduct.Description);
var editProduct = new ProductBindingModel()
{
EnName = nameLocs[0].v,
RuName = nameLocs[1].v,
BgName = nameLocs[2].v,
EnDescription = descriptionLocs[0].v,
RuDescription = descriptionLocs[1].v,
BgDescription = descriptionLocs[2].v,
Position = currentProduct.Position,
Price = currentProduct.Price,
PromoPrice = currentProduct.PromoPrice,
IsNew = currentProduct.IsNew,
IsSold = currentProduct.IsSold,
ArticleGroupId = currentProduct.ArticleGroupId,
ManufacturerId = currentProduct.ManufacturerId,
};
this.LoadDropdownLists();
return View(editProduct);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, string returnUrl, ProductBindingModel productBindingModel)
{
if (!this.ModelState.IsValid)
{
this.LoadDropdownLists();
return this.View();
}
var currentProduct = this.Data.Products.Find(id);
if (currentProduct == null)
{
this.LoadDropdownLists();
return this.View();
}
ReorderPosition(productBindingModel.Position);
currentProduct.Name = JsonHelper.Serialize(productBindingModel.EnName, productBindingModel.RuName, productBindingModel.BgName);
currentProduct.Description = JsonHelper.Serialize(productBindingModel.EnDescription, productBindingModel.RuDescription, productBindingModel.BgDescription);
currentProduct.Price = productBindingModel.Price;
currentProduct.PromoPrice = productBindingModel.PromoPrice;
currentProduct.IsNew = productBindingModel.IsNew;
currentProduct.IsSold = productBindingModel.IsSold;
currentProduct.Position = productBindingModel.Position;
currentProduct.ArticleGroupId = productBindingModel.ArticleGroupId;
currentProduct.ManufacturerId = productBindingModel.ManufacturerId;
if (productBindingModel.Multimedias != null && productBindingModel.Multimedias.ElementAt(0) != null)
{
// Delete old multimedias if any
if (currentProduct.Multimedias.Count > 0)
{
MultimediaHelper.DeleteMultiple(this.Server, currentProduct.Multimedias);
foreach (var multimedia in currentProduct.Multimedias.ToList())
{
this.Data.Multimedia.Delete(multimedia);
}
}
// Create new multimedias
var multimedias = MultimediaHelper.CreateMultiple(this.Server, productBindingModel.Multimedias, this.GetBaseUrl());
foreach (var multimedia in multimedias)
{
multimedia.ProductId = currentProduct.Id;
this.Data.Multimedia.Add(multimedia);
}
}
this.Data.SaveChanges();
this.RePosition();
return Redirect(returnUrl);
}
public ActionResult Delete(int id, string returnUrl)
{
var deleteProduct = this.Data.Products.GetAll()
.ProjectTo<ProductViewModel>()
.FirstOrDefault(a => a.Id == id)
.Localize(this.CurrentCulture, a => a.Name, a => a.Description, a => a.ArticleGroupName, a => a.ManufacturerName);
if (deleteProduct == null)
{
return this.RedirectToAction("Index");
}
return View(deleteProduct);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id, string returnUrl, ProductViewModel productViewModel)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
var currentProduct = this.Data.Products.Find(id);
if (currentProduct == null)
{
return this.View();
}
if (currentProduct.Multimedias.Count > 0)
{
MultimediaHelper.DeleteMultiple(this.Server, currentProduct.Multimedias);
foreach (var multimadia in currentProduct.Multimedias.ToList())
{
this.Data.Multimedia.Delete(multimadia);
}
}
this.Data.Products.Delete(currentProduct);
this.Data.SaveChanges();
this.RePosition();
return Redirect(returnUrl);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Up(int id, string returnUrl)
{
var up = this.Data.Products.Find(id);
if (up != null)
{
var down = this.Data.Products.GetAll().FirstOrDefault(p => p.Position == up.Position - 1);
if (down != null)
{
int temp = up.Position;
up.Position = down.Position;
down.Position = temp;
this.Data.SaveChanges();
}
}
return this.Redirect(returnUrl);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Down(int id, string returnUrl)
{
var down = this.Data.Products.Find(id);
if (down != null)
{
var up = this.Data.Products.GetAll().FirstOrDefault(p => p.Position == down.Position + 1);
if (up != null)
{
int temp = up.Position;
up.Position = down.Position;
down.Position = temp;
this.Data.SaveChanges();
}
}
return this.Redirect(returnUrl);
}
private void ReorderPosition(int newPosition)
{
var products = this.Data.Products.GetAll().ToArray();
for (int i = 0; i < products.Length; i++)
{
if (products[i].Position == newPosition)
{
products[i].Position = newPosition + 1;
newPosition += 1;
}
}
}
private void RePosition()
{
var products = this.Data.Products.GetAll()
.OrderBy(a => a.Position)
.ThenByDescending(a => a.Id)
.ToList();
for (int i = 0; i < products.Count; i++)
{
products[i].Position = i + 1;
}
this.Data.SaveChanges();
}
/// <summary>
/// Load ArticleGroups and Manufacturers for dropdown lists
/// </summary>
private void LoadDropdownLists()
{
ViewBag.ArticleGroups = this.Data.ArticleGroups.GetAll()
.OrderBy(ag => ag.Name)
.ProjectTo<ArticleGroupViewModel>()
.Localize(this.CurrentCulture, ag => ag.Name)
.Select(ag => new SelectListItem
{
Text = ag.Name,
Value = ag.Id.ToString()
})
.ToList();
ViewBag.Manufacturers = this.Data.Manufacturers.GetAll()
.OrderBy(m => m.Name)
.ProjectTo<ManufacturerViewModel>()
.Localize(this.CurrentCulture, m => m.Name)
.Select(m => new SelectListItem
{
Text = m.Name,
Value = m.Id.ToString()
})
.ToList();
}
/// <summary>
/// Load Manufacturers and Condition filter lists
/// </summary>
private void LoadFilterLists(int? group, int? condition)
{
var manufacturers = this.Data.Manufacturers.GetAll().Where(m => m.Products.Count > 0);
if (group != null)
{
manufacturers = manufacturers.Where(m => m.Products.Any(p => p.ArticleGroupId == group));
}
if (condition != null)
{
bool isNew = condition != 0;
manufacturers = manufacturers.Where(m => m.Products.Any(p => p.IsNew == isNew));
}
ViewBag.Manufacturers = manufacturers.OrderBy(m => m.Name)
.ProjectTo<ManufacturerViewModel>()
.Localize(this.CurrentCulture, m => m.Name)
.Select(m => new SelectListItem
{
Text = m.Name,
Value = m.Id.ToString()
})
.ToList();
ViewBag.Condition = new List<SelectListItem>
{
new SelectListItem
{
Text = I18N.Resources._New,
Value = 1.ToString()
},
new SelectListItem
{
Text = I18N.Resources._SecondHand,
Value = 0.ToString()
}
};
}
}
}
<file_sep>/PianoMelody.Web/Controllers/GalleryController.cs
namespace PianoMelody.Web.Controllers
{
using System;
using System.Linq;
using System.Web.Mvc;
using AutoMapper.QueryableExtensions;
using OrangeJetpack.Localization;
using Extensions;
using Helpers;
using Models.BindingModels;
using Models.ViewModels;
using PianoMelody.Models;
using PianoMelody.Models.Enumetations;
[Authorize(Roles = "Admin")]
public class GalleryController : BaseController
{
[AllowAnonymous]
public ActionResult Index()
{
var gallery = this.Data.Multimedia.GetAll()
.Where(g => g.Type == MultimediaType.PhotoElement || g.Type == MultimediaType.VideoElement)
.OrderByDescending(g => g.Created)
.ProjectTo<GalleryViewModel>()
.Localize(this.CurrentCulture, g => g.Content);
return View(gallery);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(GalleryBindingModel galleryBindingModel)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
var content = JsonHelper.Serialize(galleryBindingModel.EnContent, galleryBindingModel.RuContent, galleryBindingModel.BgContent);
Multimedia multimedia = null;
if (galleryBindingModel.Multimedia != null)
{
multimedia = MultimediaHelper.CreateSingle
(
this.Server,
galleryBindingModel.Multimedia,
this.GetBaseUrl(),
MultimediaType.PhotoElement,
content
);
}
else if (galleryBindingModel.Url != null)
{
multimedia = new Multimedia
{
Created = DateTime.Now,
Type = MultimediaType.VideoElement,
Content = content,
Url = galleryBindingModel.Url
};
}
if (multimedia == null)
{
this.AddNotification(I18N.Resources._ErrSelectMultimedia, NotificationType.ERROR);
return this.View();
}
this.Data.Multimedia.Add(multimedia);
this.Data.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult Edit(int id)
{
var currentGalleryElement = this.Data.Multimedia.Find(id);
if (currentGalleryElement == null)
{
return this.RedirectToAction("Index");
}
var contentLocs = JsonHelper.Deserialize(currentGalleryElement.Content);
var editGalleryElement = new GalleryBindingModel()
{
Type = currentGalleryElement.Type,
EnContent = contentLocs[0].v,
RuContent = contentLocs[1].v,
BgContent = contentLocs[2].v,
Url = currentGalleryElement.Url
};
return View(editGalleryElement);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, GalleryBindingModel galleryBindingModel)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
var currentGalleryElement = this.Data.Multimedia.Find(id);
if (currentGalleryElement == null)
{
return this.View();
}
currentGalleryElement.Content = JsonHelper.Serialize(galleryBindingModel.EnContent, galleryBindingModel.RuContent, galleryBindingModel.BgContent);
if (galleryBindingModel.Type == MultimediaType.PhotoElement)
{
if (galleryBindingModel.Multimedia != null)
{
MultimediaHelper.DeleteSingle(this.Server, currentGalleryElement);
var multimedia = MultimediaHelper.CreateSingle
(
this.Server,
galleryBindingModel.Multimedia,
this.GetBaseUrl(),
MultimediaType.PhotoElement,
currentGalleryElement.Content
);
currentGalleryElement.Url = multimedia.Url;
}
}
else if (galleryBindingModel.Type == MultimediaType.VideoElement)
{
currentGalleryElement.Url = galleryBindingModel.Url;
}
this.Data.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult Delete(int id)
{
var deleteGalleryElement = this.Data.Multimedia.GetAll().ProjectTo<GalleryViewModel>()
.FirstOrDefault(g => g.Id == id)
.Localize(this.CurrentCulture, n => n.Content);
if (deleteGalleryElement == null)
{
return this.RedirectToAction("Index");
}
return View(deleteGalleryElement);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id, GalleryViewModel galleryViewModel)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
var currentGalleryElement = this.Data.Multimedia.Find(id);
if (currentGalleryElement == null)
{
return this.View();
}
if (currentGalleryElement.Type == MultimediaType.PhotoElement)
{
MultimediaHelper.DeleteSingle(this.Server, currentGalleryElement);
}
this.Data.Multimedia.Delete(currentGalleryElement);
this.Data.SaveChanges();
return RedirectToAction("Index");
}
}
}
<file_sep>/PianoMelody.Web/Controllers/ServicesController.cs
namespace PianoMelody.Web.Controllers
{
using System.Linq;
using System.Web.Mvc;
using AutoMapper.QueryableExtensions;
using OrangeJetpack.Localization;
using Helpers;
using Models.BindingModels;
using Models.ViewModels;
using PianoMelody.Helpers;
using PianoMelody.Models;
[Authorize(Roles = "Admin")]
public class ServicesController : BaseController
{
[AllowAnonymous]
public ActionResult Index(int page = 1)
{
if (page < 1)
{
return this.RedirectToAction("Index");
}
var model = new ServicesWithPager();
var pager = new Pager(this.Data.Services.GetAll().Count(), page);
model.Pager = pager;
var services = this.Data.Services.GetAll()
.OrderBy(s => s.Position)
.Skip((pager.CurrentPage - 1) * pager.PageSize)
.Take(pager.PageSize)
.ProjectTo<ServiceViewModel>()
.Localize(this.CurrentCulture, s => s.Name, s => s.Description);
model.Services = services;
return View(model);
}
public ActionResult Create(string returnUrl)
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(string returnUrl, ServiceBindingModel serviceBindingModel)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
var multimedia = MultimediaHelper.CreateSingle(this.Server, serviceBindingModel.Multimedia, this.GetBaseUrl());
if (multimedia != null)
{
this.Data.Multimedia.Add(multimedia);
}
var service = new Service()
{
Name = JsonHelper.Serialize(serviceBindingModel.EnName, serviceBindingModel.RuName, serviceBindingModel.BgName),
Description = JsonHelper.Serialize(serviceBindingModel.EnDescription, serviceBindingModel.RuDescription, serviceBindingModel.BgDescription),
Price = serviceBindingModel.Price,
Multimedia = multimedia
};
this.Data.Services.Add(service);
this.Data.SaveChanges();
return Redirect(returnUrl);
}
public ActionResult Edit(int id, string returnUrl)
{
var currentService = this.Data.Services.Find(id);
if (currentService == null)
{
return Redirect(returnUrl);
}
var nameLocs = JsonHelper.Deserialize(currentService.Name);
var descriptionLocs = JsonHelper.Deserialize(currentService.Description);
var editService = new ServiceBindingModel()
{
EnName = nameLocs[0].v,
RuName = nameLocs[1].v,
BgName = nameLocs[2].v,
EnDescription = descriptionLocs[0].v,
RuDescription = descriptionLocs[1].v,
BgDescription = descriptionLocs[2].v,
Price = currentService.Price
};
if (currentService.Multimedia != null)
{
editService.Url = currentService.Multimedia.Url;
}
return View(editService);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, string returnUrl, ServiceBindingModel serviceBindingModel)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
var currentService = this.Data.Services.Find(id);
if (currentService == null)
{
return this.View();
}
if (serviceBindingModel.Multimedia != null)
{
if (currentService.Multimedia != null)
{
MultimediaHelper.DeleteSingle(this.Server, currentService.Multimedia);
this.Data.Multimedia.Delete(currentService.Multimedia);
}
currentService.Multimedia = MultimediaHelper.CreateSingle(this.Server, serviceBindingModel.Multimedia, this.GetBaseUrl());
}
currentService.Name = JsonHelper.Serialize(serviceBindingModel.EnName, serviceBindingModel.RuName, serviceBindingModel.BgName);
currentService.Description = JsonHelper.Serialize(serviceBindingModel.EnDescription, serviceBindingModel.RuDescription, serviceBindingModel.BgDescription);
currentService.Price = serviceBindingModel.Price;
this.Data.SaveChanges();
return Redirect(returnUrl);
}
public ActionResult Delete(int id, string returnUrl)
{
var deleteService = this.Data.Services.GetAll().ProjectTo<ServiceViewModel>()
.FirstOrDefault(s => s.Id == id)
.Localize(this.CurrentCulture, s => s.Name, s => s.Description);
if (deleteService == null)
{
return Redirect(returnUrl);
}
return View(deleteService);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id, string returnUrl, ServiceViewModel serviceViewModel)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
var currentService = this.Data.Services.Find(id);
if (currentService == null)
{
return this.View();
}
if (currentService.Multimedia != null)
{
MultimediaHelper.DeleteSingle(this.Server, currentService.Multimedia);
this.Data.Multimedia.Delete(currentService.Multimedia);
}
this.Data.Services.Delete(currentService);
this.Data.SaveChanges();
this.RePosition();
return Redirect(returnUrl);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Up(int id, string returnUrl)
{
var up = this.Data.Services.Find(id);
if (up != null)
{
var down = this.Data.Services.GetAll().FirstOrDefault(p => p.Position == up.Position - 1);
if (down != null)
{
int temp = up.Position;
up.Position = down.Position;
down.Position = temp;
this.Data.SaveChanges();
}
}
return this.Redirect(returnUrl);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Down(int id, string returnUrl)
{
var down = this.Data.Services.Find(id);
if (down != null)
{
var up = this.Data.Services.GetAll().FirstOrDefault(p => p.Position == down.Position + 1);
if (up != null)
{
int temp = up.Position;
up.Position = down.Position;
down.Position = temp;
this.Data.SaveChanges();
}
}
return this.Redirect(returnUrl);
}
private void RePosition()
{
var services = this.Data.Services.GetAll().OrderBy(a => a.Position).ToList();
for (int i = 0; i < services.Count; i++)
{
services[i].Position = i + 1;
}
this.Data.SaveChanges();
}
}
}
<file_sep>/PianoMelody.Web/Models/ViewModels/ArticleGroupViewModel.cs
using OrangeJetpack.Localization;
using PianoMelody.Helpers;
using PianoMelody.Models;
using PianoMelody.Web.Contracts;
using System.Collections.Generic;
namespace PianoMelody.Web.Models.ViewModels
{
public class ArticleGroupViewModel : IMapFrom<ArticleGroup>, ILocalizable
{
public int Id { get; set; }
public int Position { get; set; }
[Localized]
public string Name { get; set; }
}
public class ArticleGroupsWithPager
{
public IEnumerable<ArticleGroupViewModel> ArticleGroups { get; set; }
public Pager Pager { get; set; }
}
}<file_sep>/PianoMelody.Web/Models/BindingModels/ArticleGroupBindingModel.cs
using PianoMelody.I18N;
using System.ComponentModel.DataAnnotations;
namespace PianoMelody.Web.Models.BindingModels
{
public class ArticleGroupBindingModel
{
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
[Display(Name = "_EnName", ResourceType = typeof(Resources))]
public string EnName { get; set; }
[Display(Name = "_RuName", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string RuName { get; set; }
[Display(Name = "_BgName", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string BgName { get; set; }
}
}<file_sep>/PianoMelody.I18N/Resources.cs
using System.Globalization;
using PianoMelody.I18N.Abstract;
using PianoMelody.I18N.Concrete;
namespace PianoMelody.I18N
{
public class Resources
{
private static IResourceProvider resourceProvider = new DbResourceProvider();
public static void Refresh()
{
resourceProvider = new DbResourceProvider();
}
/// <summary>Add administrator</summary>
public static string _AddAdministrator
{
get
{
return (string) resourceProvider.GetResource("_AddAdministrator", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Add label</summary>
public static string _AddLabel
{
get
{
return (string) resourceProvider.GetResource("_AddLabel", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Address</summary>
public static string _Address
{
get
{
return (string) resourceProvider.GetResource("_Address", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Administration</summary>
public static string _Administration
{
get
{
return (string) resourceProvider.GetResource("_Administration", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Are we agent</summary>
public static string _AreWeAgent
{
get
{
return (string) resourceProvider.GetResource("_AreWeAgent", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Are you sure you want to delete this?</summary>
public static string _AreYouSure
{
get
{
return (string) resourceProvider.GetResource("_AreYouSure", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Article group</summary>
public static string _ArticleGroup
{
get
{
return (string) resourceProvider.GetResource("_ArticleGroup", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Article groups</summary>
public static string _ArticleGroups
{
get
{
return (string) resourceProvider.GetResource("_ArticleGroups", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Ask about</summary>
public static string _AskAbout
{
get
{
return (string) resourceProvider.GetResource("_AskAbout", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Availability</summary>
public static string _Availability
{
get
{
return (string) resourceProvider.GetResource("_Availability", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>BG Content</summary>
public static string _BgContent
{
get
{
return (string) resourceProvider.GetResource("_BgContent", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>BG Description</summary>
public static string _BgDescription
{
get
{
return (string) resourceProvider.GetResource("_BgDescription", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>BG Name</summary>
public static string _BgName
{
get
{
return (string) resourceProvider.GetResource("_BgName", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>BG Title</summary>
public static string _BgTitle
{
get
{
return (string) resourceProvider.GetResource("_BgTitle", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Cancel</summary>
public static string _Cancel
{
get
{
return (string) resourceProvider.GetResource("_Cancel", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Carousel</summary>
public static string _Carousel
{
get
{
return (string) resourceProvider.GetResource("_Carousel", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Change password</summary>
public static string _ChangePassword
{
get
{
return (string) resourceProvider.GetResource("_ChangePassword", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Clear</summary>
public static string _Clear
{
get
{
return (string) resourceProvider.GetResource("_Clear", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Condition</summary>
public static string _Condition
{
get
{
return (string) resourceProvider.GetResource("_Condition", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Confirm password</summary>
public static string _ConfirmPassword
{
get
{
return (string) resourceProvider.GetResource("_ConfirmPassword", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Contact form</summary>
public static string _ContactForm
{
get
{
return (string) resourceProvider.GetResource("_ContactForm", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Contact form enquery</summary>
public static string _ContactFormSubject
{
get
{
return (string) resourceProvider.GetResource("_ContactFormSubject", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Date created</summary>
public static string _Created
{
get
{
return (string) resourceProvider.GetResource("_Created", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Create</summary>
public static string _CreateNew
{
get
{
return (string) resourceProvider.GetResource("_CreateNew", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Current password</summary>
public static string _CurrentPassword
{
get
{
return (string) resourceProvider.GetResource("_CurrentPassword", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Delete</summary>
public static string _Delete
{
get
{
return (string) resourceProvider.GetResource("_Delete", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Description</summary>
public static string _Description
{
get
{
return (string) resourceProvider.GetResource("_Description", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Dictionary</summary>
public static string _Dict
{
get
{
return (string) resourceProvider.GetResource("_Dict", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Edit</summary>
public static string _Edit
{
get
{
return (string) resourceProvider.GetResource("_Edit", CultureInfo.CurrentUICulture.Name);
}
}
public static string _EditAbout
{
get
{
return (string) resourceProvider.GetResource("_EditAbout", CultureInfo.CurrentUICulture.Name);
}
}
public static string _EditAddress
{
get
{
return (string) resourceProvider.GetResource("_EditAddress", CultureInfo.CurrentUICulture.Name);
}
}
public static string _EditContact
{
get
{
return (string) resourceProvider.GetResource("_EditContact", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Email</summary>
public static string _Email
{
get
{
return (string) resourceProvider.GetResource("_Email", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Your enquery has been sent successfully</summary>
public static string _EmailSentSuccessfully
{
get
{
return (string) resourceProvider.GetResource("_EmailSentSuccessfully", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>EN Content</summary>
public static string _EnContent
{
get
{
return (string) resourceProvider.GetResource("_EnContent", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>EN Description</summary>
public static string _EnDescription
{
get
{
return (string) resourceProvider.GetResource("_EnDescription", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>EN Name</summary>
public static string _EnName
{
get
{
return (string) resourceProvider.GetResource("_EnName", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>EN Title</summary>
public static string _EnTitle
{
get
{
return (string) resourceProvider.GetResource("_EnTitle", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>The {0} field is not valid email address</summary>
public static string _ErrInvalidEmail
{
get
{
return (string) resourceProvider.GetResource("_ErrInvalidEmail", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Invalid price</summary>
public static string _ErrInvalidPrice
{
get
{
return (string) resourceProvider.GetResource("_ErrInvalidPrice", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>The {0} field must be at least {2} characters long</summary>
public static string _ErrLenghtValidation
{
get
{
return (string) resourceProvider.GetResource("_ErrLenghtValidation", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>The field is required</summary>
public static string _ErrRequired
{
get
{
return (string) resourceProvider.GetResource("_ErrRequired", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Please select multimedia</summary>
public static string _ErrSelectMultimedia
{
get
{
return (string) resourceProvider.GetResource("_ErrSelectMultimedia", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Filter</summary>
public static string _Filter
{
get
{
return (string) resourceProvider.GetResource("_Filter", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Gallery image</summary>
public static string _GalleryImage
{
get
{
return (string) resourceProvider.GetResource("_GalleryImage", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>In stock</summary>
public static string _InStock
{
get
{
return (string) resourceProvider.GetResource("_InStock", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>New</summary>
public static string _IsNew
{
get
{
return (string) resourceProvider.GetResource("_IsNew", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Is sold</summary>
public static string _IsSold
{
get
{
return (string) resourceProvider.GetResource("_IsSold", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Key</summary>
public static string _Key
{
get
{
return (string) resourceProvider.GetResource("_Key", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>label</summary>
public static string _Label
{
get
{
return (string) resourceProvider.GetResource("_Label", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Label created</summary>
public static string _LabelCreated
{
get
{
return (string) resourceProvider.GetResource("_LabelCreated", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Label updated</summary>
public static string _LabelUpdated
{
get
{
return (string) resourceProvider.GetResource("_LabelUpdated", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Login</summary>
public static string _Login
{
get
{
return (string) resourceProvider.GetResource("_Login", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Log Off</summary>
public static string _LogOff
{
get
{
return (string) resourceProvider.GetResource("_LogOff", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Manufacturer</summary>
public static string _Manufacturer
{
get
{
return (string) resourceProvider.GetResource("_Manufacturer", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Manufacturers</summary>
public static string _Manufacturers
{
get
{
return (string) resourceProvider.GetResource("_Manufacturers", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Message</summary>
public static string _Message
{
get
{
return (string) resourceProvider.GetResource("_Message", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Name</summary>
public static string _Name
{
get
{
return (string) resourceProvider.GetResource("_Name", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Negotiable</summary>
public static string _Negotiable
{
get
{
return (string) resourceProvider.GetResource("_Negotiable", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>New</summary>
public static string _New
{
get
{
return (string) resourceProvider.GetResource("_New", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>New password</summary>
public static string _NewPassword
{
get
{
return (string) resourceProvider.GetResource("_NewPassword", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>News</summary>
public static string _News
{
get
{
return (string) resourceProvider.GetResource("_News", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Password</summary>
public static string _Password
{
get
{
return (string) resourceProvider.GetResource("_Password", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>The passwords do not match</summary>
public static string _PasswordValidation
{
get
{
return (string) resourceProvider.GetResource("_PasswordValidation", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Phone</summary>
public static string _Phone
{
get
{
return (string) resourceProvider.GetResource("_Phone", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Photo</summary>
public static string _Photo
{
get
{
return (string) resourceProvider.GetResource("_Photo", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Photos</summary>
public static string _Photos
{
get
{
return (string) resourceProvider.GetResource("_Photos", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Position</summary>
public static string _Position
{
get
{
return (string) resourceProvider.GetResource("_Position", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Product</summary>
public static string _Product
{
get
{
return (string) resourceProvider.GetResource("_Product", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Promotion</summary>
public static string _PromoPrice
{
get
{
return (string) resourceProvider.GetResource("_PromoPrice", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Reference</summary>
public static string _Reference
{
get
{
return (string) resourceProvider.GetResource("_Reference", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>RU Content</summary>
public static string _RuContent
{
get
{
return (string) resourceProvider.GetResource("_RuContent", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>RU Description</summary>
public static string _RuDescription
{
get
{
return (string) resourceProvider.GetResource("_RuDescription", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>RU Name</summary>
public static string _RuName
{
get
{
return (string) resourceProvider.GetResource("_RuName", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>RU Title</summary>
public static string _RuTitle
{
get
{
return (string) resourceProvider.GetResource("_RuTitle", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Save</summary>
public static string _Save
{
get
{
return (string) resourceProvider.GetResource("_Save", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Second hand</summary>
public static string _SecondHand
{
get
{
return (string) resourceProvider.GetResource("_SecondHand", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Send</summary>
public static string _Send
{
get
{
return (string) resourceProvider.GetResource("_Send", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Service</summary>
public static string _Service
{
get
{
return (string) resourceProvider.GetResource("_Service", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Sold out</summary>
public static string _SoldOut
{
get
{
return (string) resourceProvider.GetResource("_SoldOut", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Type</summary>
public static string _Type
{
get
{
return (string) resourceProvider.GetResource("_Type", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Url address</summary>
public static string _UrlAddress
{
get
{
return (string) resourceProvider.GetResource("_UrlAddress", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Video</summary>
public static string _Video
{
get
{
return (string) resourceProvider.GetResource("_Video", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Video Url</summary>
public static string _VideoUrl
{
get
{
return (string) resourceProvider.GetResource("_VideoUrl", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Without choice</summary>
public static string _WithoutChoice
{
get
{
return (string) resourceProvider.GetResource("_WithoutChoice", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>About us</summary>
public static string About
{
get
{
return (string) resourceProvider.GetResource("About", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Melodia</summary>
public static string AboutDescription
{
get
{
return (string) resourceProvider.GetResource("AboutDescription", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Melodia</summary>
public static string AboutKeywords
{
get
{
return (string) resourceProvider.GetResource("AboutKeywords", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Accessories</summary>
public static string Accessories
{
get
{
return (string) resourceProvider.GetResource("Accessories", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Accessories, stools and metronoms</summary>
public static string AccessoriesDescription
{
get
{
return (string) resourceProvider.GetResource("AccessoriesDescription", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>accessories, stools, piano benches, metronoms, lamps</summary>
public static string AccessoriesKeywords
{
get
{
return (string) resourceProvider.GetResource("AccessoriesKeywords", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Accordions</summary>
public static string Accordions
{
get
{
return (string) resourceProvider.GetResource("Accordions", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Accordions new and second hand</summary>
public static string AccordionsDescription
{
get
{
return (string) resourceProvider.GetResource("AccordionsDescription", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>accordion,accordions</summary>
public static string AccordionsKeywords
{
get
{
return (string) resourceProvider.GetResource("AccordionsKeywords", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Acoustic pianos</summary>
public static string AcousticPianos
{
get
{
return (string) resourceProvider.GetResource("AcousticPianos", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Acoustic pianos</summary>
public static string AcousticPianosDescription
{
get
{
return (string) resourceProvider.GetResource("AcousticPianosDescription", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>piano, pianos, grand piano, acoustic</summary>
public static string AcousticPianosKeywords
{
get
{
return (string) resourceProvider.GetResource("AcousticPianosKeywords", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>All</summary>
public static string All
{
get
{
return (string) resourceProvider.GetResource("All", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Contacts</summary>
public static string Contacts
{
get
{
return (string) resourceProvider.GetResource("Contacts", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Address, contacts and working time</summary>
public static string ContactsDescription
{
get
{
return (string) resourceProvider.GetResource("ContactsDescription", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>address, contact, contacts, working time</summary>
public static string ContactsKeywords
{
get
{
return (string) resourceProvider.GetResource("ContactsKeywords", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Digital pianos</summary>
public static string DigitalPianos
{
get
{
return (string) resourceProvider.GetResource("DigitalPianos", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Digital pianos</summary>
public static string DigitalPianosDescription
{
get
{
return (string) resourceProvider.GetResource("DigitalPianosDescription", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>digital, pianos, Piano</summary>
public static string DigitalPianosKeywords
{
get
{
return (string) resourceProvider.GetResource("DigitalPianosKeywords", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Gallery</summary>
public static string Gallery
{
get
{
return (string) resourceProvider.GetResource("Gallery", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Video and photo content about us</summary>
public static string GalleryDescription
{
get
{
return (string) resourceProvider.GetResource("GalleryDescription", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>video,photo,multimedia,content</summary>
public static string GalleryKeywords
{
get
{
return (string) resourceProvider.GetResource("GalleryKeywords", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Piano shop</summary>
public static string Home
{
get
{
return (string) resourceProvider.GetResource("Home", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Piano shop Melody, sale of pianos and grand pianos. Import and export of new and second hand pianos. Exclusive representative for PETROF, C.BECHSTEIN and others for BULGARIA.</summary>
public static string HomeDescription
{
get
{
return (string) resourceProvider.GetResource("HomeDescription", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Melody piano lounge, piano, grand piano, royals, used piano, music, music store, metronomes, guitar, accordion, music, piano bar, stools</summary>
public static string HomeKeywords
{
get
{
return (string) resourceProvider.GetResource("HomeKeywords", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Useful information</summary>
public static string Info
{
get
{
return (string) resourceProvider.GetResource("Info", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Useful information</summary>
public static string InfoDescription
{
get
{
return (string) resourceProvider.GetResource("InfoDescription", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>useful,information,info,about,pianos</summary>
public static string InfoKeywords
{
get
{
return (string) resourceProvider.GetResource("InfoKeywords", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Melodia</summary>
public static string Logo
{
get
{
return (string) resourceProvider.GetResource("Logo", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>News</summary>
public static string News
{
get
{
return (string) resourceProvider.GetResource("News", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Our news</summary>
public static string NewsDescription
{
get
{
return (string) resourceProvider.GetResource("NewsDescription", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>news,media</summary>
public static string NewsKeywords
{
get
{
return (string) resourceProvider.GetResource("NewsKeywords", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Price</summary>
public static string Price
{
get
{
return (string) resourceProvider.GetResource("Price", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Products</summary>
public static string Products
{
get
{
return (string) resourceProvider.GetResource("Products", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Our products are pianos, royals and accessoaries</summary>
public static string ProductsDescription
{
get
{
return (string) resourceProvider.GetResource("ProductsDescription", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>products,pianos,royals,accessoaries</summary>
public static string ProductsKeywords
{
get
{
return (string) resourceProvider.GetResource("ProductsKeywords", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Sale</summary>
public static string Promotions
{
get
{
return (string) resourceProvider.GetResource("Promotions", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Sales pianos, grand pianos and accessories</summary>
public static string PromotionsDescription
{
get
{
return (string) resourceProvider.GetResource("PromotionsDescription", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>sale, promotion, promotions</summary>
public static string PromotionsKeywords
{
get
{
return (string) resourceProvider.GetResource("PromotionsKeywords", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>References</summary>
public static string References
{
get
{
return (string) resourceProvider.GetResource("References", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Our references </summary>
public static string ReferencesDescription
{
get
{
return (string) resourceProvider.GetResource("ReferencesDescription", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>References</summary>
public static string ReferencesKeywords
{
get
{
return (string) resourceProvider.GetResource("ReferencesKeywords", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Grand pianos</summary>
public static string Royals
{
get
{
return (string) resourceProvider.GetResource("Royals", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Grand pianos new and second hand</summary>
public static string RoyalsDescription
{
get
{
return (string) resourceProvider.GetResource("RoyalsDescription", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>grand piano, grand pianos</summary>
public static string RoyalsKeywords
{
get
{
return (string) resourceProvider.GetResource("RoyalsKeywords", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Services</summary>
public static string Services
{
get
{
return (string) resourceProvider.GetResource("Services", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Transport and delivery of piano and grand piano. Rental of pianos and grand pianos. Restoration and tuning. Piano lessons.</summary>
public static string ServicesDescription
{
get
{
return (string) resourceProvider.GetResource("ServicesDescription", CultureInfo.CurrentUICulture.Name);
}
}
/// <summary>Transportation, handling, piano, rental, tuning, restoration, lessons</summary>
public static string ServicesKeywords
{
get
{
return (string) resourceProvider.GetResource("ServicesKeywords", CultureInfo.CurrentUICulture.Name);
}
}
}
}
<file_sep>/PianoMelody.Web/Models/ViewModels/HomeViewModel.cs
using System.Collections.Generic;
namespace PianoMelody.Web.Models.ViewModels
{
public class HomeViewModel
{
public CarouselViewModel[] Carousel { get; set; }
public ProductViewModel[] PromoProducts { get; set; }
public NewsViewModel[] LastNews { get; set; }
public ReferenceViewModel[] RandomReferences { get; set; }
public IEnumerable<ManufacturerViewModel> Manufacturers { get; set; }
}
}<file_sep>/PianoMelody.Web/Scripts/Custom/image-preview.js
$(document).ready(function () {
function previewImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#image-preview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#file").change(function () {
previewImage(this);
});
});<file_sep>/PianoMelody.Web/Models/BindingModels/ServiceBindingModel.cs
using PianoMelody.I18N;
using System.ComponentModel.DataAnnotations;
using System.Web;
namespace PianoMelody.Web.Models.BindingModels
{
public class ServiceBindingModel
{
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
[Display(Name = "_EnName", ResourceType = typeof(Resources))]
public string EnName { get; set; }
[Display(Name = "_RuName", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string RuName { get; set; }
[Display(Name = "_BgName", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string BgName { get; set; }
[DataType(DataType.MultilineText)]
[Display(Name = "_EnDescription", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string EnDescription { get; set; }
[DataType(DataType.MultilineText)]
[Display(Name = "_RuDescription", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string RuDescription { get; set; }
[DataType(DataType.MultilineText)]
[Display(Name = "_BgDescription", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string BgDescription { get; set; }
[Display(Name = "Price", ResourceType = typeof(Resources))]
[RegularExpression(@"^\d*(\.|,|(\.\d{1,2})|(,\d{1,2}))?$", ErrorMessage = "Invalid price")]
public decimal? Price { get; set; }
[Display(Name = "_Photo", ResourceType = typeof(Resources))]
public HttpPostedFileBase Multimedia { get; set; }
public string Url { get; set; }
}
}<file_sep>/PianoMelody.Web/Controllers/InfoController.cs
namespace PianoMelody.Web.Controllers
{
using System;
using System.Linq;
using System.Web.Mvc;
using AutoMapper.QueryableExtensions;
using OrangeJetpack.Localization;
using Helpers;
using Models.BindingModels;
using Models.ViewModels;
using PianoMelody.Helpers;
using PianoMelody.Models;
[Authorize(Roles = "Admin")]
public class InfoController : BaseController
{
[AllowAnonymous]
public ActionResult Index(int page = 1)
{
if (page < 1)
{
return this.RedirectToAction("Index");
}
var model = new InfoWithPager();
var pager = new Pager(this.Data.Informations.GetAll().Count(), page);
model.Pager = pager;
var informations = this.Data.Informations.GetAll()
.OrderBy(i => i.Position)
.Skip((pager.CurrentPage - 1) * pager.PageSize)
.Take(pager.PageSize)
.ProjectTo<InfoViewModel>()
.Localize(this.CurrentCulture, i => i.Title, i => i.Content);
model.Informations = informations;
return View(model);
}
public ActionResult Create(string returnUrl)
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(string returnUrl, InfoBindingModel infoBindingModel)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
var multimedia = MultimediaHelper.CreateSingle(this.Server, infoBindingModel.Multimedia, this.GetBaseUrl());
if (multimedia != null)
{
this.Data.Multimedia.Add(multimedia);
}
var info = new Information()
{
Created = DateTime.Now,
Title = JsonHelper.Serialize(infoBindingModel.EnTitle, infoBindingModel.RuTitle, infoBindingModel.BgTitle),
Content = JsonHelper.Serialize(infoBindingModel.EnContent, infoBindingModel.RuContent, infoBindingModel.BgContent),
Multimedia = multimedia
};
this.Data.Informations.Add(info);
this.Data.SaveChanges();
return Redirect(returnUrl);
}
public ActionResult Edit(int id, string returnUrl)
{
var currentInfo = this.Data.Informations.Find(id);
if (currentInfo == null)
{
return Redirect(returnUrl);
}
var titleLocs = JsonHelper.Deserialize(currentInfo.Title);
var contentLocs = JsonHelper.Deserialize(currentInfo.Content);
var editInfo = new InfoBindingModel()
{
EnTitle = titleLocs[0].v,
RuTitle = titleLocs[1].v,
BgTitle = titleLocs[2].v,
EnContent = contentLocs[0].v,
RuContent = contentLocs[1].v,
BgContent = contentLocs[2].v
};
if (currentInfo.Multimedia != null)
{
editInfo.Url = currentInfo.Multimedia.Url;
}
return View(editInfo);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, string returnUrl, InfoBindingModel infoBindingModel)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
var currentInfo = this.Data.Informations.Find(id);
if (currentInfo == null)
{
return this.View();
}
if (infoBindingModel.Multimedia != null)
{
if (currentInfo.Multimedia != null)
{
MultimediaHelper.DeleteSingle(this.Server, currentInfo.Multimedia);
this.Data.Multimedia.Delete(currentInfo.Multimedia);
}
currentInfo.Multimedia = MultimediaHelper.CreateSingle(this.Server, infoBindingModel.Multimedia, this.GetBaseUrl());
}
currentInfo.Title = JsonHelper.Serialize(infoBindingModel.EnTitle, infoBindingModel.RuTitle, infoBindingModel.BgTitle);
currentInfo.Content = JsonHelper.Serialize(infoBindingModel.EnContent, infoBindingModel.RuContent, infoBindingModel.BgContent);
this.Data.SaveChanges();
return Redirect(returnUrl);
}
public ActionResult Delete(int id, string returnUrl)
{
var deleteInfo = this.Data.Informations.GetAll().ProjectTo<InfoViewModel>()
.FirstOrDefault(i => i.Id == id)
.Localize(this.CurrentCulture, i => i.Title, i => i.Content);
if (deleteInfo == null)
{
return Redirect(returnUrl);
}
return View(deleteInfo);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id, string returnUrl, InfoViewModel infoViewModel)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
var currentInfo = this.Data.Informations.Find(id);
if (currentInfo == null)
{
return this.View();
}
if (currentInfo.Multimedia != null)
{
MultimediaHelper.DeleteSingle(this.Server, currentInfo.Multimedia);
this.Data.Multimedia.Delete(currentInfo.Multimedia);
}
this.Data.Informations.Delete(currentInfo);
this.Data.SaveChanges();
this.RePosition();
return Redirect(returnUrl);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Up(int id, string returnUrl)
{
var up = this.Data.Informations.Find(id);
if (up != null)
{
var down = this.Data.Informations.GetAll().FirstOrDefault(p => p.Position == up.Position - 1);
if (down != null)
{
int temp = up.Position;
up.Position = down.Position;
down.Position = temp;
this.Data.SaveChanges();
}
}
return this.Redirect(returnUrl);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Down(int id, string returnUrl)
{
var down = this.Data.Informations.Find(id);
if (down != null)
{
var up = this.Data.Informations.GetAll().FirstOrDefault(p => p.Position == down.Position + 1);
if (up != null)
{
int temp = up.Position;
up.Position = down.Position;
down.Position = temp;
this.Data.SaveChanges();
}
}
return this.Redirect(returnUrl);
}
private void RePosition()
{
var informations = this.Data.Informations.GetAll().OrderBy(a => a.Position).ToList();
for (int i = 0; i < informations.Count; i++)
{
informations[i].Position = i + 1;
}
this.Data.SaveChanges();
}
}
}
<file_sep>/PianoMelody.Web/Models/ViewModels/LoginViewModel.cs
namespace PianoMelody.Web.Models.ViewModels
{
using System.ComponentModel.DataAnnotations;
using I18N;
public class LoginViewModel
{
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
[Display(Name = "_Email", ResourceType = typeof(Resources))]
public string Email { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
[DataType(DataType.Password)]
[Display(Name = "_Password", ResourceType = typeof(Resources))]
public string Password { get; set; }
}
}<file_sep>/PianoMelody.Models/Multimedia.cs
using PianoMelody.Models.Enumetations;
using System;
using System.ComponentModel.DataAnnotations;
namespace PianoMelody.Models
{
public class Multimedia
{
[Key]
public int Id { get; set; }
public int Position { get; set; }
public DateTime Created { get; set; }
public string Url { get; set; }
public string DataSize { get; set; }
public string Content { get; set; }
public MultimediaType Type { get; set; }
public int? ProductId { get; set; }
public virtual Product Product { get; set; }
}
}
<file_sep>/PianoMelody.Data/Contracts/IPianoMelodyData.cs
namespace PianoMelody.Data.Contracts
{
using Models;
public interface IPianoMelodyData
{
IRepository<User> Users { get; }
IRepository<Resources> Resources { get; }
IRepository<ArticleGroup> ArticleGroups { get; }
IRepository<Product> Products { get; }
IRepository<Service> Services { get; }
IRepository<News> News { get; }
IRepository<Information> Informations { get; }
IRepository<Reference> References { get; }
IRepository<Manufacturer> Manufacturers { get; }
IRepository<Multimedia> Multimedia { get; }
int SaveChanges();
}
}<file_sep>/PianoMelody.Data/PianoMelodyData.cs
namespace PianoMelody.Data
{
using System;
using System.Collections.Generic;
using System.Data.Entity;
using Contracts;
using Models;
public class PianoMelodyData : IPianoMelodyData
{
private DbContext context;
private Dictionary<Type, object> repositories;
public PianoMelodyData()
: this(new PianoMelodyContext())
{
}
public PianoMelodyData(DbContext context)
{
this.context = context;
this.repositories = new Dictionary<Type, object>();
}
public IRepository<ArticleGroup> ArticleGroups
{
get
{
return this.GetRepository<ArticleGroup>();
}
}
public IRepository<Product> Products
{
get
{
return this.GetRepository<Product>();
}
}
public IRepository<Information> Informations
{
get
{
return this.GetRepository<Information>();
}
}
public IRepository<Manufacturer> Manufacturers
{
get
{
return this.GetRepository<Manufacturer>();
}
}
public IRepository<Multimedia> Multimedia
{
get
{
return this.GetRepository<Multimedia>();
}
}
public IRepository<News> News
{
get
{
return this.GetRepository<News>();
}
}
public IRepository<Reference> References
{
get
{
return this.GetRepository<Reference>();
}
}
public IRepository<Resources> Resources
{
get
{
return this.GetRepository<Resources>();
}
}
public IRepository<Service> Services
{
get
{
return this.GetRepository<Service>();
}
}
public IRepository<User> Users
{
get
{
return this.GetRepository<User>();
}
}
public int SaveChanges()
{
return this.context.SaveChanges();
}
private IRepository<T> GetRepository<T>() where T : class
{
var typeOfModel = typeof(T);
if (!this.repositories.ContainsKey(typeOfModel))
{
var type = typeof(Repository<T>);
this.repositories.Add(typeOfModel, Activator.CreateInstance(type, this.context));
}
return (IRepository<T>)this.repositories[typeOfModel];
}
}
}<file_sep>/PianoMelody.Web/App_Start/RouteConfig.cs
namespace PianoMelody.Web
{
using Helpers;
using LowercaseRoutesMVC;
using System.Web.Mvc;
using System.Web.Routing;
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRouteLowercase(
name: "Admin",
url: "{culture}/admin",
defaults: new
{
culture = CultureHelper.GetDefaultCulture(),
controller = "Account",
action = "Login"
}
);
routes.MapRouteLowercase(
name: "About",
url: "{culture}/about-us",
defaults: new
{
culture = CultureHelper.GetDefaultCulture(),
controller = "Home",
action = "About"
}
);
routes.MapRouteLowercase(
name: "Contact",
url: "{culture}/contact-us",
defaults: new
{
culture = CultureHelper.GetDefaultCulture(),
controller = "Home",
action = "Contact"
}
);
routes.MapRouteLowercase(
name: "DefaultLocalized",
url: "{culture}/{controller}/{action}/{id}",
defaults: new
{
culture = CultureHelper.GetDefaultCulture(),
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
}
}
}<file_sep>/PianoMelody.Web/App_Start/BundleConfig.cs
namespace PianoMelody.Web
{
using System.Web.Optimization;
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(
new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-3.1.0.min.js"));
bundles.Add(
new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(
new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-2.8.3.js"));
bundles.Add(
new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.min.js",
"~/Scripts/respond.min.js"));
bundles.Add(
new ScriptBundle("~/bundles/shared").Include(
"~/Scripts/Custom/shared.js"));
bundles.Add(
new ScriptBundle("~/bundles/image-preview").Include(
"~/Scripts/Custom/image-preview.js"));
bundles.Add(
new ScriptBundle("~/bundles/images-preview").Include(
"~/Scripts/Custom/images-preview.js"));
bundles.Add(
new ScriptBundle("~/bundles/photoswipe").Include(
"~/Scripts/photoswipe/photoswipe.min.js",
"~/Scripts/photoswipe/photoswipe-ui-default.min.js"));
bundles.Add(
new ScriptBundle("~/bundles/load-gallery").Include(
"~/Scripts/Custom/photoswipe-function.js",
"~/Scripts/Custom/load-gallery.js"));
bundles.Add(
new ScriptBundle("~/bundles/owl-carousel").Include(
"~/Scripts/owl.carousel.min.js"));
bundles.Add(
new StyleBundle("~/Content/owl").Include(
"~/Content/OwlCarousel/owl.carousel.css",
"~/Content/OwlCarousel/owl.theme.css",
"~/Content/OwlCarousel/owl.transitions.css"
));
bundles.Add(
new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.min.css",
"~/Content/photoswipe/photoswipe.css",
"~/Content/photoswipe/default-skin/default-skin.css",
"~/Content/site.css"));
}
}
}<file_sep>/PianoMelody.Web/Models/BindingModels/GalleryBindingModel.cs
using PianoMelody.I18N;
using PianoMelody.Models.Enumetations;
using System.ComponentModel.DataAnnotations;
using System.Web;
namespace PianoMelody.Web.Models.BindingModels
{
public class GalleryBindingModel
{
public MultimediaType Type { get; set; }
[DataType(DataType.MultilineText)]
[Display(Name = "_EnContent", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string EnContent { get; set; }
[DataType(DataType.MultilineText)]
[Display(Name = "_RuContent", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string RuContent { get; set; }
[DataType(DataType.MultilineText)]
[Display(Name = "_BgContent", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string BgContent { get; set; }
[Display(Name = "_Photo", ResourceType = typeof(Resources))]
public HttpPostedFileBase Multimedia { get; set; }
public string Url { get; set; }
}
}<file_sep>/PianoMelody.Web/Extensions/LinqExtensions.cs
using System;
using System.Linq;
using System.Linq.Expressions;
namespace PianoMelody.Web.Extensions
{
public static class LinqExtensions
{
/// <summary>
/// Get random elements while process query
/// </summary>
/// <typeparam name="T">The type of the objects</typeparam>
/// <param name="query">this Queryable</param>
/// <param name="e">lambda expression</param>
/// <param name="number">The count of the required random elements</param>
/// <returns>this Queryable</returns>
public static IQueryable<T> RandomElements<T>(this IQueryable<T> query, Expression<Func<T, bool>> e, int number = 1)
{
var rand = new Random();
query = query.Where(e);
return query.Skip(rand.Next(query.Count()))
.Take(number);
}
}
}<file_sep>/PianoMelody.Web/Models/ViewModels/GalleryViewModel.cs
using OrangeJetpack.Localization;
using PianoMelody.Models;
using PianoMelody.Models.Enumetations;
using PianoMelody.Web.Contracts;
using System;
namespace PianoMelody.Web.Models.ViewModels
{
public class GalleryViewModel : IMapFrom<Multimedia>, ILocalizable
{
public int Id { get; set; }
public MultimediaType Type { get; set; }
public DateTime Created { get; set; }
[Localized]
public string Content { get; set; }
public string Url { get; set; }
public string DataSize { get; set; }
}
}<file_sep>/PianoMelody.Models/Product.cs
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace PianoMelody.Models
{
public class Product
{
private ICollection<Multimedia> multimedias;
public Product()
{
this.multimedias = new HashSet<Multimedia>();
}
[Key]
public int Id { get; set; }
public int Position { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal? Price { get; set; }
public decimal? PromoPrice { get; set; }
public bool IsNew { get; set; }
public bool IsSold { get; set; }
public int? ArticleGroupId { get; set; }
public virtual ArticleGroup ArtilceGroup { get; set; }
public int? ManufacturerId { get; set; }
public virtual Manufacturer Manufacturer { get; set; }
public virtual ICollection<Multimedia> Multimedias
{
get
{
return this.multimedias;
}
set
{
this.multimedias = value;
}
}
}
}
<file_sep>/PianoMelody.Web/Models/ViewModels/ManufacturerViewModel.cs
using OrangeJetpack.Localization;
using PianoMelody.Helpers;
using PianoMelody.Models;
using PianoMelody.Web.Contracts;
using System.Collections.Generic;
namespace PianoMelody.Web.Models.ViewModels
{
public class ManufacturerViewModel : IMapFrom<Manufacturer>, ILocalizable
{
public int Id { get; set; }
public int Position { get; set; }
[Localized]
public string Name { get; set; }
public bool AreWeAgent { get; set; }
public string UrlAddress { get; set; }
public Multimedia Multimedia { get; set; }
}
public class ManufacturersWithPager
{
public IEnumerable<ManufacturerViewModel> Manufacturers { get; set; }
public Pager Pager { get; set; }
}
}<file_sep>/PianoMelody.Web/Helpers/JsonHelper.cs
using Newtonsoft.Json;
using System.Collections.Generic;
namespace PianoMelody.Web.Helpers
{
public static class JsonHelper
{
public static string Serialize(string enValue, string ruValue, string bgValue)
{
return JsonConvert.SerializeObject
(
new List<object>
{
new { k = "en", v = enValue },
new { k = "ru", v = ruValue },
new { k = "bg", v = bgValue }
}
);
}
public static List<LocObject> Deserialize(string json)
{
return JsonConvert.DeserializeObject<List<LocObject>>(json);
}
}
public class LocObject
{
public string k { get; set; }
public string v { get; set; }
}
}<file_sep>/PianoMelody.Web/Models/BindingModels/ManufacturerBindingModel.cs
using PianoMelody.I18N;
using System.ComponentModel.DataAnnotations;
using System.Web;
namespace PianoMelody.Web.Models.BindingModels
{
public class ManufacturerBindingModel
{
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
[Display(Name = "_EnName", ResourceType = typeof(Resources))]
public string EnName { get; set; }
[Display(Name = "_RuName", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string RuName { get; set; }
[Display(Name = "_BgName", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string BgName { get; set; }
[Display(Name = "_AreWeAgent", ResourceType = typeof(Resources))]
public bool AreWeAgent { get; set; }
[Display(Name = "_UrlAddress", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string UrlAddress { get; set; }
[Display(Name = "_Photo", ResourceType = typeof(Resources))]
public HttpPostedFileBase Multimedia { get; set; }
public string Url { get; set; }
}
}<file_sep>/PianoMelody.Web/Models/BindingModels/ProductBindingModel.cs
using OrangeJetpack.Localization;
using PianoMelody.I18N;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web;
namespace PianoMelody.Web.Models.BindingModels
{
public class ProductBindingModel : ILocalizable
{
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
[Display(Name = "_EnName", ResourceType = typeof(Resources))]
public string EnName { get; set; }
[Display(Name = "_RuName", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string RuName { get; set; }
[Display(Name = "_BgName", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string BgName { get; set; }
[DataType(DataType.MultilineText)]
[Display(Name = "_EnDescription", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string EnDescription { get; set; }
[DataType(DataType.MultilineText)]
[Display(Name = "_RuDescription", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string RuDescription { get; set; }
[DataType(DataType.MultilineText)]
[Display(Name = "_BgDescription", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string BgDescription { get; set; }
[Display(Name = "_Position", ResourceType = typeof(Resources))]
public int Position { get; set; }
[Display(Name = "Price", ResourceType = typeof(Resources))]
[RegularExpression(@"^\d*(\.|,|(\.\d{1,2})|(,\d{1,2}))?$", ErrorMessage = "Invalid price")]
public decimal? Price { get; set; }
[Display(Name = "_PromoPrice", ResourceType = typeof(Resources))]
[RegularExpression(@"^\d*(\.|,|(\.\d{1,2})|(,\d{1,2}))?$", ErrorMessage = "Invalid price")]
public decimal? PromoPrice { get; set; }
[Display(Name = "_IsNew", ResourceType = typeof(Resources))]
public bool IsNew { get; set; }
[Display(Name = "_IsSold", ResourceType = typeof(Resources))]
public bool IsSold { get; set; }
[Display(Name = "_ArticleGroup", ResourceType = typeof(Resources))]
public int? ArticleGroupId { get; set; }
[Display(Name = "_Manufacturer", ResourceType = typeof(Resources))]
public int? ManufacturerId { get; set; }
[Display(Name = "_Photos", ResourceType = typeof(Resources))]
public ICollection<HttpPostedFileBase> Multimedias { get; set; }
}
}<file_sep>/PianoMelody.Web/Models/ViewModels/ReferenceViewModel.cs
using OrangeJetpack.Localization;
using PianoMelody.Helpers;
using PianoMelody.Models;
using PianoMelody.Web.Contracts;
using System;
using System.Collections.Generic;
namespace PianoMelody.Web.Models.ViewModels
{
public class ReferenceViewModel : IMapFrom<Reference>, ILocalizable
{
public int Id { get; set; }
public int Position { get; set; }
public DateTime Created { get; set; }
[Localized]
public string Title { get; set; }
[Localized]
public string Content { get; set; }
public Multimedia Multimedia { get; set; }
}
public class ReferencesWithPager
{
public IEnumerable<ReferenceViewModel> References { get; set; }
public Pager Pager { get; set; }
}
}<file_sep>/PianoMelody.Web/Models/ViewModels/ChangePasswordViewModel.cs
namespace PianoMelody.Web.Models.ViewModels
{
using System.ComponentModel.DataAnnotations;
using I18N;
public class ChangePasswordViewModel
{
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
[DataType(DataType.Password)]
[Display(Name = "_CurrentPassword", ResourceType = typeof(Resources))]
public string CurrentPassword { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
[StringLength(100, ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrLenghtValidation",
MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "_NewPassword", ResourceType = typeof(Resources))]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "_ConfirmPassword", ResourceType = typeof(Resources))]
[Compare("NewPassword", ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_PasswordValidation")]
public string ConfirmPassword { get; set; }
}
}<file_sep>/PianoMelody.Models/Resources.cs
namespace PianoMelody.Models
{
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class Resources
{
[Key]
[Column(Order = 1)]
public string Name { get; set; }
[Key]
[Column(Order = 2)]
[MaxLength(8)]
public string Culture { get; set; }
public string Value { get; set; }
}
}
<file_sep>/PianoMelody.Compiled/Scripts/Custom/load-gallery.js
initPhotoSwipeFromDOM('.my-gallery');
$('.btn-admin').on('click', 'a', function (e) {
e.stopPropagation();
});<file_sep>/PianoMelody.Web/Models/BindingModels/ResourceBindingModel.cs
namespace PianoMelody.Web.Models.BindingModels
{
using System.ComponentModel.DataAnnotations;
using I18N;
public class ResourcesBindingModel
{
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string Name { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string BgValue { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string EnValue { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_ErrRequired")]
public string RuValue { get; set; }
}
}<file_sep>/PianoMelody.Web/Models/ViewModels/ResourceViewModel.cs
using PianoMelody.Models;
using PianoMelody.Web.Contracts;
namespace PianoMelody.Web.Models.ViewModels
{
public class ResourceViewModel : IMapFrom<Resources>
{
public string Name { get; set; }
}
}<file_sep>/PianoMelody.Web/Controllers/HomeController.cs
namespace PianoMelody.Web.Controllers
{
using System.Configuration;
using System.Linq;
using System.Net;
using System.Text;
using System.Web.Mvc;
using AutoMapper.QueryableExtensions;
using OrangeJetpack.Localization;
using Extensions;
using Helpers;
using I18N;
using Models.BindingModels;
using Models.ViewModels;
using PianoMelody.Models.Enumetations;
using reCAPTCHA.MVC;
public class HomeController : BaseController
{
// GET /Home
[HttpGet]
public ActionResult Index()
{
var homeViewModel = new HomeViewModel();
homeViewModel.Carousel = this.Data.Multimedia.GetAll()
.Where(m => m.Type == MultimediaType.CarouselElement)
.ProjectTo<CarouselViewModel>()
.Localize(this.CurrentCulture, c => c.Content)
.ToArray();
homeViewModel.PromoProducts = this.Data.Products.GetAll()
.Where(p => p.PromoPrice != null)
.OrderBy(p => p.Position)
.Take(3)
.ProjectTo<ProductViewModel>()
.Localize(this.CurrentCulture, p => p.Name, p => p.Description, p => p.ArticleGroupName, p => p.ManufacturerName)
.ToArray();
homeViewModel.LastNews = this.Data.News.GetAll()
.OrderByDescending(n => n.Created)
.Take(3)
.ProjectTo<NewsViewModel>()
.Localize(this.CurrentCulture, n => n.Title, n => n.Content)
.ToArray();
homeViewModel.RandomReferences = this.Data.References.GetAll()
.OrderByDescending(r => r.Created)
.RandomElements(r => r.Multimedia != null, 2)
.ProjectTo<ReferenceViewModel>()
.Localize(this.CurrentCulture, r => r.Title, r => r.Content)
.ToArray();
homeViewModel.Manufacturers = this.Data.Manufacturers.GetAll()
.Where(m => m.AreWeAgent && m.Multimedia != null)
.ProjectTo<ManufacturerViewModel>()
.Localize(this.CurrentCulture, m => m.Name);
return this.View(homeViewModel);
}
// GET /About
[HttpGet]
public ActionResult About()
{
return this.View();
}
// GET /Contact
[HttpGet]
public ActionResult Contact(string about)
{
if (about != null)
{
return this.View(new EmailBindingModel { Message = string.Format("{0} {1} - ", Resources._AskAbout, about) });
}
return this.View();
}
// GET /EditAbout
[HttpGet]
[Authorize(Roles = "Admin")]
public ActionResult Edit(string html, string returnUrl)
{
var htmls = this.Data.Resources.GetAll().Where(r => r.Name == html).ToArray();
var enAbout = htmls.FirstOrDefault(l => l.Culture == "en");
var ruAbout = htmls.FirstOrDefault(l => l.Culture == "ru");
var bgAbout = htmls.FirstOrDefault(l => l.Culture == "bg");
var rbm = new ResourcesBindingModel()
{
Name = html,
EnValue = enAbout.Value,
RuValue = ruAbout.Value,
BgValue = bgAbout.Value
};
return this.View(rbm);
}
// GET /EditAbout
[HttpPost]
[Authorize(Roles = "Admin")]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult Edit(string html, string returnUrl, ResourcesBindingModel rbm)
{
if (!this.ModelState.IsValid)
{
return this.View();
}
var htmls = this.Data.Resources.GetAll().Where(r => r.Name == html).ToArray();
var enAbout = htmls.FirstOrDefault(l => l.Culture == "en");
var ruAbout = htmls.FirstOrDefault(l => l.Culture == "ru");
var bgAbout = htmls.FirstOrDefault(l => l.Culture == "bg");
enAbout.Value = rbm.EnValue;
ruAbout.Value = rbm.RuValue;
bgAbout.Value = rbm.BgValue;
this.Data.SaveChanges();
Resources.Refresh();
return this.Redirect(returnUrl);
}
// GET /SendEmail
[HttpPost]
[ValidateAntiForgeryToken]
[CaptchaValidator]
public ActionResult SendEmail(EmailBindingModel ebm, bool captchaValid)
{
if (!ModelState.IsValid)
{
return this.View("Contact");
}
var emailBody = new StringBuilder();
if (ebm.Name != null)
{
emailBody.AppendFormat("{0}<br />", ebm.Name);
}
emailBody.AppendFormat("{0}<br />", ebm.Email);
if (ebm.Phone != null)
{
emailBody.AppendFormat("{0}<br /><br />", ebm.Phone);
}
emailBody.AppendFormat("{0}<br />", ebm.Message);
var email = new EmailHelper();
email.Name = ebm.Name;
email.Email = ebm.Email;
email.Recipient = ConfigurationManager.AppSettings["recipient"];
email.Subject = Resources._ContactFormSubject;
email.Body = emailBody.ToString();
email.Send();
this.AddNotification(Resources._EmailSentSuccessfully, NotificationType.SUCCESS);
return this.RedirectToAction("Contact");
}
}
}
|
d6138a199946c9b8ee25ac5919badaa7c8058eb8
|
[
"Markdown",
"C#",
"JavaScript",
"Text"
] | 57
|
C#
|
PianoMelody/PianoMelody
|
79d8767ddf88ba4964374a37a9a5ae195d63ba83
|
6feb129fc18b8a82f329e42bbbf74af98e5fb5b9
|
refs/heads/master
|
<repo_name>afosterw/confrigurator<file_sep>/docs/usage.rst
=====
Usage
=====
To use Confrigulator in a project::
import confrigulator
<file_sep>/requirements.txt
dpath==1.4.2
<file_sep>/confrigulator/confrigulator.py
# -*- coding: utf-8 -*-
import logging
import dpath.util
logger = logging.getLogger(__name__)
class KeyNotFoundException(Exception):
pass
class Interpolator(object):
def __init__(self, config):
pass
def interpolate(self, value):
return value
class Layer(object):
def __init__(self, name):
self.name = name
self.dirty = False
self.writable = False
def exists(self, key):
raise Exception('Not implimented')
def get(self, key, default_value=None):
raise Exception('Not implimented')
def set(self, key, value):
raise Exception('Not implimented')
def has_key(self, key):
raise Exception('Not implimented')
def query(self, query_string):
raise Exception('Not implimented')
def write(self):
raise Exception('Not implimented')
def load(self, data):
raise Exception('Not implimented')
class DictLayer(Layer):
def __init__(self, name, data=None):
super(DictLayer, self).__init__(name)
self.data = dict()
if data:
self.load(data)
self.query_engine = DPathQueryEngine()
def exists(self, key):
try:
self.query(key)
except KeyNotFoundException:
return False
except InvalidKeyException:
return False
return True
def get(self, key, default_value=None):
try:
return self.query(key)
except KeyNotFoundException:
return default_value
def set(self, key, value, create=True):
try:
return bool(self.query_engine.set(key, value, self.data, create=create))
except KeyNotFoundException as e:
logger.info(e)
return False
def remove(self, key):
try:
return bool(self.query_engine.remove(key, self.data))
except KeyNotFoundException as e:
logger.info(e)
return False
def has_key(self, key):
return self.exists(key)
def query(self, query_string):
return self.query_engine.query(query_string, self.data)
def write(self):
raise Exception("Not a writable config layer.")
def load(self, data):
self.data = data
class ObjectLayer(Layer):
pass
class YAMLLayer(Layer):
pass
class KeyNotFoundException(Exception):
pass
class InvalidKeyException(Exception):
pass
class DPathQueryEngine:
def __init__(self, delimiter='.'):
self.delimiter = delimiter
def query(self, key, data):
try:
return dpath.util.get(data, key, separator=self.delimiter)
except KeyError as e:
raise KeyNotFoundException(key)
except IndexError as e:
raise InvalidKeyException()
def set(self, key, value, data, create=True):
result = dpath.util.set(data, key, value, separator=self.delimiter)
if result == 0:
if create:
logger.debug('Creating new key {}'.format(key))
dpath.util.new(data, key, value, separator=self.delimiter)
return 1
else:
raise KeyNotFoundException(key)
return result
def remove(self, key, data):
try:
return dpath.util.delete(data, key, separator=self.delimiter)
except dpath.exceptions.PathNotFound as e:
raise(KeyNotFoundException(key))
class ConfigQueryException(Exception):
def __init__(self, message, query):
self.message = message
self.query = query
class LayerQuery(object):
def __init__(self, query, layer):
self.query = query
self.layer = layer
self.success = False
self.result = None
def execute(self):
try:
self.result = self.layer.query(query)
self.success = True
except KeyNotFoundException as e:
self.success = False
self.result = e
return self.success
class ConfigQuery(object):
def __init__(self, config, query_string, cast, return_default, default_value, return_first):
self.config = config
self.query_string = query_string
self.cast = cast
self.return_default = return_default
self.default_value = default_value
self.return_first = return_first
self.executed = False
self.success = False
self.layer_queries = list()
def execute(self, return_first=None):
self.executed = True
if return_first is None:
return_first = self.return_first
for layer in reversed(config.layers):
layer_query = LayerQuery(query, layer)
layer_query.execute()
self.layer_queries.append(layer_query)
if layer_query.success:
self.success = True
if return_first:
return self.success
return self.success
def result(self, cast=None, return_default=None, default_value=None, layer=None):
if self.success:
result = self.layer_queries[-1].result
if cast is not None:
result = cast(result)
return result
elif return_default:
return default_value
else:
raise ConfigQueryException(self.query_string, self)
class Config(object):
def __init__(self, layers=None, retain_queries=False):
self.layers = list()
self.queries = list()
if layers:
for layer in layers:
self.layers.append(layer)
def insert_layer(self, layer, location=None):
if location is None:
location = len(self.layers)
self.layers.insert(location, layer)
def remove_layer(self, location):
self.layers.remove(location)
def index(self):
return [layer.name for layer in self.layers]
def query(self, query_string, cast=None, return_default=False, default_value=None, return_first=False, layer_name=None):
query = Query(
query_string,
cast,
return_default,
default_value
)
<file_sep>/tests/test_confrigulator.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `confrigulator` package."""
import pytest
from click.testing import CliRunner
from confrigulator import confrigulator
from confrigulator import cli
@pytest.fixture
def root_layer_data():
data = {
'root': {
'root_branch_dict': {
'root_branch_list': [1,2,3,4,5],
'root_branch_value': 'original_value'
},
'root_list': [1,2,3,4,5],
'root_value': 'original_value'
}
}
return data
@pytest.fixture
def root_layer_name():
return 'root'
@pytest.fixture
def root_layer(root_layer_name, root_layer_data):
return confrigulator.DictLayer(root_layer_name, data=root_layer_data)
@pytest.fixture
def root_config(root_layer):
return confrigulator.Config(layers=[root_layer])
@pytest.fixture
def dpath_query_engine():
return confrigulator.DPathQueryEngine()
@pytest.fixture
def response():
"""Sample pytest fixture.
See more at: http://doc.pytest.org/en/latest/fixture.html
"""
# import requests
# return requests.get('https://github.com/audreyr/cookiecutter-pypackage')
def test_content(response):
"""Sample pytest test function with the pytest fixture as an argument."""
# from bs4 import BeautifulSoup
# assert 'GitHub' in BeautifulSoup(response.content).title.string
def test_command_line_interface():
"""Test the CLI."""
runner = CliRunner()
result = runner.invoke(cli.main)
assert result.exit_code == 0
assert 'confrigulator.cli.main' in result.output
help_result = runner.invoke(cli.main, ['--help'])
assert help_result.exit_code == 0
assert '--help Show this message and exit.' in help_result.output
def test_config(root_config, root_layer_name):
assert root_config.index() == [root_layer_name]
class TestDPathQueryEngine:
def test_create(self, dpath_query_engine):
assert dpath_query_engine.delimiter == '.'
def test_query(self, dpath_query_engine, root_layer_data):
assert dpath_query_engine.query('root.root_branch_dict.root_branch_value', root_layer_data) == 'original_value'
def test_invalid_key(self, dpath_query_engine, root_layer_data):
with pytest.raises(confrigulator.InvalidKeyException):
dpath_query_engine.query('', root_layer_data)
def test_key_not_found(self, dpath_query_engine, root_layer_data):
with pytest.raises(confrigulator.KeyNotFoundException):
dpath_query_engine.query('root.something', root_layer_data)
def test_set(self, dpath_query_engine, root_layer_data):
with pytest.raises(confrigulator.KeyNotFoundException):
dpath_query_engine.set('root.new_key', 'new_value', root_layer_data, create=False)
assert dpath_query_engine.set('root.new_key', 'new_value', root_layer_data) == 1
assert dpath_query_engine.query('root.new_key', root_layer_data) == 'new_value'
assert dpath_query_engine.set('root.new_key', 'changed_value', root_layer_data, create=False)
assert dpath_query_engine.query('root.new_key', root_layer_data) == 'changed_value'
class TestDictLayer:
def test_create(self, root_layer_data):
layer = confrigulator.DictLayer('dict_layer', data=root_layer_data)
assert layer.data == root_layer_data
assert layer.name == 'dict_layer'
assert layer.dirty == False
assert layer.writable == False
assert isinstance(layer.query_engine, confrigulator.DPathQueryEngine)
def test_exists(self, root_layer):
assert root_layer.exists('root')
assert root_layer.exists('other') == False
assert root_layer.exists('') == False
def test_get(self, root_layer):
assert root_layer.get('root.root_branch_dict.root_branch_value') == 'original_value'
assert root_layer.get('root.no_key', 'not_found') == 'not_found'
def test_set(self, root_layer):
assert root_layer.set('root.new_key', 'new_value', create=False) == False
assert root_layer.set('root.new_key', 'new_value') == True
assert root_layer.get('root.new_key') == 'new_value'
assert root_layer.set('root.new_key', 'changed_value', create=False) == True
assert root_layer.get('root.new_key') == 'changed_value'
def test_delete(self, root_layer):
assert root_layer.set('root.new_key', 'new_value') == 1
assert root_layer.get('root.new_key') == 'new_value'
assert root_layer.remove('root.new_key') == 1
assert root_layer.exists('root.new_key') == False
with pytest.raises(confrigulator.KeyNotFoundException):
root_layer.remove('root.new_key')
|
4adab6518b367335ed0d3dca5c295220a9ea4b34
|
[
"Python",
"Text",
"reStructuredText"
] | 4
|
reStructuredText
|
afosterw/confrigurator
|
56071fea1d97bb478524f4a0df67ad8cda36d283
|
1c876816146f04758f20ca45669c2c147ffadb84
|
refs/heads/master
|
<file_sep>package com.duang.action;
import java.util.List;
import com.duang.model.Class;
import com.duang.model.Exam;
import com.duang.model.Grade;
import com.duang.model.Student;
import com.duang.service.ClassService;
import com.duang.service.ExamService;
import com.duang.service.GradeService;
import com.duang.service.StudentService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class GradeAction extends ActionSupport implements ModelDriven<Grade>{
private Grade grade=new Grade();
List<Grade> list;
List<Exam> examlist;
List<Student> stulist;
public List<Class> getClassList() {
return classList;
}
public void setClassList(List<Class> classList) {
this.classList = classList;
}
List<Class> classList;
public Grade getGrade() {
return grade;
}
public void setGrade(Grade grade) {
this.grade = grade;
}
public List<Grade> getList() {
return list;
}
public void setList(List<Grade> list) {
this.list = list;
}
public List<Exam> getExamlist() {
return examlist;
}
public void setExamlist(List<Exam> examlist) {
this.examlist = examlist;
}
public List<Student> getStulist() {
return stulist;
}
public void setStulist(List<Student> stulist) {
this.stulist = stulist;
}
/**
* 获取全部
*
*/
public String getAllGrade(){
GradeService service=new GradeService();
list=service.getAllGrade();
return SUCCESS;
}
public String getAllGradeOrderByExamId(){
GradeService service=new GradeService();
list=service.getAllOrderByExamId();
return SUCCESS;
}
public String preModifyGrade(){
GradeService service=new GradeService();
int id=grade.getId();
grade =service.getById(id);
return SUCCESS;
}
public String getAllGradeOrderByStuId(){
GradeService service=new GradeService();
list=service.getAllOrderByStuId();
return SUCCESS;
}
/**
* 预添加
*
*/
public String preAddGrade(){
ExamService examService=new ExamService();
StudentService studentService=new StudentService();
//ClassService classService=new ClassService();
this.examlist=examService.getAllExam();
this.stulist=studentService.getAllStudent();
//this.classList=classService.getAllClass();
return SUCCESS;
}
/**
* 添加
*
*/
public String addGrade(){
GradeService gradeService=new GradeService();
gradeService.addGrade(grade);
return this.getAllGrade();
}
/**
* 修改
* @param student
* @return
*/
public String modifyGrade(){
GradeService service=new GradeService();
service.modifyGrade(grade);
return this.getAllGrade();
}
/**
* 删除
* @return
*/
public String delGrade(){
GradeService service=new GradeService();
service.delGrade(grade.getId());
return this.getAllGrade();
}
/**
* 查看详细信息
* @return
*/
public String getGradeInfoById(){
GradeService service=new GradeService();
grade=service.getById(grade.getId());
return SUCCESS;
}
@Override
public Grade getModel() {
// TODO Auto-generated method stub
return this.grade;
}
}
<file_sep>package com.duang.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.duang.model.Exam;
import com.duang.util.HibernateSessionFactory;
public class ExamDao {
/**
* 得到所有
* @return
*/
public List<Exam> getAllExam(){
String hql="from Exam";//from后面接的是类名,而不是数据库中的table名
Session session=HibernateSessionFactory.getSession();
Transaction tran=session.beginTransaction();
Query query=session.createQuery(hql);
List<Exam> list=query.list();
tran.commit();
session.close();
for(Exam exam:list){
System.out.println(exam.getId()+"\t"+exam.getName()+"\t");
}
return list;
}
/**
* 添加
* @param student
*/
public void addExam(Exam exam){
Session session=HibernateSessionFactory.getSession();
Transaction tran=session.beginTransaction();
session.save(exam);
tran.commit();
session.close();
}
/**
* 通过ID查询
* @param id
* @return
*/
public Exam getById(int id){
Session session=HibernateSessionFactory.getSession();
Transaction tran=session.beginTransaction();
Exam exam=(Exam) session.get(Exam.class, id);
tran.commit();
session.close();
System.out.println(exam.getId());
System.out.println(exam.getName());
return exam;
}
/**
* 通过ID修改
* @param student
*/
public void modifyExam(Exam exam){
Session session=HibernateSessionFactory.getSession();
Transaction tran=session.beginTransaction();
System.out.println(exam.getId());
session.update(exam);
tran.commit();
session.close();
}
/**
* 通过ID删除
* @param id
*/
public void delExam(int id){
Session session=HibernateSessionFactory.getSession();
Transaction tran=session.beginTransaction();
session.delete(new Exam(id));
tran.commit();
session.close();
}
}
<file_sep>package com.duang.action;
import java.util.List;
import com.duang.model.User;
import com.duang.service.UserService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class UserAction extends ActionSupport implements ModelDriven<User> {
List<User> list;
private User user=new User();
public List<User> getList() {
return list;
}
public void setList(List<User> list) {
this.list = list;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
/**
* 获取全部用户
* @return
*/
public String getAllUser(){
UserService service=new UserService();
list=service.getAllUser();
return "success";
}
/**
* 添加
* @author <NAME>
*
*/
public String addUser(){
UserService userService=new UserService();
userService.addStudent(user);
return this.getAllUser();
}
/**
* 删除用户
* @return
*/
public String delUser(){
UserService service=new UserService();
service.delUser(user.getId());
return this.getAllUser();
}
/**
* 预修改用户
* @return
*/
public String preModifyUser(){
UserService service=new UserService();
user=service.getByID(user.getId());
return SUCCESS;
}
/**
* 修改用户
* @return
*/
public String modifyUser(){
UserService service=new UserService();
service.modiftStudent(user);
return this.getAllUser();
}
public String userLogin(){
UserService userService = new UserService();
List<User> list=userService.login(user.getName(), user.getPwd());
if(list !=null){
return "success";
}
else
{
return "input";
}
}
/*
public String register(){
return "regsuccess";
}*/
@Override
public User getModel() {
// TODO Auto-generated method stub
return this.user;
}
}
<file_sep>package com.duang.model;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/**
* Exam entity. @author MyEclipse Persistence Tools
*/
public class Exam implements java.io.Serializable {
// Fields
private Integer id;
private String name;
private Date begintime;
private Date endtime;
private String place;
private Set grades = new HashSet(0);
// Constructors
/** default constructor */
public Exam() {
}
public Exam(int id) {
this.id=id;
}
public Exam(String name, Date begintime, Date endtime, String place) {
this.name = name;
this.begintime = begintime;
this.endtime = endtime;
this.place = place;
this.grades = grades;
}
/** full constructor */
public Exam(String name, Date begintime, Date endtime, String place,
Set grades) {
this.name = name;
this.begintime = begintime;
this.endtime = endtime;
this.place = place;
this.grades = grades;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Date getBegintime() {
return this.begintime;
}
public void setBegintime(Date begintime) {
this.begintime = begintime;
}
public Date getEndtime() {
return this.endtime;
}
public void setEndtime(Date endtime) {
this.endtime = endtime;
}
public String getPlace() {
return this.place;
}
public void setPlace(String place) {
this.place = place;
}
public Set getGrades() {
return this.grades;
}
public void setGrades(Set grades) {
this.grades = grades;
}
}<file_sep>package com.duang.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.duang.model.Student;
import com.duang.util.HibernateSessionFactory;
public class StudentDao {
/**
* 得到所有学生信息
* @return
*/
public List<Student> getAllStudent(){
String hql="from Student";//from后面接的是类名,而不是数据库中的table名
Session session=HibernateSessionFactory.getSession();
Transaction tran=session.beginTransaction();
Query query=session.createQuery(hql);
List<Student> list=query.list();
tran.commit();
session.close();
for(Student student:list){
System.out.println(student.getId()+"\t"+student.getName()+"\t");
}
return list;
}
/**
* 添加一个学生
* @param student
*/
public void addStudent(Student student){
Session session=HibernateSessionFactory.getSession();
Transaction tran=session.beginTransaction();
session.save(student);
tran.commit();
session.close();
}
/**
* 通过ID查询学生信息
* @param id
* @return
*/
public Student getById(int id){
Session session=HibernateSessionFactory.getSession();
Transaction tran=session.beginTransaction();
Student stu=(Student) session.get(Student.class, id);
tran.commit();
session.close();
System.out.println(stu.getId());
System.out.println(stu.getName());
// ? System.out.println(stu.getBanji().getCode());通过lazy=“false”来解决
return stu;
}
/**
* 通过ID修改学生信息
* @param student
*/
public void modifyStudent(Student student){
Session session=HibernateSessionFactory.getSession();
Transaction tran=session.beginTransaction();
System.out.println(student.getId());
session.update(student);
tran.commit();
session.close();
}
/**
* 通过ID删除学生信息
* @param id
*/
public void delStudent(int id){
Session session=HibernateSessionFactory.getSession();
Transaction tran=session.beginTransaction();
session.delete(new Student(id));
tran.commit();
session.close();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new StudentDao().getById(2);;
}
}
<file_sep>package com.duang.action;
import java.util.List;
import com.duang.model.Student;
import com.duang.model.Class;
import com.duang.service.ClassService;
import com.duang.service.StudentService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
/**
* action的作用是 控制器
* 控制器的作用:接收数据,整理数据,封装数据,跳转到页面
* @author <NAME>
*
*/
public class StudentAction extends ActionSupport implements ModelDriven<Student>{
List<Student> list;
List<Class> classList;
private Student student=new Student();
public List<Class> getClassList() {
return classList;
}
public void setClassList(List<Class> classList) {
this.classList = classList;
}
public List<Student> getList() {
return list;
}
public void setList(List<Student> list) {
this.list = list;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
/**
* 获取全部学生
* @author <NAME>
*
*/
public String getAllStudent(){
StudentService service=new StudentService();
list=service.getAllStudent();
return SUCCESS;
}
/**
* 预添加学生
* @author <NAME>
*
*/
public String preAddStudent(){
ClassService classService=new ClassService();
this.classList=classService.getAllClass();
return SUCCESS;
}
/**
* 添加学生
* @author <NAME>
*
*/
public String addStudent(){
StudentService studentService=new StudentService();
studentService.addStudent(student);
return this.getAllStudent();//返回getAllStudent是防止返回后列表中没有学生信息了
}
/**
* 准备修改学生信息,跳转到修改学生信息页面
* @return
*/
public String preModifyStudent(){
StudentService service=new StudentService();
int id=student.getId();
student =service.getByID(id);
ClassService classService=new ClassService();
this.classList=classService.getAllClass();
return SUCCESS;
}
/**
* 修改学生信息
* @param student
* @return
*/
public String modifyStudent(){
StudentService service=new StudentService();
//System.out.println(student.getId());
service.modiftStudent(student);
return this.getAllStudent();
}
/**
* 删除学生信息
* @return
*/
public String delStudent(){
StudentService service=new StudentService();
service.delStudent(student.getId());
return this.getAllStudent();
}
/**
* 查看学生详细信息
* @return
*/
public String getStudentInfoById(){
StudentService service=new StudentService();
student=service.getByID(student.getId());
return SUCCESS;
}
@Override
public Student getModel() {
// TODO Auto-generated method stub
return this.student;
}
}
|
af887900a6884100c5e6a80cf23c0213f04cd60b
|
[
"Java"
] | 6
|
Java
|
AomanHao/StudentSYS
|
a4cf0709865d67efc808aeb00229112b833c9eff
|
51e4485de370912d43cb8a80b175e3bd8ba779c6
|
refs/heads/master
|
<repo_name>Parthjuneja24/Data-Structures-and-Algorithms-master<file_sep>/Stack/LongestValidParanthesis.java
package Stack;
import java.util.Stack;
public class LongestValidParanthesis {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "())(())))(()))()(()()())";
func(str);
}
public static void func(String str) {
int countermax = 0;
Stack<Integer> stack = new Stack<Integer>();
// we push -1 so that if the stack comes to the end, we can measure
// the distance from -1
stack.push(-1);
for (int i = 0; i < str.length(); i++) {
// if the char at the index is ) , we pop and measure the distance of
// current index from stack top, which gives us previous element before (
if ((str.charAt(i) == ')') && (!stack.isEmpty())) {
stack.pop();
if ((!stack.isEmpty()) && (i - stack.peek()) > countermax) {
// we update the max counter
countermax = i - stack.peek();
}
} else {
stack.push(i);
}
}
System.out.println(countermax);
}
}
<file_sep>/Recursion/NextGreater.java
package Recursion;
public class NextGreater {
public static void main(String[] args) {
int arr[] = { -4, 5, 25, 13, 6, 12 };
func(arr);
}
private static void func(int[] arr) {
int ans[] = new int[arr.length];
ans[arr.length - 1] = -1;
int max = arr[arr.length - 1];
for (int i = arr.length - 2; i >= 0; i--) {
if (max > arr[i]) {
ans[i] = max;
} else {
ans[i] = -1;
max = arr[i];
}
}
for (int val : ans) {
System.out.print(val + " ");
}
}
}
<file_sep>/Recursion/Candy_Distribution.java
package Recursion;
import java.util.*;
public class Candy_Distribution {
public static int code(ArrayList<Integer> ratings) {
if (ratings == null || ratings.size() == 0)
return 0;
int[] candies = new int[ratings.size()];
candies[0] = 1;
for (int i = 1; i < ratings.size(); i++) {
if (ratings.get(i) > ratings.get(i - 1))
candies[i] = candies[i - 1] + 1;
else {
candies[i] = 1;
}
}
int result = candies[ratings.size() - 1];
for (int i = ratings.size() - 2; i >= 0; i--) {
int cur = 1;
if (ratings.get(i) > ratings.get(i + 1))
cur = candies[i + 1] + 1;
result += Math.max(cur, candies[i]);
candies[i] = cur;
}
return result;
}
public static void main(String[] args) {
ArrayList<Integer> ratings = new ArrayList<Integer>();
ratings.add(1);
ratings.add(2);
ratings.add(2);
System.out.println(code(ratings));
}
}
|
f01cd1d975c121958bcc3cdcd79cd6aeaa5bd828
|
[
"Java"
] | 3
|
Java
|
Parthjuneja24/Data-Structures-and-Algorithms-master
|
13e09f1bb0d7ac1cc61bbbd95d658d73162d715f
|
443fba8c1d059b92143376db68d76e8433eaa46c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.