language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
|---|---|---|---|---|---|---|---|
C
|
UTF-8
| 1,867
| 2.546875
| 3
|
[] |
no_license
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* manage_tilde.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gjensen <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/04/25 17:17:51 by gjensen #+# #+# */
/* Updated: 2016/05/08 20:50:18 by bciss ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_sh.h"
#include <pwd.h>
#include <sys/types.h>
char *ft_check_tild(char **str)
{
char *val;
if (ft_strlen(*str) == 1)
{
val = sh_get_env_var("HOME");
ft_strdel(str);
if (val)
return (ft_strdup(val));
else
return (ft_strdup(""));
}
return (NULL);
}
char *ft_found_or_not(char **str, char *tmp, int i)
{
struct passwd *usp;
char user[0xFFF];
char ret[0xFFF];
ft_bzero(user, 0xFFF);
tmp = *str + 1;
while (tmp[++i])
user[i] = tmp[i];
tmp[i] = 0;
if ((usp = getpwnam(user)) != NULL)
{
ft_strcpy(ret, usp->pw_dir);
ft_strcat(ret, *str + i + 1);
ft_strdel(str);
*str = ft_strdup(ret);
}
else
{
ft_putstr_fd("42sh"": no such user or named directory: ", 2);
ft_putendl_fd(user, 2);
ft_strdel(str);
return (NULL);
}
return (*str);
}
char *manage_tilde(char *str)
{
char *tmp;
int i;
tmp = ft_check_tild(&str);
if (tmp != NULL)
return (tmp);
i = -1;
tmp = ft_found_or_not(&str, tmp, i);
return (tmp);
}
|
Markdown
|
UTF-8
| 1,589
| 2.96875
| 3
|
[
"MIT"
] |
permissive
|
# Containerizing an Express server.
This repository is a step by step guide for setting up and containerizing an express server. This repository also serves as a complementary guide for this [article](https://pogsdotnet.blogspot.com/2018/08/10-steps-to-setup-and-containerize.html).
# Environment Setup
- NodeJS Installed ([Download Here](https://nodejs.org/en/download/))
- Express Generator ([Installation Guide Here](https://expressjs.com/en/starter/generator.html))
- Docker ([Download Here](https://www.docker.com/get-started))
# Steps
1. Create a folder
2. Open a terminal and initial NPM on the folder.
```sh
npm init -y
```
3. Install express-generator
```sh
npm install express-generator -g
```
4. Bootstrap application skeleton
```sh
express --view=pug
```
5. Install express server dependencies
```sh
npm install
```
6. Add a docker file from iron/node
```dockerfile
FROM iron/node
WORKDIR /app
# Copy package.json + package-lock.json files
COPY package*.json ./
# Installing dependencies
RUN npm install
# Bundle app source
COPY . .
EXPOSE 3000
ENTRYPOINT [ "npm", "start" ]
```
7. Add the .dockerignore file below
```.dockerignore
node_modules
npm-debug.log
```
8. Create a docker image by executing the command below on your app folder.
```sh
docker build --tag express/iron-api .
```
9. Verify that your docker image was built.
```sh
docker images --all
```
10. Instantiate a container out of the image you created.
```sh
docker run -p 3000:3000 --name iron-api express/iron-api
```
11. Open the following link on a browser. http://localhost:3000/
|
Swift
|
UTF-8
| 2,172
| 2.78125
| 3
|
[] |
no_license
|
//
// Heartbeat.swift
// WuXiaGPS
//
// Created by asdasd on 2017/5/17.
// Copyright © 2017年 WuXia. All rights reserved.
//
import UIKit
class Heartbeat: NSObject {
/// 心跳终止点,超过这个数值就说明心跳停止
let beatEndNum = 3
// static let share = Heartbeat()
private weak var timer:Timer?
let timerQueue = DispatchQueue.global()
/// 是否活着
var isLive:Bool{
get{
return beat < beatEndNum
}
}
/// 用来循环的方法
var block:(() -> ())?
/// 当到达临界点时,执行的方法
var beatEnd:(() -> ())?
private var beat = 999
/// 开始时间
///
/// - Parameter block: 发送心跳
func startTimer(block:@escaping ()->(),beatEnd:(() -> ())?){
guard timer == nil else {
return
}
objc_sync_enter(self)
if timer == nil{
self.block = block
self.beatEnd = beatEnd
self.beat = 0
timerQueue.async {[weak self] in
guard let s = self else{
return
}
s.timer = Timer.scheduledTimer(timeInterval: 30, target: s, selector: #selector(Heartbeat.sendHeartBeat(timer:)), userInfo: nil, repeats: true)
RunLoop.current.add(s.timer!, forMode: RunLoopMode.commonModes)
RunLoop.current.run()
s.timer?.fire()
}
}
objc_sync_exit(self)
}
/// 停止时间
func stopTimer(){
setBeat(num: 999)
guard let timer = timer,timer.isValid else{
return
}
timer.invalidate()
}
func sendHeartBeat(timer:Timer){
setBeat(num: beat + 1)
if isLive {
block?()
}else{
stopTimer()
beatEnd?()
}
}
/// 设置心跳
///
/// - Parameter num: 数量
func setBeat(num:Int){
objc_sync_enter(self)
beat = num
objc_sync_exit(self)
}
func restoreBeat(){
setBeat(num: 0)
}
}
|
Java
|
UTF-8
| 552
| 2.296875
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ultima;
/**
*
* @author aline, hugo, izadora, betania e larissa
* @since 24/11/2017
*/
/**Resultado da seleção de personagem*/
public class teste {
public static void main(String[] args) {
Supernatural spn = new Supernatural();
spn.nome1();
spn.nome2();
spn.nome3();
}
}
|
JavaScript
|
UTF-8
| 4,806
| 2.5625
| 3
|
[] |
no_license
|
// Logic for the runner, animations and key/events actions
var RunnerLayer = cc.Layer.extend({
_runnerSprite: null,
_runnerSpriteAnimation:null,
_runnerSpriteAnimationJump:null,
_runnerGameOverSprite:null,
_dirtyGameOver: true,
_jumpAction:null,
_runAction:null,
_runnerSpriteFiles:
["../res/runner/rastaIdle.png",
"../res/runner/rastaRun1.png",
"../res/runner/rastaRun2.png",
"../res/runner/rastaRun3.png",
"../res/runner/rastaJump.png"],
_gameState: null,
_currentRotation:0,
_currentPosition: null,
_runnerHeight:0,
_runnerScale:0.3,
_resetAnim: true,
_runVel: 1.0,
_updateT: 0,
_stressX: 50,
update: function(dt){
if(this._gameState)
{
if(!this._gameState.gameOver)
{
var size = cc.Director.getInstance().getWinSize();
var maxSizeX = size.width - this._stressX;
this._currentPosition.x= maxSizeX - 50.0*this._gameState.playbackRate;
if(this._currentPosition.x > maxSizeX)
this._currentPosition.x = maxSizeX;
this.setPosition(this._currentPosition);
this._gameState.runnerPositionX = this._currentPosition.x;
if(this._gameState.jumping)
{
this.jump();
this._resetAnim = true;
}
else
{
this.run();
}
if(this._gameState.time - this._updateT > 1.0)
{
this._updateT = this._gameState.time;
this._runVel = 0.1*(1.0/this._gameState.playbackRate);
//console.log("dt:"+this._gameState.time+" runVel:" + this._runVel);
this._resetAnim = true;
}
}
if(this._gameState.gameOver)
{
this.gameOver();
}
}
},
init:function (gameState) {
//////////////////////////////
// 1. super init first
this._super();
this._gameState = gameState;
var size = cc.Director.getInstance().getWinSize();
// idle frame sprite with
this._runnerSprite = cc.Sprite.create(this._runnerSpriteFiles[0]);
this._runnerSprite.setAnchorPoint(cc.p(0.5,0));
this._currentPosition = cc.p(size.width - this._stressX,
this._runnerHeight);
this.setPosition(this._currentPosition);
//this._runnerSprite.setScale(-this._runnerScale,this._runnerScale);
//
// RUN!!!!
this.run();
this.schedule(this.update);
return true;
},
jump: function () {
this.removeChild(this._runnerSprite);
this._runnerSprite = cc.Sprite.create(this._runnerSpriteFiles[4]);
this._runnerSprite.setAnchorPoint(cc.p(0.5,0));
//cc.AnimationManager.getInstance()
//this._runnerSprite.runAction(this._jumpAction);
this.addChild(this._runnerSprite);
},
run: function() {
if(this._resetAnim)
{
this.removeChild(this._runnerSprite,false);
this._runnerSprite = cc.Sprite.create(this._runnerSpriteFiles[1]);
this._runnerSprite.setAnchorPoint(cc.p(0.5,0));
this._runnerSpriteAnimation = cc.Animation.create();
for (i = 1; i < 3; i++) {
this._runnerSpriteAnimation.addSpriteFrameWithFile(
this._runnerSpriteFiles[i]);
}
// Todo: use playbackRate...
this._runnerSpriteAnimation.setDelayPerUnit(this._runVel);
this._runnerSpriteAnimation.setRestoreOriginalFrame(false);
var runAction = cc.RepeatForever.create(
cc.Animate.create(this._runnerSpriteAnimation));
this._runnerSprite.runAction(runAction);
this.addChild(this._runnerSprite);
this._resetAnim = false;
}
},
gameOver: function()
{
if(this._dirtyGameOver)
{
this.removeAllChildren(true);
this._runnerGameOverSprite = resources.bg.gameover.create(this._gameState,0.2);
this._runnerGameOverSprite.setRunOnce(true);
//this._runnerGameOverSprite.setAnchorPoint(cc.p(0.5,0));
var size = cc.Director.getInstance().getWinSize();
this.addChild(this._runnerGameOverSprite);
var h = this._runnerGameOverSprite.getContentSize().height;
this._currentPosition.y = h/2-60;
this.setPosition(this._currentPosition);
this._dirtyGameOver = false;
}
}
});
|
Swift
|
UTF-8
| 896
| 2.703125
| 3
|
[] |
no_license
|
//
// CardCell.swift
// SGMobileNetworkUsage
//
// Created by Rajkumar Murugesan on 17/8/20.
// Copyright © 2020 Rajkumar M. All rights reserved.
//
import UIKit
class CardCell: UITableViewCell {
@IBOutlet weak var cardView: UIView!
@IBOutlet weak var pictureView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
// Set up the cell
func configure(picture: UIImage, title: String,
description: String)
{
pictureView.image = picture
titleLabel.text = title
descriptionLabel.text = description
cardView.layer.shadowColor = UIColor.gray.cgColor
cardView.layer.shadowOffset = CGSize(width:1.0, height:1.0)
cardView.layer.shadowOpacity = 1.0
cardView.layer.masksToBounds = false
cardView.layer.cornerRadius = 2.0
}
}
|
Java
|
UTF-8
| 568
| 3.328125
| 3
|
[] |
no_license
|
public class solution {
public static int binarySearchHelper(int input[], int start, int end, int element) {
if (start > end) {
return -1;
}
int mid = (start + end) / 2;
if (input[mid] == element) {
return mid;
} else if (input[mid] > element) {
return binarySearchHelper(input, start, mid - 1, element);
} else {
return binarySearchHelper(input, mid + 1, end, element);
}
}
public static int binarySearch(int input[], int element) {
return binarySearchHelper(input, 0, input.length - 1, element);
}
}
|
Markdown
|
UTF-8
| 292
| 2.5625
| 3
|
[] |
no_license
|
## 题名:[移除元素](https://leetcode-cn.com/problems/remove-element/)
这里采用双指针的方法
循环 `nums` 为快指针
`m` 为慢指针记录新的数组长度
当 `n` 不等于给定值时我们就复制 `n` 到 `nums[m]` 并递增 `m` 直到 `nums` 循环到尾部结束
|
Python
|
UTF-8
| 9,826
| 3.03125
| 3
|
[] |
no_license
|
import numpy as np
from typing import List
from hw1_knn import KNN
# TODO: Information Gain function
def Information_Gain(S, branches):
# S: float
# branches: List[List[int]] num_branches * num_cls
# return: float
raise NotImplementedError
# TODO: implement reduced error prunning function, pruning your tree on this function
def reduced_error_prunning(decisionTree, X_test, y_test):
# decisionTree
# X_test: List[List[any]]
# y_test: List
raise NotImplementedError
# print current tree
def print_tree(decisionTree, node=None, name='branch 0', indent='', deep=0):
if node is None:
node = decisionTree.root_node
print(name + '{')
print(indent + '\tdeep: ' + str(deep))
string = ''
label_uniq = np.unique(node.labels).tolist()
for label in label_uniq:
string += str(node.labels.count(label)) + ' : '
print(indent + '\tnum of samples for each class: ' + string[:-2])
if node.splittable:
print(indent + '\tsplit by dim {:d}'.format(node.dim_split))
for idx_child, child in enumerate(node.children):
print_tree(decisionTree, node=child, name='\t' + name + '->' + str(idx_child), indent=indent + '\t', deep=deep+1)
else:
print(indent + '\tclass:', node.cls_max)
print(indent + '}')
def f1_score(real_labels: List[int], predicted_labels: List[int]) -> float:
# assert len(real_labels) == len(predicted_labels)
# tp,fp,tn,fn = 0,0,0,0
# print('inside f1')
# for i in range(len(real_labels)):
# if predicted_labels[i] == 1 and real_labels[i] == 1:
# tp += 1
# elif predicted_labels[i] == 1 and real_labels[i] == 0:
# fp += 1
# elif predicted_labels[i] == 0 and real_labels[i] == 0:
# tn += 1
# elif predicted_labels[i] == 0 and real_labels[i] == 1:
# fn += 1
# print('tp', tp,fp,fn)
# if tp == fp == fn == 0:
# return 0
# precision = tp/(tp + fp)
# recall = tp/(tp + fn)
# f1 = (2 * precision * recall)/(precision+recall)
# print('precision,recal', precision, recall)
# return f1
# print('inside f1')
assert len(real_labels) == len(predicted_labels)
tp = sum([x == 1 and y == 1 for x, y in zip(real_labels, predicted_labels)])
fp = sum([x == 0 and y == 1 for x, y in zip(real_labels, predicted_labels)])
fn = sum([x == 1 and y == 0 for x, y in zip(real_labels, predicted_labels)])
if 2 * tp + fp + fn == 0:
return 0
f1 = 2 * tp / float(2 * tp + fp + fn)
return f1
def euclidean_distance(point1: List[float], point2: List[float]) -> float:
dist = [(p - q) ** 2 for p, q in zip(point1, point2)]
dist = np.sqrt(sum(dist))
return dist
def inner_product_distance(point1: List[float], point2: List[float]) -> float:
# dist = [(p - q) ** 2 for p, q in zip(point1, point2)]
# return sum(dist)
sum = 0
for i in range(len(point1)):
sum += point1[i] * point2[i]
return sum
def gaussian_kernel_distance(point1: List[float], point2: List[float]) -> float:
dist = [(p - q) ** 2 for p, q in zip(point1, point2)]
dist = -0.5* sum(dist)
return -np.exp(dist)
def cosine_sim_distance(point1: List[float], point2: List[float]) -> float:
num = sum(p*q for p,q in zip(point1, point2))
den1 = np.sqrt(sum([p*p for p in point1]))
den2 = np.sqrt(sum([q*q for q in point2]))
return 1-(num/(den1*den2))
# TODO: select an instance of KNN with the best f1 score on validation dataset
def model_selection_without_normalization(distance_funcs, Xtrain, ytrain, Xval, yval):
# distance_funcs: dictionary of distance funtion
# Xtrain: List[List[int]] train set
# ytrain: List[int] train labels
# Xval: List[List[int]] validation set
# yval: List[int] validation labels
# return best_model: an instance of KNN
# return best_k: best k choosed for best_model
# return best_func: best function choosed for best_model
print('inside model_selection')
best_k, best_func, best_f1_score = 0, "", -1
for name, func in distance_funcs.items():
# print(name, distance_funcs[name], func)
# best_f1_score, k_val = -1, 0
for k in range(1,30,2):
model = KNN(k=k, distance_function=func)
model.train(Xtrain, ytrain)
val_f1 = f1_score(yval, model.predict(Xval))
if val_f1 > best_f1_score:
best_f1_score, best_k = val_f1, k
best_func = name
print('best_func, best_k, best f1, val', name, best_k, k, best_f1_score, val_f1)
print('**best_func, best_k', best_func, best_k)
print('****best_func, best_k', best_func, best_k)
return KNN(best_k, distance_funcs[best_func]), best_k, best_func
# TODO: select an instance of KNN with the best f1 score on validation dataset, with normalized data
def model_selection_with_transformation(distance_funcs, scaling_classes, Xtrain, ytrain, Xval, yval):
# distance_funcs: dictionary of distance funtion
# scaling_classes: diction of scalers
# Xtrain: List[List[int]] train set
# ytrain: List[int] train labels
# Xval: List[List[int]] validation set
# yval: List[int] validation labels
# return best_model: an instance of KNN
# return best_k: best k choosed for best_model
# return best_func: best function choosed for best_model
# return best_scaler: best function choosed for best_model
best_k, best_func, best_scaler, best_f1_score = 0, "", "", -1
for scaler_name, scaler in scaling_classes.items():
for name, func in distance_funcs.items():
print(scaler_name, name, distance_funcs[name], func)
# best_f1_score, k_val = -1, 0
scale_class = scaler()
scale_train = scale_class(Xtrain)
scale_val = scale_class(Xval)
for k in range(1, 32, 2):
model = KNN(k=k, distance_function=func)
model.train(scale_train, ytrain)
val_f1 = f1_score(yval, model.predict(scale_val))
if val_f1 > best_f1_score:
best_f1_score, best_k = val_f1, k
best_func = name
best_scaler = scaler_name
print('best_func, best_k, best f1, val', name, best_k, k,
best_f1_score, val_f1)
print('**best_func, best_k, best_scale', best_func, best_k, best_scaler)
print('****best_func, best_k, best_scale', best_func, best_k, best_scaler)
return KNN(best_k, distance_funcs[best_func]), best_k, best_func, best_scaler
class NormalizationScaler:
def __init__(self):
pass
#TODO: normalize data
def __call__(self, features: List[List[float]]) -> List[List[float]]:
"""
normalize the feature vector for each sample . For example,
if the input features = [[3, 4], [1, -1], [0, 0]],
the output should be [[0.6, 0.8], [0.707107, -0.707107], [0, 0]]
"""
normalized_vector = []
for feature in features:
if all(item == 0 for item in feature):
normalized_vector.append(feature)
else:
den = [x*x for x in feature]
den = np.sqrt(den)
vector = [val / den for val in feature]
normalized_vector.append(vector)
return normalized_vector
# norm_features = []
# for x in features:
# sum = 0
# norm_feature_vec = []
# # if all the features in x are 0, then all_zeroes variable would store True else False
# all_zeroes = all(ft == 0 for ft in x)
# # below if condition avoids feature vector with zeroes from being normalized
# if (not all_zeroes):
# for i in range(len(x)):
# sum += x[i] * x[i]
# for i in range(len(x)):
# norm_feature_vec.append(x[i] / sum)
# norm_features.append(norm_feature_vec)
# return norm_features
class MinMaxScaler:
"""
You should keep some states inside the object.
You can assume that the parameter of the first __call__
must be the training set.
Hints:
1. Use a variable to check for first __call__ and only compute
and store min/max in that case.
Note:
1. You may assume the parameters are valid when __call__
is being called the first time (you can find min and max).
Example:
train_features = [[0, 10], [2, 0]]
test_features = [[20, 1]]
scaler = MinMaxScale()
train_features_scaled = scaler(train_features)
# now train_features_scaled should be [[0, 1], [1, 0]]
test_features_sacled = scaler(test_features)
# now test_features_scaled should be [[10, 0.1]]
new_scaler = MinMaxScale() # creating a new scaler
_ = new_scaler([[1, 1], [0, 0]]) # new trainfeatures
test_features_scaled = new_scaler(test_features)
# now test_features_scaled should be [[20, 1]]
"""
def __init__(self):
self.count = 0
self.min_max_values = []
self.min, self.max = None, None
def __call__(self, features: List[List[float]]) -> List[List[float]]:
"""
normalize the feature vector for each sample . For example,
if the input features = [[2, -1], [-1, 5], [0, 0]],
the output should be [[1, 0], [0, 1], [0.333333, 0.16667]]
"""
feat_array = np.array(features)
if self.min is None or self.max is None:
self.min = np.amin(feat_array, axis=0)
self.max = np.amax(feat_array, axis=0)
normalized = (feat_array - self.min) / (self.max - self.min)
return normalized.tolist()
|
Python
|
UTF-8
| 285
| 4.1875
| 4
|
[] |
no_license
|
first_name = str(input("Enter your First Name : "))
last_name = str(input("Enter your Last Name: "))
height = float(input("Enter your height: "))
age = int(input("Enter your age : "))
print(f"Ім'я: {first_name} \nПрізвище: {last_name} \nРіст: {height} \nВік: {age}")
|
Python
|
UTF-8
| 4,606
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
import csv
import json
import os
import re
import yaml
class Config:
def __init__(self, configfile:str, configformat:str, logger) -> None:
self.logger = logger
self.configfile = configfile
self.configformat = configformat
self._check_configfile()
self._parse_config()
self._check_config()
def get_config(self) -> dict:
return self.config
def _get_function_dict(self) -> dict:
return {"csv":self._parse_csv, "tsv":self._parse_tsv, "json":self._parse_json,
"yml":self._parse_yaml, "yaml":self._parse_yaml}
def _parse_params_from_command(self) -> None:
self.config["params"] = tuple(dict.fromkeys(re.findall("\{(.*?)\}", self.config["command"])))
def _check_configfile(self) -> None:
self._check_path_exist()
self._check_file_exist()
self._check_format()
def _check_path_exist(self) -> None:
if not os.path.exists(self.configfile):
self.logger.log_error("Invalid path to configfile.")
raise FileNotFoundError("Invalid path to configfile.")
def _check_file_exist(self) -> None:
if not os.path.isfile(self.configfile):
self.logger.log_error("Configfile does not exist.")
raise FileNotFoundError("Configfile does not exist.")
def _check_format(self) -> None:
if self.configformat == "":
self.configformat = os.path.splitext(self.configfile)[1][1:] # Use [1:] to get everything but the first character '.' so .csv becomes csv
if self.configformat not in self._get_function_dict().keys():
self.logger.log_error(f"The file format {self.configformat} is not supported.")
raise ValueError(f"The file format {self.configformat} is not supported.")
def _parse_config(self) -> None:
self.logger.log_message(f"File {self.configfile} can be opened")
self.config = self._get_function_dict().get(self.configformat)() # Equivalent to 'config = parse_<format>()'
def _parse_csv(self) -> dict:
self.logger.log_message("Parsing file {self.configfile} in csv format.")
data = dict()
with open(self.configfile) as file:
reader = csv.reader(file)
for row in reader:
data[row[0]] = row[1:]
return data
def _parse_tsv(self) -> dict:
self.logger.log_message("Parsing file {self.configfile} in tsv format.")
data = dict()
with open(self.configfile) as file:
reader = csv.reader(file, delimiter="\t")
for row in reader:
data[row[0]] = row[1:]
return data
def _parse_json(self) -> dict:
self.logger.log_message("Parsing file {self.configfile} in json format.")
with open(self.configfile) as file:
data = json.load(file)
return data
def _parse_yaml(self) -> dict:
self.logger.log_message("Parsing file {self.configfile} in yaml format.")
with open(self.configfile) as file:
data = yaml.full_load(file)
return data
def _check_config(self) -> None:
self._check_presence_command()
self._check_type_command()
self._parse_params_from_command()
self._check_presence_params()
self._check_length_params()
def _check_presence_command(self) -> None:
if "command" not in self.config.keys():
self.logger.log_error("The required field 'command' is not present in the configfile.")
raise KeyError("The required field 'command' is not present in the configfile.")
def _check_type_command(self):
if isinstance(self.config["command"], list) == True:
self.logger.log_message("")
self.config["command"] = str(self.config["command"][0])
def _check_presence_params(self) -> None:
for param in self.config["params"]:
if param not in self.config["command"]:
self.logger.log_error("The field for parameter '{param}' is not present in the configfile.")
raise ValueError("The field for parameter '{param}' is not present in the configfile.")
def _check_length_params(self) -> None:
params_lists = {key: self.config[key] for key in self.config["params"]}
if len(set(map(len, params_lists.values()))) != 1: # Ensure all params lists are of the same length
self.logger.log_error("Not all parameters have an equal number of values.")
raise ValueError("Not all parameters have an equal number of values.")
|
JavaScript
|
UTF-8
| 4,020
| 3.953125
| 4
|
[] |
no_license
|
// Steps to build the game
// Set a random number
// check the number to see if it is above, below, or the same as the number
// display score when checking the button
// reset the game with button
// document.getElementById('message').textContent = 'Correct Number!';
// document.getElementById('number').textContent = 13;
// document.getElementById('score').textContent = 10;
// document.getElementById('guess').value = 10;
let secreatNumber = Math.trunc(Math.random() * 20) + 1;
//document.getElementById('number').textContent = secreatNumber;
let score = Number(document.getElementById('score').textContent);
let highscore = 0;
const displayMessage = function(message) {
document.querySelector('#message').textContent = message;
}
// Start the game
document.getElementById('checkNumber').addEventListener('click', function(){
const guess = Number(document.querySelector('#guess').value);
console.log(guess, typeof(guess));
// There is no guess
if(!guess) {
// document.getElementById('message').textContent = 'No number!';
displayMessage('No number!');
// Player wins the game
} else if (guess === secreatNumber) {
// document.getElementById('message').textContent = "You guessed the number!";
displayMessage("You guessed the number!");
document.querySelector('.container').style.backgroundColor = '#60b347';
document.querySelector('#number').style.fontSize = '12rem';
document.querySelector('.mysteryNumberSection').style.width = '250px';
document.getElementById('number').textContent = secreatNumber;
if(score > highscore) {
highscore = score;
document.getElementById('highScore').textContent = highscore;
}
// When guess is wrong
} else if(guess !== secreatNumber) {
if (score > 1) {
// document.getElementById('message').textContent = guess > secreatNumber ? "Guess is too High!" : "Guess is too low!";
displayMessage(guess > secreatNumber ? "Guess is too High!" : "Guess is too low!");
score = score - 1;
document.getElementById('score').textContent = score;
} else {
//document.getElementById('message').textContent = 'You lost the game!';
displayMessage('You lost the game!');
document.getElementById('score').textContent = 0;
}
}
// // Guess is too high
// } else if (guess > secreatNumber) {
// if (score > 1) {
// document.getElementById('message').textContent = "Guess is too High!";
// score = score - 1;
// document.getElementById('score').textContent = score;
// } else {
// document.getElementById('message').textContent = 'You lost the game!';
// document.getElementById('score').textContent = 0;
// }
// // Guess is too low
// } else if (guess < secreatNumber) {
// if (score > 1) {
// document.getElementById('message').textContent = "Guess is too low!";
// score = score - 1;
// document.getElementById('score').textContent = score;
// } else {
// document.getElementById('message').textContent = 'You lost the game!';
// document.getElementById('score').textContent = 0;
// }
// }
});
// Play again
document.getElementById('reset').addEventListener('click', function(){
score = 20;
secreatNumber = Math.trunc(Math.random() * 20) + 1;
//document.getElementById('message').textContent = "Start guesing...";
displayMessage('start guesing...');
document.getElementById('score').textContent = score;
document.getElementById('number').textContent = '?';
document.querySelector('#guess').value = '';
document.querySelector('.container').style.backgroundColor = 'black';
document.querySelector('#number').style.fontSize = '6rem';
document.querySelector('.mysteryNumberSection').style.width = '160px';
})
|
JavaScript
|
UTF-8
| 1,237
| 2.515625
| 3
|
[] |
no_license
|
const url = new RequestUrlResource()
if (url.getItens().id) {
const id = url.getItens().id
document.querySelector('form').addEventListener('submit', function (e) {
e.preventDefault()
const config = new configClass()
const request = new FetchResource('json', false, {
'Content-Type': 'application/json;charset=UTF-8',
'Authorization': localStorage.getItem('token')
})
const nome = document.getElementsByName('nome')[0].value
const descrissao = document.getElementsByName('descrissao')[0].value
const inicioEstimado = document.getElementsByName('inicioEstimado')[0].value
const terminoEstimado = document.getElementsByName('terminoEstimado')[0].value
const obj = {
nome: nome,
descrissao: descrissao,
inicioEstimado: inicioEstimado,
terminoEstimado: terminoEstimado,
projeto: id
}
request.POST(config.getUrl() + 'atividade', obj).then(e => {
console.log(e)
window.location.href = '../index.html?id=' + id
}).catch(e => {
console.log(e)
alert(e)
})
})
}
|
Python
|
UTF-8
| 1,042
| 2.9375
| 3
|
[] |
no_license
|
#Script Loads table data from a csv file into a Spanner Instance
# csv file is from Github repo for sqkdb
!wget https://raw.githubusercontent.com/amercado-chemistsclub/sqldb_data_servers/master/tech_stocks_history.csv
from google.cloud import spanner
from google.cloud.spanner import Client
import pandas as pd
#Read the csv file and select columns into a dataframe
df_tech = pd.read_csv("tech_stocks_history.csv")
df = df_tech[['Date','NVDA','TSLA']]
#Connect to the Spanner instance and database that were set up
instance_id = 'spanner-ETFtest'
instance = spanner_client.instance(instance_id)
database_id = 'historical_etf'
database = instance.database(database_id)
#Instead of row by row insertion run the batch load as a list
columns = df.columns
values = df.values.tolist()
#Insert the data into the table specifed with the batch method
with database.batch() as batch:
batch.insert(
table='Stock_past',
columns=columns,
values=values
)
#Afterwords view the data inserted on the GCP Spanner cosole
|
C++
|
UTF-8
| 3,279
| 2.921875
| 3
|
[] |
no_license
|
#include "Utility Objects.h"
int CircleI::getLeft()
{
return m_Position.x - m_Radius;
}
int CircleI::getRight()
{
return m_Position.x + m_Radius;
}
int CircleI::getTop()
{
return m_Position.y - m_Radius;
}
int CircleI::getBottom()
{
return m_Position.y + m_Radius;
}
Vector2I CircleI::getCentre()
{
return m_Position;
}
float CircleF::getLeft()
{
return m_Position.x - m_Radius;
}
float CircleF::getRight()
{
return m_Position.x + m_Radius;
}
float CircleF::getTop()
{
return m_Position.y - m_Radius;
}
float CircleF::getBottom()
{
return m_Position.y + m_Radius;
}
Vector2F CircleF::getCentre()
{
return m_Position;
}
int RectI::getLeft()
{
return m_Position.x;
}
int RectI::getRight()
{
return m_Position.x + m_Size.width;
}
int RectI::getTop()
{
return m_Position.y;
}
int RectI::getBottom()
{
return m_Position.y + m_Size.height;
}
Vector2I RectI::getTopLeftVertex() //This is also the same as calling to get the position;
{
return m_Position;
}
Vector2I RectI::getTopRightVertex()
{
Vector2I vector;
vector.x = getRight();
vector.y = getTop();
return vector;
}
Vector2I RectI::getBottomLeftVertex()
{
Vector2I vector;
vector.x = getLeft();
vector.y = getBottom();
return vector;
}
Vector2I RectI::getBottomRightVertex()
{
Vector2I vector;
vector.x = getRight();
vector.y = getBottom();
return vector;
}
Vector2I RectI::getCentre()
{
Vector2I vector;
vector.x = m_Position.x + (m_Size.width/2);
vector.y = m_Position.y + (m_Size.height/2);
return vector;
}
void RectF::setZero() //sets all values to zero
{
m_Position.x = 0;
m_Position.y = 0;
m_Size.width = 0;
m_Size.height = 0;
}
float RectF::getLeft()
{
return m_Position.x;
}
float RectF::getRight()
{
return m_Position.x + m_Size.width;
}
float RectF::getTop()
{
return m_Position.y;
}
float RectF::getBottom()
{
return m_Position.y + m_Size.height;
}
Vector2F RectF::getTopLeftVertex()//This is also the same as calling to get the position;
{
return m_Position;
}
Vector2F RectF::getTopRightVertex()
{
Vector2F vector;
vector.x = getRight();
vector.y = getTop();
return vector;
}
Vector2F RectF::getBottomLeftVertex()
{
Vector2F vector;
vector.x = getLeft();
vector.y = getBottom();
return vector;
}
Vector2F RectF::getBottomRightVertex()
{
Vector2F vector;
vector.x = getRight();
vector.y = getBottom();
return vector;
}
Vector2F RectF::getCentre()
{
Vector2F vector;
vector.x = m_Position.x + (m_Size.width/2);
vector.y = m_Position.y + (m_Size.height/2);
return vector;
}
Param::Param()
{
m_Type = 0;
}
Param::~Param()
{
}
void Param::setType(int type)
{
m_Type = type;
}
int Param::getType()
{
return m_Type;
}
CircleI scaleShape(CircleI circle, int scale)
{
circle.m_Radius *= scale;
return circle;
}
CircleF scaleShape(CircleF circle, float scale)
{
circle.m_Radius *= scale;
return circle;
}
RectI scaleShape(RectI rect, int scale)
{
rect.m_Size.width *= scale;
rect.m_Size.height *= scale;
return rect;
}
RectF scaleShape(RectF rect, float scale)
{
rect.m_Size.width *= scale;
rect.m_Size.height *= scale;
return rect;
}
|
C
|
UTF-8
| 230
| 3.65625
| 4
|
[] |
no_license
|
#include<stdio.h>
int main()
{
int a,i,b,n;
printf("Enter the number:");
scanf("%d",&a);
printf("Enter the number of multiples");
scanf("%d",&n);
for(i=0;i<=n;i++)
{
b=i*a;
printf("\n%d*%d=%d",a,i,b);
}
return 0;
}
|
C++
|
UTF-8
| 552
| 2.578125
| 3
|
[] |
no_license
|
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <math.h>
#define PIE 3.1415926
using namespace std;
int main()
{
char temp[10];
int aa, bb, cas = 1;
while (scanf("%d%s%d", &aa, temp, &bb) && aa + bb)
{
double a = aa, b = bb, angle = atan(b / a);
double k = 200 / (2 * angle * pow((a / 2) * (a / 2) + (b / 2) * (b / 2), 0.5) + a);
cout << "Case " << cas++ << ": ";
printf("%.2lf", a * k);
cout << " ";
printf("%.2lf\n", b * k);
}
return 0;
}
|
Java
|
UTF-8
| 1,069
| 1.820313
| 2
|
[] |
no_license
|
package com.wisdom.common.activiti.model.vo;
/**
*
* @author shangl
* @description 流程业务中间表
* @date 2017/8/14
*
*/
@SuppressWarnings("unused")
public class ActBusinessVO {
private static final long serialVersionUID = 1L;
private String wsdId;
private String executionId;
private String businessId;
private String businessType;
public String getWsdId() {
return wsdId;
}
public void setWsdId(String wsdId) {
this.wsdId = wsdId;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getBusinessId() {
return businessId;
}
public void setBusinessId(String businessId) {
this.businessId = businessId;
}
public String getBusinessType() {
return businessType;
}
public void setBusinessType(String businessType) {
this.businessType = businessType;
}
}
|
Markdown
|
UTF-8
| 2,250
| 2.59375
| 3
|
[
"LicenseRef-scancode-generic-cla"
] |
no_license
|
## <a name="understanding-azure-resource-templates-and-resource-groups"></a>Informazioni su modelli di risorse e gruppi di risorse di Azure
La maggior parte delle applicazioni, distribuite ed eseguite da Microsoft Azure, vengono create da una combinazione di tipi diversi di risorse cloud (ad esempio, una o più macchine virtuali e uno o più account di archiviazione, un database SQL, una rete virtuale, una rete CDN e così via). I [modelli di Azure Resource Manager](../articles/resource-group-authoring-templates.md) consentono di distribuire e gestire insieme queste risorse diverse tra loro usando una descrizione JSON delle risorse e parametri di configurazione e distribuzione associati.
Dopo aver definito un modello di risorsa basato su JSON, è possibile eseguirlo e impostare la distribuzione del le risorse definite in Azure tramite un comando di PowerShell. È possibile eseguire questo comando di PowerShell in modo autonomo nella shell dei comandi PowerShell o integrandolo in uno script di PowerShell contenente logica di automazione aggiuntiva.
Le risorse create con i modelli di Gestione risorse di Azure verranno distribuite in un gruppo di risorse Azure nuovo o esistente. Un gruppo di risorse di Azure consente di gestire più risorse distribuite insieme come gruppo logico. In genere, un gruppo conterrà risorse correlate a una specifica applicazione. I gruppi di risorse di Azure forniscono un modo per gestire il ciclo di vita complessivo del gruppo o dell'applicazione e fornire le API di gestione che consentono di arrestare, avviare o eliminare contemporaneamente tutte le risorse all'interno del gruppo, applicare le regole di controllo degli accessi in base al ruolo per bloccare le autorizzazioni di sicurezza su di essi, controllare le operazioni, nonché contrassegnare le risorse con metadati aggiuntivi per una gestione più efficiente. Per altre informazioni sui gruppi di risorse di Azure, vedere [Panoramica di Gestione risorse di Azure](https://azure.microsoft.com/documentation/articles/resource-group-overview/).
Gli esempi di automazione seguenti illustrano come usare i modelli di Gestione risorse di Azure e distribuire gruppi di risorse tramite PowerShell o CLI.
<!--HONumber=Jan17_HO3-->
|
JavaScript
|
UTF-8
| 247
| 3.21875
| 3
|
[
"MIT"
] |
permissive
|
export function KgtoLb (kg) {
const lb = 2.205
let resultado = kg*lb
return parseFloat(resultado.toFixed(1))
}
export function LbtoKg (lb) {
const kg = 0.454
let resultado = lb*kg
return parseFloat(resultado.toFixed(1))
}
|
C
|
UTF-8
| 3,126
| 4.3125
| 4
|
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stack.h"
#include "ADTErrors.h"
enum
{
CREATE_STACK = 1,
INSERT_DATA,
REMOVE_DATA,
GET_SIZE,
IS_EMPTY,
PRINT,
DESTROY,
EXIT
};
void GetInitValues(size_t *_initialSize, size_t *_BlockSize)
{
printf("Please enter the initial size:");
scanf("%lu",_initialSize);
printf("Please enter the incremet block size:");
scanf("%lu",_BlockSize);
getchar();
}
int main()
{
Stack *stack = NULL;
int action, NewData, isEmpty;
size_t initialSize, BlockSize, numOfElements;
ErrCode err;
do
{
printf("\nPlease select an action by pressing the suitable button: \n1 - for creating dynamic stack.\n");
printf("2 - for inserting a new data to the stack.\n3 - for removing the last data from the stack. \n");
printf("4 - for get the number of elements in the stack.\n5 - for checking if the stack is empty \n");
printf("6 - for printing the stack \n7 - for destroying the dynamic stack \n");
printf("8 - for exit.\n");
scanf("%d", &action);
switch (action)
{
case CREATE_STACK:
GetInitValues(&initialSize,&BlockSize);
stack = StackCreate(initialSize,BlockSize);
if(NULL == stack)
{
printf("\nMemory overflow or Illegal input in initial size or in incremet block size\n");
break;
}
printf("\nstack created!\n");
break;
case INSERT_DATA:
printf("\nPlease insert new data:");
scanf("%d",&NewData);
err = StackPush(stack,NewData);
switch (err)
{
case ERR_NOT_EXIST:
printf("\nstack not exist!\n");
break;
case ERR_OVERFLOW:
printf("\nMemory overflow!\n");
break;
case ERR_ILLEGAL_INPUT:
printf("\nIllegal data input!\n");
break;
default:
printf("\nData added to the vector!\n");
break;
}
break;
case REMOVE_DATA:
err = StackPop(stack,&NewData);
switch (err)
{
case ERR_NOT_EXIST:
printf("\nstack not exist or stack is empty!\n");
break;
case ERR_OVERFLOW:
printf("\nMemory overflow!\n");
break;
default:
printf("\nData %d removed!\n", NewData);
break;
}
break;
case GET_SIZE:
numOfElements = StackNumOfelements(stack);
if(0 == numOfElements)
{
printf("\nstack if empty or not exist!\n");
break;
}
printf("\nnumber of elements in the stack is %ld \n",numOfElements);
break;
case IS_EMPTY:
isEmpty = StackIsEmpty(stack);
if(true == isEmpty)
{
printf("\nstack is empty or isn't exist!\n");
break;
}
printf("\nstack is not empty!\n");
break;
case PRINT:
err = PrintStack(stack);
if(ERR_NOT_EXIST == err)
{
printf("\nstack not exist!\n");
}
break;
case DESTROY:
StackDestroy(stack);
stack = NULL;
printf("\nstack destroyed!\n");
break;
case EXIT:
StackDestroy(stack);
stack = NULL;
printf("\nbye byeee :) \n");
break;
default:
printf("you press a wrong button!");
break;
}
}while(EXIT != action);
return 0;
}
|
JavaScript
|
UTF-8
| 5,843
| 3.015625
| 3
|
[
"MIT"
] |
permissive
|
/*
* JavaScript base32 / base32hex encoder and decoder
* Source https://simplycalc.com/base32-decode.php
*/
/*
* input: 5 times 8-bit characters: 11111111 00000000 11111111 00000000 11111111
* base32: 8 times 5-bit indexes : 11111 11100 00000 01111 11110 00000 00111 11111
*/
const b32c = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" // base32 dictionary
const b32h = "0123456789ABCDEFGHIJKLMNOPQRSTUV" // base32hex dictionary
const b32pad = '='
/* base32_encode_data
* Internal helper to encode data to base32 using specified dictionary.
*/
function base32_encode_data(data, len, b32x) {
var dst = ""
var i
for (i = 0; i <= len - 5; i += 5)
{
dst += b32x[data.charCodeAt(i) >>> 3]
dst += b32x[((data.charCodeAt(i) & 0x07) << 2) | (data.charCodeAt(i+1) >>> 6)]
dst += b32x[(data.charCodeAt(i+1) & 0x3E) >>> 1]
dst += b32x[((data.charCodeAt(i+1) & 0x01) << 4) | (data.charCodeAt(i+2) >>> 4)]
dst += b32x[((data.charCodeAt(i+2) & 0x0F) << 1) | (data.charCodeAt(i+3) >>> 7)]
dst += b32x[(data.charCodeAt(i+3) & 0x7C) >>> 2]
dst += b32x[((data.charCodeAt(i+3) & 0x03) << 3) | ((data.charCodeAt(i+4) & 0xE0) >>> 5)]
dst += b32x[data.charCodeAt(i+4) & 0x1F]
}
if (len % 5 == 4)
{
dst += b32x[data.charCodeAt(i) >>> 3]
dst += b32x[((data.charCodeAt(i) & 0x07) << 2) | (data.charCodeAt(i+1) >>> 6)]
dst += b32x[(data.charCodeAt(i+1) & 0x3E) >>> 1]
dst += b32x[((data.charCodeAt(i+1) & 0x01) << 4) | (data.charCodeAt(i+2) >>> 4)]
dst += b32x[((data.charCodeAt(i+2) & 0x0F) << 1) | (data.charCodeAt(i+3) >>> 7)]
dst += b32x[(data.charCodeAt(i+3) & 0x7C) >>> 2]
dst += b32x[(data.charCodeAt(i+3) & 0x03) << 3]
dst += b32pad
}
else if (len % 5 == 3)
{
dst += b32x[data.charCodeAt(i) >>> 3]
dst += b32x[((data.charCodeAt(i) & 0x07) << 2) | (data.charCodeAt(i+1) >>> 6)]
dst += b32x[(data.charCodeAt(i+1) & 0x3E) >>> 1]
dst += b32x[((data.charCodeAt(i+1) & 0x01) << 4) | (data.charCodeAt(i+2) >>> 4)]
dst += b32x[(data.charCodeAt(i+2) & 0x0F) << 1]
dst += b32pad
dst += b32pad
dst += b32pad
}
else if (len % 5 == 2)
{
dst += b32x[data.charCodeAt(i) >>> 3]
dst += b32x[((data.charCodeAt(i) & 0x07) << 2) | (data.charCodeAt(i+1) >>> 6)]
dst += b32x[(data.charCodeAt(i+1) & 0x3E) >>> 1]
dst += b32x[(data.charCodeAt(i+1) & 0x01) << 4]
dst += b32pad
dst += b32pad
dst += b32pad
dst += b32pad
}
else if (len % 5 == 1)
{
dst += b32x[data.charCodeAt(i) >>> 3]
dst += b32x[((data.charCodeAt(i) & 7) << 2)]
dst += b32pad
dst += b32pad
dst += b32pad
dst += b32pad
dst += b32pad
dst += b32pad
}
return dst
}
/* base32_encode
* Encode a JavaScript string to base32.
* Specified string is first converted from JavaScript UCS-2 to UTF-8.
*/
export function base32_encode(str) {
const utf8str = unescape(encodeURIComponent(str))
return base32_encode_data(utf8str, utf8str.length, b32c)
}
/* base32hex_encode
* Encode a JavaScript string to base32hex.
* Specified string is first converted from JavaScript UCS-2 to UTF-8.
*/
function base32hex_encode(str) {
var utf8str = unescape(encodeURIComponent(str))
return base32_encode_data(utf8str, utf8str.length, b32h)
}
/* base32_decode_data
* Internal helper to decode data from base32 using specified dictionary.
*/
function base32_decode_data(data, len, b32x) {
let dst = ""
let i
for (i = 0; i < data.length - 7; i += 8) {
const a = b32x.indexOf(data[i+0])
const b = b32x.indexOf(data[i+1])
const c = b32x.indexOf(data[i+2])
const d = b32x.indexOf(data[i+3])
const e = b32x.indexOf(data[i+4])
const f = b32x.indexOf(data[i+5])
const g = b32x.indexOf(data[i+6])
const h = b32x.indexOf(data[i+7])
dst += String.fromCharCode((a << 3) | (b >>> 2))
if (data[i+3] != b32pad)
dst += String.fromCharCode(((b << 6) & 0xC0) | (c << 1) | ((d >>> 4) & 0x01))
if (data[i+4] != b32pad)
dst += String.fromCharCode(((d << 4) & 0xF0) | (e >>> 1))
if (data[i+6] != b32pad)
dst += String.fromCharCode(((e << 7) & 0x80) | (f << 2) | (g >>> 3))
if (data[i+7] != b32pad)
dst += String.fromCharCode(((g << 5) & 0xE0) | h)
}
return dst
}
/* base32_decode
* Decode a base32 string to a JavaScript string.
* Input is assumed to be a base32 encoded UTF-8 string.
* Returned result is a JavaScript (UCS-2) string.
*/
export function base32_decode(str) {
const strUp = str.toUpperCase()
const utf8str = base32_decode_data(strUp, strUp.length, b32c)
return decodeURIComponent(escape(utf8str))
}
/* base32hex_decode
* Decode a base32hex string to a JavaScript string.
* Input is assumed to be a base32hex encoded UTF-8 string.
* Returned result is a JavaScript (UCS-2) string.
*/
function base32hex_decode(str) {
var strUp = str.toUpperCase()
var utf8str = base32_decode_data(strUp, strUp.length, b32h)
return decodeURIComponent(escape(utf8str))
}
/* base32_sniff
* Check whether specified base32 string contains base32 specific characters (as opposed to base32hex).
* Return true if specified string is base32 encoded, false if undetermined.
*/
function base32_sniff(base32) {
base32 = base32.toUpperCase()
if (base32.indexOf("W") >= 0) return true
if (base32.indexOf("X") >= 0) return true
if (base32.indexOf("Y") >= 0) return true
if (base32.indexOf("Z") >= 0) return true
return false
}
/* base32hex_sniff
* Check whether specified base32 string contains base32hex specific characters.
* Return true if specified string is base32hex encoded, false if undetermined.
*/
function base32hex_sniff(base32) {
if (base32.indexOf("0") >= 0) return true
if (base32.indexOf("1") >= 0) return true
if (base32.indexOf("8") >= 0) return true
if (base32.indexOf("9") >= 0) return true
return false
}
|
JavaScript
|
UTF-8
| 1,448
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
(function(){
'use strict';
var path = require('path');
var util = require('util');
var jsConf = require('js-conf');
function i18n(options){
options || (options = {});
//the target locale and the fallbacks
if(!options.locales){
this._locales = ['en'];
}
else if(!Array.isArray(options.locales)){
this._locales = [options.locales];
}
else{
this._locales = options.locales;
}
//replace _ to -, eg. zh_CN->zh-CN
for(var i in this._locales){
this._locales[i] = this._locales[i].replace('_', '-');
}
this._dir = options.dir || './i18n';
this._data = {};//locale name and keys mapping
for(var j in this._locales) loadData.call(this, this._locales[j]);
}
module.exports = i18n;
function loadData(name){
if(!name) return;
this._data[name] = {};
try{
this._data[name] = jsConf.readFileSync(path.join(this._dir, name+'.json'));
}catch(e){
}
}
i18n.prototype.t = function(key){
if(!key) return key;
var value = key;
for(var i in this._locales){
var name = this._locales[i];
if(!name) continue;
if(!this._data[name]) loadData.call(this, name);
if(typeof this._data[name][key] === 'string'){
value = this._data[name][key];
break;
}
}
var args = [value], len = arguments.length;
for(var ii=1; ii<len; ++ii) args.push(arguments[ii]);
return util.format.apply(null, args);
};
})();
|
Markdown
|
UTF-8
| 1,632
| 2.828125
| 3
|
[] |
no_license
|
# Homework 1 Assigment -01 HTML CSS Git: Code Refactor
## 01-Homework Repository
This repository is where my first homework assigment for refactoring takes place. As I move along in the course, I hope to have learned how to write better README files.
## Link to GitHub Page
https://robertsantos-dfw.github.io/01-Homework/
## Screenshot example

## Challenge/Reason for Refactoring
Web accessibility is an increasingly important consideration for businesses. It ensures that people with disabilities can access a website using assistive technologies such as video captions, screen readers, and braille keyboards. Making a website accessible is also good for business for many reasons, one of them being that accessible sites are better positioned in search engines like Google. It also helps companies avoid litigation that can occur when people with disabilities cannot access their website.
## User Story
```
AS A marketing agency
I WANT a codebase that follows accessibility standards
SO THAT our own site is optimized for search engines
```
### Changes
A large part of the refactoring process was done in the style.css file. Head class was changed to Header in the body of the HTML and the CSS was also updated to reflect the changes. Once reviewing redundant CSS, I merged what I could find that was using the same padding, margin, float, font-family, and font-size together as one entry.
Another large consolidation was the IMG stylings that used the same margins, padding, floating, width, etc. throughout the CSS.
|
Markdown
|
UTF-8
| 2,314
| 2.859375
| 3
|
[
"Apache-2.0"
] |
permissive
|
SmartBackup
===========
SmartBackup is a backup mod for Minecraft that backs up the game's world data.
Backup Methods
--------------
There are two different methods of backing up data using SmartBackup. You can
choose between these methods when manually running a backup and the backup
scheduler can be instructed to use different methods on different intervals.
### Snapshots
Snapshots are a restorable state of the world at a given time. Snapshots use
hard links instead of copying all of the world data each time you take a backup.
This means that the disk space used by each snapshot is -- barring a complete
re-write of the data -- less than it would be if you were to perform a typical
copy-based backup. It also means that the time required to do a backup is less
than a copy-based backup since less data is written to disk.
While this is typically better than copying the whole world for each backup,
there are a couple of reasons why you might want to use a copy-based backup:
* Your filesystem does not support hard links.
* On-disk corruption of world data (while unlikely, still possible unless the
underlying filesystem is smart/resilient enough).
* Ease of moving a single file around (ie to an off-site storage system) instead
of a folder.
### Archives
Archives are the traditional method of taking world backups. They're things like
a tarball or zip file of the world data. The world data is copied in its
entirety into an archive file and is optionally compressed.
Backup Scheduling
-----------------
Not yet documented.
The /smartbackup Command
------------------------
Not yet documented.
License
-------
SmartBackup is licensed with the Apache License, version 2.0:
Copyright 2015 John "LuaMilkshake" Marion
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.
|
C#
|
UTF-8
| 11,747
| 2.578125
| 3
|
[] |
no_license
|
using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace TextEditor
{
public partial class TextEditor : Form
{
private User user;
public TextEditor(User user)
{
InitializeComponent();
this.user = user;
// Disable the rich text box if the user is View Only
if (user.getUserType() == "View"){
resultTxt.ReadOnly = true;
ViewOnlyLabel.Visible = true;
}
// Fix this part later
foreach(FontFamily font in FontFamily.Families.ToList()){
fontFamilyComboBox.Items.Add(font.Name);
}
/// Personalise the message based on the login user first name
welcomeLbl.Text = "Welcome back, " + user.getFirstName();
// Set the default value of font box in the beginning
fontSizeComboBox.SelectedItem = fontSizeComboBox.Items[0];
fontFamilyComboBox.SelectedItem = fontFamilyComboBox.Items[1];
}
///////////////////
/////// Structure of code ///////
//////////////////
//// 1. Menustrip events
//// 2. Top Toolstrip Events
//// 3. Left Toolstrip events
//// 4. Non events re-useable methods
/////////////////////////////////////////
/////// 1. Menu strip Events ///////////
///////////////////////////////////////
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.Title = "Open a Rich Text File";
openFile.Filter = "Rich Text File (*.rtf)|*.rtf";
DialogResult result = openFile.ShowDialog();
if (result == DialogResult.OK) {
string filename = openFile.FileName;
try
{
resultTxt.Rtf = File.ReadAllText(openFile.FileName);
// Get the name of the file with its extension only
filenameLbl.Text = openFile.SafeFileName;
filenameLbl.Visible = true;
}
catch {
MessageBox.Show("Sorry, the file should be in either .rtf or .txt. Please select another file", "Incompatible file format", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
TextEditor newPortal = new TextEditor(this.user);
newPortal.Show();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Title = "Save RTF file";
saveFileDialog.Filter = "Rich Text File (*.rtf)|*.rtf";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
File.WriteAllText(saveFileDialog.FileName, resultTxt.Rtf);
// Get the filename and extension only
FileInfo fi = new FileInfo(saveFileDialog.FileName);
filenameLbl.Text = fi.Name;
filenameLbl.Visible = true;
}
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Title = "Save-as RTF file";
saveFileDialog.Filter = "Rich Text File (*.rtf)|*.rtf";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
File.WriteAllText(saveFileDialog.FileName, resultTxt.Rtf);
// Get the filename and extension only
FileInfo fi = new FileInfo(saveFileDialog.FileName);
filenameLbl.Text = fi.Name;
filenameLbl.Visible = true;
}
}
private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{
resultTxt.Cut();
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
resultTxt.Copy();
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
resultTxt.Paste();
}
private void logOutToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
Login loginPortal = new Login();
loginPortal.ShowDialog();
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
About aboutTextEditor = new About();
aboutTextEditor.Show();
}
//// Under formatting Tab
private void boldToolStripMenuItem_Click(object sender, EventArgs e)
{
checkButton(topBoldBtn);
resultTxt.SelectionFont = new Font(resultTxt.SelectionFont, selectedFontStyle());
}
private void italicToolStripMenuItem_Click(object sender, EventArgs e)
{
checkButton(topItalicBtn);
resultTxt.SelectionFont = new Font(resultTxt.SelectionFont, selectedFontStyle());
}
private void underlineToolStripMenuItem_Click(object sender, EventArgs e)
{
checkButton(topUnderlineBtn);
resultTxt.SelectionFont = new Font(resultTxt.SelectionFont, selectedFontStyle());
}
/////////////////////////////////
//// 2. Top Toolstrip events /////
////////////////////////////////
private void TopNewBtn_Click(object sender, EventArgs e)
{
TextEditor newFile = new TextEditor(this.user);
newFile.Show();
}
private void topBoldBtn_Click(object sender, EventArgs e)
{
checkButton(topBoldBtn);
resultTxt.SelectionFont = new Font(resultTxt.SelectionFont, selectedFontStyle());
}
private void topItalicBtn_Click(object sender, EventArgs e)
{
checkButton(topItalicBtn);
resultTxt.SelectionFont = new Font(resultTxt.SelectionFont, selectedFontStyle());
}
private void topUnderlineBtn_Click(object sender, EventArgs e)
{
checkButton(topUnderlineBtn);
resultTxt.SelectionFont = new Font(resultTxt.SelectionFont, selectedFontStyle());
}
private void topNewBtn_Click_1(object sender, EventArgs e)
{
TextEditor newFile = new TextEditor(this.user);
newFile.Show();
}
private void topOpenBtn_Click(object sender, EventArgs e)
{
resultTxt.Clear();
OpenFileDialog openFile = new OpenFileDialog();
openFile.Title = "Open a Rich Text File";
openFile.Filter = "Rich Text File (*.rtf)|*.rtf";
DialogResult result = openFile.ShowDialog();
if (result == DialogResult.OK)
{
string filename = openFile.FileName;
try
{
resultTxt.Rtf = File.ReadAllText(openFile.FileName);
filenameLbl.Text = openFile.SafeFileName;
filenameLbl.Visible = true;
}
catch
{
MessageBox.Show("Sorry, the file should be in .rtf format. Please select another file", "Incompatible file format", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void topSaveBtn_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Title = "Save a Rich Text File";
saveFileDialog.Filter = "Rich Text File (*.rtf)|*.rtf";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
File.WriteAllText(saveFileDialog.FileName, resultTxt.Rtf);
// Get the filename and extension only
FileInfo fi = new FileInfo(saveFileDialog.FileName);
filenameLbl.Text = fi.Name;
filenameLbl.Visible = true;
}
}
private void topSaveasBtn_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Title = "Save-as a Rich Text File";
saveFileDialog.Filter = "Rich Text File (*.rtf)|*.rtf";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
File.WriteAllText(saveFileDialog.FileName, resultTxt.Rtf);
// Get the filename and extension only
FileInfo fi = new FileInfo(saveFileDialog.FileName);
filenameLbl.Text = fi.Name;
filenameLbl.Visible = true;
}
}
private void topHelpBtn_Click(object sender, EventArgs e)
{
// Open a local html file
System.Diagnostics.Process.Start("help.html");
}
private void fontFamilyComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (fontFamilyComboBox.SelectedItem != null && fontSizeComboBox.SelectedItem != null)
{
string selectedFont = fontFamilyComboBox.SelectedItem.ToString();
resultTxt.SelectionFont = new Font(selectedFont, Convert.ToInt32(fontSizeComboBox.SelectedItem.ToString()), selectedFontStyle());
}
}
private void fontSizeComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (fontFamilyComboBox.SelectedItem != null && fontSizeComboBox.SelectedItem != null) {
int fontSize = Convert.ToInt32(fontSizeComboBox.SelectedItem.ToString());
resultTxt.SelectionFont = new Font(fontFamilyComboBox.SelectedItem.ToString(), fontSize, selectedFontStyle());
}
}
////////////////////////////////
//// 3. Left Toolstrip Events ///
///////////////////////////////
private void leftCutBtn_Click(object sender, EventArgs e)
{
resultTxt.Cut();
}
private void leftCopyBtn_Click(object sender, EventArgs e)
{
resultTxt.Copy();
}
private void leftPasteBtn_Click(object sender, EventArgs e)
{
resultTxt.Paste();
}
//////////////////////////////////////
//// 4. Non-events Reusable functions///
//////////////////////////////////////
//// Check and uncheck the button based on its check state
private void checkButton(ToolStripButton button) {
if (button.Checked) button.Checked = false;
else button.Checked = true;
}
///// Get the selected font style based on the checked button
private FontStyle selectedFontStyle() {
FontStyle selected = new FontStyle();
// Check if the button is checked, if yes, append to the existing font style
if (topUnderlineBtn.Checked) selected = FontStyle.Underline;
if (topBoldBtn.Checked) selected = selected | FontStyle.Bold;
if (topItalicBtn.Checked) selected = selected | FontStyle.Italic;
return selected;
}
}
}
|
Java
|
UTF-8
| 1,013
| 3.109375
| 3
|
[] |
no_license
|
package leetcode.p2545;
import java.util.Arrays;
/**
* Solution
*
* @author heshan
* @date 2023/1/26
*/
public class Solution {
public int[][] sortTheStudents(int[][] score, int k) {
int[] ks = new int[score.length];
for (int i = 0; i < score.length; i++) {
ks[i] = score[i][k];
}
Arrays.sort(ks);
int[][] res = new int[score.length][];
for (int i = 0; i < score.length; i++) {
int s = score[i][k];
int ind = score.length - findIndex(ks, s) - 1;
res[ind] = score[i];
}
return res;
}
private int findIndex(int[] arr, int target) {
int l = 0;
int r = arr.length;
while (l < r) {
int mid = l + ((r - l) >> 1);
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
l = mid + 1;
} else {
r = mid;
}
}
return -1;
}
}
|
C++
|
UTF-8
| 439
| 2.8125
| 3
|
[] |
no_license
|
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<int> v1;
vector<int> ::iterator it;
int main(void)
{
int n,i,j;
while(1)
{
cin >> n;
if(!n)
break;
for(i = 0; i < n; i++)
{
cin >> j;
v1.push_back(j);
}
sort(v1.begin(),v1.end());
for( i = 0; i < n; i++)
{
if( i != n-1)
cout << v1[i] << " ";
else
cout << v1[i] << endl;
}
v1.clear();
}
return 0;
}
|
TypeScript
|
UTF-8
| 10,395
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
import "@plumier/testing"
import { RouteAnalyzerFunction, RouteMetadata } from "@plumier/core"
import { JwtAuthFacility } from "@plumier/jwt"
import { cleanupConsole } from "@plumier/testing"
import reflect from "@plumier/reflect"
import Plumier, { domain, RestfulApiFacility, route } from "plumier"
describe("Route Analyzer", () => {
it("Should identify missing backing parameter", async () => {
@domain()
class Domain {
constructor(public name: string) { }
}
class AnimalController {
@route.get(":c")
method(@reflect.type([Domain]) a: Domain[], b: number) { }
}
const mock = console.mock()
const app = await new Plumier()
.set(new RestfulApiFacility())
.set({ controller: [AnimalController] })
.initialize()
expect(cleanupConsole(mock.mock.calls)).toMatchSnapshot()
console.mockClear()
})
it("Should identify missing backing parameter on root decorator", async () => {
@route.root("/beast/:type")
class AnimalController {
@route.get(":a")
method(a: number, b: number) { }
}
const mock = console.mock()
const app = await new Plumier()
.set(new RestfulApiFacility())
.set({ controller: [AnimalController] })
.initialize()
expect(cleanupConsole(mock.mock.calls)).toMatchSnapshot()
console.mockClear()
})
it("Should identify missing type information for data binding", async () => {
class AnimalController {
method(a: number) { }
}
const mock = console.mock()
const app = await new Plumier()
.set(new RestfulApiFacility())
.set({ controller: [AnimalController] })
.initialize()
expect(cleanupConsole(mock.mock.calls)).toMatchSnapshot()//("PLUM1001")
console.mockClear()
})
it("Should not identify missing type information for data binding if method has no parameter", async () => {
class AnimalController {
method() { }
}
const mock = console.mock()
const app = await new Plumier()
.set(new RestfulApiFacility())
.set({ controller: [AnimalController] })
.initialize()
expect(cleanupConsole(mock.mock.calls).length).toBe(4)
console.mockClear()
})
it("Should identify duplicate route", async () => {
@route.root("/beast")
class AnimalController {
@route.get()
method(a: number) { }
}
class BeastController {
@route.get()
method(a: number) { }
}
const mock = console.mock()
const app = await new Plumier()
.set(new RestfulApiFacility())
.set({ controller: [AnimalController, BeastController] })
.initialize()
expect(cleanupConsole(mock.mock.calls)).toMatchSnapshot()//.toContain("PLUM1003")
console.mockClear()
})
it("Should identify if model doesn't have type information for parameter binding", async () => {
class AnimalModel {
constructor(
public id: number,
public name: string
) { }
}
class AnimalController {
@route.post()
method(a: AnimalModel) { }
}
const mock = console.mock()
const app = await new Plumier()
.set(new RestfulApiFacility())
.set({ controller: [AnimalController] })
.initialize()
expect(cleanupConsole(mock.mock.calls)).toMatchSnapshot()//.toContain("PLUM1005")
console.mockClear()
})
it("Should identify if model property doesn't have type information for parameter binding", async () => {
@domain()
class AnimalModel {
constructor(
public id: number,
public name: any
) { }
}
class AnimalController {
@route.post()
method(a: AnimalModel) { }
}
const mock = console.mock()
const app = await new Plumier()
.set(new RestfulApiFacility())
.set({ controller: [AnimalController] })
.initialize()
expect(cleanupConsole(mock.mock.calls)).toMatchSnapshot()//.toContain("PLUM1005")
console.mockClear()
})
it("Should identify if model doesn't have type information for parameter binding recursive", async () => {
class TagModel {
constructor(
public id: number,
public name: string
) { }
}
@domain()
class AnimalModel {
constructor(
public id: number,
public name: string,
public tag: TagModel
) { }
}
class AnimalController {
@route.post()
method(a: AnimalModel) { }
}
const mock = console.mock()
const app = await new Plumier()
.set(new RestfulApiFacility())
.set({ controller: [AnimalController] })
.initialize()
expect(cleanupConsole(mock.mock.calls)).toMatchSnapshot()//.toContain("PLUM1005")
console.mockClear()
})
it("Should identify if array doesn't have type information for parameter binding", async () => {
@domain()
class AnimalModel {
constructor(
public id: number,
public name: string
) { }
}
class AnimalController {
@route.post()
method(a: AnimalModel[]) { }
}
const mock = console.mock()
const app = await new Plumier()
.set(new RestfulApiFacility())
.set({ controller: [AnimalController] })
.initialize()
expect(cleanupConsole(mock.mock.calls)).toMatchSnapshot()//.toContain("PLUM1006")
console.mockClear()
})
it("Should identify if array property doesn't have type information for parameter binding", async () => {
@domain()
class AnimalModel {
constructor(
public id: number,
public name: number[]
) { }
}
class AnimalController {
@route.post()
method(a: AnimalModel) { }
}
const mock = console.mock()
const app = await new Plumier()
.set(new RestfulApiFacility())
.set({ controller: [AnimalController] })
.initialize()
expect(cleanupConsole(mock.mock.calls)).toMatchSnapshot()//.toContain("PLUM1005")
console.mockClear()
})
it("Should not error when analyzing cross reference model", async () => {
class Client {
@reflect.noop()
id: number
@reflect.type(x => Animal)
animals: any
}
class Animal {
@reflect.noop()
id: number
@reflect.type(x => Client)
name: any
}
class AnimalController {
@route.post()
method(a: Animal) { }
}
const mock = console.mock()
const app = await new Plumier()
.set(new RestfulApiFacility())
.set({ controller: [AnimalController] })
.initialize()
expect(cleanupConsole(mock.mock.calls)).toMatchSnapshot()
console.mockClear()
})
it("Should be able to extends the route analyzer", async () => {
class AnimalController {
@route.get()
method() { }
}
const mock = console.mock()
const analyzer: RouteAnalyzerFunction = (route: RouteMetadata, allRoutes: RouteMetadata[]) => ([{ type: "error", message: "PLUM1005: Just an error" }])
const app = await new Plumier()
.set(new RestfulApiFacility())
.set({ analyzers: [analyzer] })
.set({ controller: [AnimalController] })
.initialize()
expect(cleanupConsole(mock.mock.calls)).toMatchSnapshot()//.toContain("PLUM1005: Just an error")
console.mockClear()
})
})
describe("Analyzer Report", () => {
it("Should trim long controller report", async () => {
class AveryVeryVeryVeryVeryLongNamedController {
@route.get()
aVerryVerryVerryVerryVerryLongNamedMethod(very: string, long: string, list: string, of: string, method: string, parameters: string) { }
@route.get()
anotherVerryVerryVerryVerryVerryLongNamedMethod(very: string, long: string, list: string, of: string, method: string, parameters: string) { }
}
const mock = console.mock()
const app = await new Plumier()
.set(new RestfulApiFacility())
.set(new JwtAuthFacility({ secret: "lorem" }))
.set({ controller: [AveryVeryVeryVeryVeryLongNamedController] })
.initialize()
expect(cleanupConsole(mock.mock.calls)).toMatchSnapshot()
console.mockClear()
})
it("Should only trim parameters if still long", async () => {
class UsersController {
@route.get("")
get(very: string, long: string, list: string, of: string, method: string, parameters: string) { }
@route.post("")
save(very: string, long: string, list: string, of: string, method: string, parameters: string) { }
}
const mock = console.mock()
const app = await new Plumier()
.set(new RestfulApiFacility())
.set({ controller: [UsersController] })
.initialize()
expect(cleanupConsole(mock.mock.calls)).toMatchSnapshot()
console.mockClear()
})
it("Should not trim if short enough to fit", async () => {
class UsersController {
@route.get("")
get(very: string, long: string) { }
@route.post("")
save(very: string, long: string) { }
}
const mock = console.mock()
const app = await new Plumier()
.set(new RestfulApiFacility())
.set({ controller: [UsersController] })
.initialize()
expect(cleanupConsole(mock.mock.calls)).toMatchSnapshot()
console.mockClear()
})
})
|
JavaScript
|
UTF-8
| 2,863
| 2.515625
| 3
|
[] |
no_license
|
import React, { Component } from "react";
import API from "../../utils/API";
class Results extends Component {
state = {
savedGame: [],
}
componentDidMount() {
API.savedGame()
.then(savedGame => this.setState({ savedGame: savedGame }))
.catch(err => console.error(err));
}
handleSave = game => {
if (this.state.savedGame.map(game => game._id).includes(game._id)) {
API.deleteBook(game._id)
.then(deletedGame => this.setState({ savedGame: this.state.savedGame.filter(game => game._id !== deletedGame._id) }))
.catch(err => console.error(err));
} else {
API.savedGame(game)
.then(savedGame => this.setState({ savedGame: this.state.savedGame.concat([savedGame]) }))
.catch(err => console.error(err));
}
}
render() {
return (
<div>
{!this.props.game ? ( // might need to add this.props.game.length
<h1 className="text-center">No Results to Display</h1>
) : (
<div>
{this.props.game.map(result => (
<div className="card mb-3" key={result._id}>
<div className="row">
<div className="col-md-2">
<img alt={result.title} className="img-fluid" src={result.image} />
</div>
<div className="col-md-10">
<div className="card-body">
<h5 className="card-title">{result.title} by {result.authors}</h5>
<p className="card-text">{result.description}</p>
<div>
<a href={result.link} className="btn badge-pill btn-outline-dark mt-3" target="_blank" >View</a>
<button onClick={() => this.handleSave(result)} className="btn badge-pill btn-outline-warning mt-3 ml-3" >
{this.state.game.map(game => game._id).includes(result._id) ? "Unsave" : "Save"}
</button>
</div>
</div>
</div>
</div>
</div>
))}
</div>
)}
</div>
)
}
}
export default Results;
|
Java
|
UTF-8
| 6,214
| 2.046875
| 2
|
[] |
no_license
|
package com.mycompany.webapp.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.mycompany.webapp.dto.Pager;
import com.mycompany.webapp.dto.Qna;
import com.mycompany.webapp.dto.QnaBoardComment;
import com.mycompany.webapp.service.QnaBoardCommentService;
import com.mycompany.webapp.service.QnaService;
@Controller
public class QnaController {
@Resource private QnaService qnaService;
@Resource private QnaBoardCommentService qnaBoardCommentService;
Logger logger = LoggerFactory.getLogger(QnaController.class);
@GetMapping("/qna")
public String qna(Model model) {
//게시물 목록 가져오기
int totalRows = qnaService.getQnaTotalRows();
Pager pager = new Pager(5, 5, totalRows, 1);
List<Qna> list = qnaService.getQnaList(pager);
model.addAttribute("list", list);
model.addAttribute("pager", pager);
return "qna";
}
@PostMapping("/qnaWrite")
public String qnaWrite(Qna qna, HttpServletRequest request, Model model) throws Exception {
//로그인한 mid 세팅
HttpSession session = request.getSession();
String mid = (String) session.getAttribute("mid");
qna.setMid(mid);
//서비스를 이용해서 게시물 쓰기
qnaService.qnaWrite(qna);
//게시물 목록 가져오기
int totalRows = qnaService.getQnaTotalRows();
Pager pager = new Pager(5, 5, totalRows, 1);
List<Qna> list = qnaService.getQnaList(pager);
model.addAttribute("list", list);
model.addAttribute("pager", pager);
return "qnaList";
}
@GetMapping("/qnaList")
public String qnaList(@RequestParam(defaultValue = "1") int pageNo, Model model) {
int totalRows = qnaService.getQnaTotalRows();
Pager pager = new Pager(5, 5, totalRows, pageNo);
List<Qna> list = qnaService.getQnaList(pager);
model.addAttribute("list", list);
model.addAttribute("pager", pager);
return "qnaList";
}
@GetMapping("/qnaDetail")
public String qnaDetail(HttpSession session, int bno, Model model) {
Qna qnaBoard = qnaService.getQnaBoard(bno);
model.addAttribute("qnaBoard", qnaBoard);
List<QnaBoardComment> qnaBoardCommentsList = qnaBoardCommentService.getBoardComments(bno);
model.addAttribute("qnaBoardCommentsList", qnaBoardCommentsList);
return "qnaDetail";
}
@GetMapping("/photodownload")
public void photodownload(String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
//파일의 데이터를 읽기 위한 입력 스트림 얻기
String saveFilePath = "D:/MyWorkspace/images/member/" + fileName;
InputStream is = new FileInputStream(saveFilePath);
//응답 HTTP 헤더 구성
//1)Content - Type 헤더 구성(파일의 종류)
ServletContext application = request.getServletContext();
String fileType = application.getMimeType(fileName);
response.setContentType("fileType");
//2) Content-Disposition 헤더 구성(다운로드할 파일의 이름 지정)
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
//3) Content-Length 헤더 구성(다운로드할 파일의 크기를 지정)
int fileSize = (int)new File(saveFilePath).length();
response.setContentLength(fileSize);
//응답 HTTP의 바디(본문) 구성
OutputStream os = response.getOutputStream();
FileCopyUtils.copy(is, os); //is에서 읽어서 os로 보낸다는 뜻
os.flush();
os.close();
is.close();
}
@PostMapping("/qnaDetailDelete")
public void qnaDetailDelete(int bno, HttpServletResponse response) throws IOException {
qnaService.qnaDetailDelete(bno);
JSONObject jsonObject = new JSONObject();
jsonObject.put("result", "success");
String json = jsonObject.toString();
PrintWriter out = response.getWriter();
response.setContentType("application/json;charset=utf-8");
out.println(json);
out.flush();
out.close();
}
@GetMapping("/qnaDetailUpdate")
public String qnaDetailUpdate(int bno, Model model) {
Qna qnaBoard = qnaService.getQnaBoard(bno);
model.addAttribute("qnaBoard", qnaBoard);
return "qnaDetailUpdate";
}
@PostMapping("/qnaDetailUpdate")
public void qnaDetailUpdate(Qna qna, HttpServletResponse response) throws IOException {
qnaService.qnaDetailUpdate(qna);
//JSON 생성
JSONObject jsonObject = new JSONObject(); //결과값 {} 요렇게 나오려면 이렇게, 배열로 [] 나오려면 array로 써라
jsonObject.put("result", "success");
String json = jsonObject.toString(); //{"result" : "success"}
//응답 보내기
PrintWriter out = response.getWriter();
response.setContentType("application/json;charset=utf-8");
out.println(json);
out.flush();
out.close();
}
@RequestMapping("/qnaCommentWrite")
public String qnaCommentWrite(String ccomment,int bno, String mid, Model model) {
QnaBoardComment qnaBoardComment=new QnaBoardComment();
qnaBoardComment.setBno(bno);
qnaBoardComment.setCcontent(ccomment);
qnaBoardComment.setMid(mid);
qnaBoardCommentService.QnaCommentsWrite(qnaBoardComment);
List<QnaBoardComment> qnaBoardCommentsListWrite = qnaBoardCommentService.getQnaBoardCommentWrite(bno);
model.addAttribute("qnaBoardCommentsListWrite", qnaBoardCommentsListWrite);
return "qnaCommentHTML";
}
}
|
Python
|
UTF-8
| 4,092
| 2.90625
| 3
|
[] |
no_license
|
import numpy as np
import pandas as pd
import scipy
import scipy.sparse as sp
import scipy.sparse.linalg
from scipy.sparse import *
from scipy.sparse.linalg import norm
import random
from scipy import linalg
import timeit
import matplotlib.pyplot as plt
from PIL import Image
"""Function computes the CUR decomposition of matrix A, sampling numr rows and numc columns. A is of size nrows X ncols."""
def CUR(mat,numr,numc,nrows,ncols):
A_T = np.transpose(mat)
A = sp.csr_matrix(mat)
A_T = sp.csr_matrix(A_T)
rows = np.zeros(nrows, dtype=float)
r = []
rowsprob = np.zeros(nrows, dtype=float)
total = 0
tempr = sp.coo_matrix(A)
#calculating the probability of each row being selected
for i,j,v in zip(tempr.row, tempr.col, tempr.data):
rowsprob[i] = rowsprob[i] + v*v
total = total + v*v
rowsprob = rowsprob/total
#calculating the cumulative probabilities
cumrowsprob = np.zeros(nrows, dtype=float)
cumrowsprob[0] = rowsprob[0]
for i in range(1,rowsprob.size):
cumrowsprob[i] = cumrowsprob[i-1] + rowsprob[i]
#generating random rows and building r matrix
for i in range(0,numr):
rand = random.random()
entry = np.searchsorted(cumrowsprob,rand)
rows[entry] = rows[entry] + 1
#handling duplicates by multiplying duplicate rows with square root of number of duplications and removing duplicates
selectedrows = []
rows = np.sqrt(rows)
for i in range(0,nrows):
if rows[i]>0:
r.append((A[i].toarray()/((numr*rowsprob[i])**0.5))*rows[i])
selectedrows.append(i)
cols = np.zeros(ncols, dtype=float)
c = []
colsprob = np.zeros(ncols, dtype=float)
total = 0
tempc = sp.coo_matrix(A_T)
#calculating the probability of each column being selected
for i,j,v in zip(tempc.row, tempc.col, tempc.data):
colsprob[i] = colsprob[i] + v*v
total = total + v*v
colsprob = colsprob/total
#calculating the cumulative probabilities
cumcolsprob = np.zeros(ncols, dtype=float)
cumcolsprob[0] = colsprob[0]
for i in range(1,colsprob.size):
cumcolsprob[i] = cumcolsprob[i-1] + colsprob[i]
#generating random cols and building r matrix
for i in range(0,numc):
rand = random.random()
entry = np.searchsorted(cumcolsprob,rand)
cols[entry] = cols[entry] + 1
#handling duplicates by multiplying duplicate columns with square root of number of duplications and removing duplicates
selectedcols = []
cols = np.sqrt(cols)
for i in range(0,ncols):
if cols[i]>0:
c.append((A_T[i].toarray()/((numc*colsprob[i])**0.5))*cols[i])
selectedcols.append(i)
c = np.vstack(c)
r = np.vstack(r)
#finding the intersection of c and r = w
w = np.zeros(shape=(len(selectedrows),len(selectedcols)))
for i in range(0,len(selectedrows)):
for j in range(0,len(selectedcols)):
w[i][j] = mat[selectedrows[i]][selectedcols[j]]
c = sp.csr_matrix(c)
c = c.transpose()
r = sp.csr_matrix(r)
#computing the SVD decomposition of the w matrix
x,z,y_T = linalg.svd(w)
z = linalg.diagsvd(z, x.shape[1], y_T.shape[0])
y = np.transpose(y_T)
#computing the u matrix
zplus = linalg.pinv(np.matrix(z))
zplussquare = zplus*zplus
u = np.matmul(y,np.matmul(zplussquare,np.transpose(x)))
#computing the reconstructed matrix and error
reconstructedmatrix = c*(u*r)
errormatrix = sp.csr_matrix(A-reconstructedmatrix)
reconstructionerror = norm(errormatrix)
return reconstructedmatrix
def generate(image_red,image_green,image_blue,dimension,original_bytes,row,col):
cases = [1,2,5,10]
for n in cases:
dim = int(dimension * n)
reconR = CUR(image_red,dim,dim,row,col)
reconG = CUR(image_green,dim,dim,row,col)
reconB = CUR(image_blue,dim,dim,row,col)
image_recon = np.zeros((row,col,3))
image_recon[:,:,0] = reconR/255
image_recon[:,:,1] = reconG/255
image_recon[:,:,2] = reconB/255
image_recon[image_recon < 0] = 0
image_recon[image_recon > 1] = 1
result = Image.fromarray((image_recon*255).astype(np.uint8))
result.save('lena_cur_'+str(n)+'.jpg')
|
Python
|
UTF-8
| 4,517
| 2.640625
| 3
|
[] |
no_license
|
import locale
import time
import traceback
from collections import deque
from dataclasses import dataclass
import telegram
import settings
TELEGRAM_MAX_MESSAGE_LENGTH = 4096
TELEGRAM_PERSONAL_MESSAGE_MAX_RATE = 30 # 30 messages/sec
TELEGRAM_GROUP_MESSAGE_MAX_RATE = 20/60 # 20 messages/min
@dataclass
class TelegramMessage:
chat_id: str
text: str
class CianNotifierBot:
bot = telegram.Bot(token=settings.TELEGRAM_BOT_TOKEN)
personal_messages_queue = deque()
group_messages_queue = deque()
actions_map = {
'change': 'изменено',
'add': 'добавлено',
}
fields_to_ignore = ['statistic', 'priceChanges']
@classmethod
def check_ignored_field(cls, field_path):
for ignored in cls.fields_to_ignore:
if ignored in field_path:
return True
return False
@classmethod
def send_message(cls, chat_id, message):
message_end = ' < ... >'
content_len = TELEGRAM_MAX_MESSAGE_LENGTH - len(message_end)
message = (message[:content_len] + message_end) if len(message) > content_len else message
return cls.bot.send_message(chat_id=chat_id, text=message)
@classmethod
def enqueue_message(cls, chat_id, message):
message = TelegramMessage(chat_id, message)
if int(chat_id) > 0:
cls.personal_messages_queue.append(message)
else:
cls.group_messages_queue.append(message)
@staticmethod
def process_personal_messages_queue():
while True:
try:
message = CianNotifierBot.personal_messages_queue.pop()
CianNotifierBot.send_message(message.chat_id, message.text)
except IndexError:
pass
except Exception as e:
print('process_personal_messages_queue')
print(f'Traceback: {traceback.format_exc()}')
time.sleep(1/TELEGRAM_PERSONAL_MESSAGE_MAX_RATE)
@staticmethod
def process_group_messages_queue():
while True:
try:
message = CianNotifierBot.group_messages_queue.pop()
CianNotifierBot.send_message(message.chat_id, message.text)
except IndexError:
pass
except Exception as e:
print('process_group_messages_queue')
print(f'Traceback: {traceback.format_exc()}')
time.sleep(1/TELEGRAM_GROUP_MESSAGE_MAX_RATE)
@classmethod
def generate_readable_diff(cls, diff):
result = []
for action, field_path, values in diff:
action_text = cls.actions_map.get(action, action)
if type(field_path) is not str:
field_path = '.'.join(str(f) for f in field_path)
if cls.check_ignored_field(field_path):
continue
if action == 'change':
values_text = ' -> '.join(f'`{v}`' for v in values)
else:
values_text = str(values)
text = f'{action_text}: {field_path}\n{values_text}'
result.append(text)
return '\n\n'.join(result)
@staticmethod
def get_offer_link(offer):
cian_id = offer['cianId']
return f'https://www.cian.ru/rent/flat/{cian_id}/'
@classmethod
def get_offer_info(cls, offer):
offer_link = cls.get_offer_link(offer)
price = offer['bargainTerms']['price']
stats = offer.get('statisctic', {})
total_views = stats.get('total')
daily_views = stats.get('daily')
price = locale.currency(price, grouping=True)
added_date = offer['added']
text = f'{offer_link}\nЦена: {price}\nДобавлено: {added_date}'
if total_views and daily_views:
text += '\nПросмотров: {total_views}\nЗа сегодня: {daily_views}'
return text
@classmethod
def send_new_offer(cls, offer):
info_text = cls.get_offer_info(offer)
text = f'#новое предложение:\n{info_text}'
return cls.enqueue_message(settings.TELEGRAM_NEW_OFFER_CHAT_ID, text)
@classmethod
def send_offer_changed(cls, offer, diff):
info_text = cls.get_offer_info(offer)
diff_text = cls.generate_readable_diff(diff)
if diff_text:
text = f'#изменение предложения:\n{info_text}\n\n{diff_text}'
return cls.enqueue_message(settings.TELEGRAM_CHANGE_OFFER_CHAT_ID, text)
|
Java
|
UTF-8
| 7,878
| 2.765625
| 3
|
[] |
no_license
|
package finki.ukim.mk.battlesofhistory.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import finki.ukim.mk.battlesofhistory.model.Battle;
import finki.ukim.mk.battlesofhistory.model.Conflict;
/*
This is a class for instantating a Database Access Object.
This object will provide methods which will help for accessing the SQLite database.
The class contains methods and properties for both Conflict and Battle object database manipulation.
properties:
database = an SQLiteDatabase object which will be the database
dbHelper - a ConflictBattleOpenHelper object for creating and opening a SQLite database.
allColumnsConflict - a String array that contains the names of the columns in the database for Conflict
allColumnsBattle - a String array that contains the names of the columns in the database for Conflict
methods:
public ConflictBattleDao(Context context) - a constructor
public void openWritable() - getting a database with the dbHelper
public void close() - closing the dbHelper and database
public boolean insertConflict(Conflict item) - insertion of Conflict item in database
public boolean insertBattle(Battle item) - insertion of Battle item in database
public void trancateTableConflict() - deletion of Conflict table
public void trancateTableBattle() - deletion of Battle table
public boolean updateConflict(Conflict item) - update of a Conflict row
public boolean updateBattle(Battle item) - update of a Battle row
public List<Conflict> getAllItemsConflict() - returns a list of all Conflict rows
public List<Battle> getAllItemsBattle() - returns a list of all Battle rows
helper methods:
protected Conflict cursorToItemConflict(Cursor cursor) - returns a Conflict object on the cursor's position
protected Battle cursorToItemBattle(Cursor cursor) - returns a Battle object on the cursor's position
protected ContentValues itemToContentValuesConflict(Conflict item) - returns a ContentValues object in which
the properties (like uri or id) of the Conflict item send as argument are contained
protected ContentValues itemToContentValuesBattle(Battle item) - returns a ContentValues object in which
the properties (like uri or id) of the Battle item send as argument are contained
*/
public class ConflictBattleDao {
private SQLiteDatabase database;
private ConflictBattleDbOpenHelper dbHelper;
private String[] allColumnsConflict = {
ConflictBattleDbOpenHelper.COLUMN_ID_CONFLICT,
ConflictBattleDbOpenHelper.COLUMN_URL_CONFLICT};
private String[] allColumnsBattle = {
ConflictBattleDbOpenHelper.COLUMN_ID_BATTLE,
ConflictBattleDbOpenHelper.COLUMN_URL_BATTLE,
ConflictBattleDbOpenHelper.COLUMN_PLACE_BATTLE};
public ConflictBattleDao(Context context) {
dbHelper = new ConflictBattleDbOpenHelper(context);
}
public void openWritable() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
database.close();
dbHelper.close();
}
public boolean insertConflict(Conflict item) {
if (item.getId() != null) {
return updateConflict(item);
}
long insertId = database.insert(ConflictBattleDbOpenHelper.TABLE_NAME_CONFLICTS, null,
itemToContentValuesConflict(item));
if (insertId > 0) {
item.setId(insertId);
return true;
} else {
return false;
}
}
public boolean insertBattle(Battle item) {
if (item.getId() != null) {
return updateBattle(item);
}
long insertId = database.insert(ConflictBattleDbOpenHelper.TABLE_NAME_BATTLES, null,
itemToContentValuesBattle(item));
if (insertId > 0) {
item.setId(insertId);
return true;
} else {
return false;
}
}
public void trancateTableConflict() {
database.delete(ConflictBattleDbOpenHelper.TABLE_NAME_CONFLICTS, null, null);
}
public void trancateTableBattle() {
database.delete(ConflictBattleDbOpenHelper.TABLE_NAME_BATTLES, null, null);
}
public boolean updateConflict(Conflict item) {
long numRowsAffected = database.update(ConflictBattleDbOpenHelper.TABLE_NAME_CONFLICTS,
itemToContentValuesConflict(item), ConflictBattleDbOpenHelper.COLUMN_ID_CONFLICT
+ " = " + item.getId(), null);
return numRowsAffected > 0;
}
public boolean updateBattle(Battle item) {
long numRowsAffected = database.update(ConflictBattleDbOpenHelper.TABLE_NAME_BATTLES,
itemToContentValuesBattle(item), ConflictBattleDbOpenHelper.COLUMN_ID_BATTLE
+ " = " + item.getId(), null);
return numRowsAffected > 0;
}
public List<Conflict> getAllItemsConflict() {
List<Conflict> items = new ArrayList<Conflict>();
Cursor cursor = database.query(ConflictBattleDbOpenHelper.TABLE_NAME_CONFLICTS,
allColumnsConflict, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
items.add(cursorToItemConflict(cursor));
} while (cursor.moveToNext());
}
cursor.close();
return items;
}
public List<Battle> getAllItemsBattle() {
List<Battle> items = new ArrayList<Battle>();
Cursor cursor = database.query(ConflictBattleDbOpenHelper.TABLE_NAME_BATTLES,
allColumnsBattle, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
items.add(cursorToItemBattle(cursor));
} while (cursor.moveToNext());
}
cursor.close();
return items;
}
protected Conflict cursorToItemConflict(Cursor cursor) {
Conflict item = new Conflict();
item.setId(cursor.getLong(cursor
.getColumnIndex(ConflictBattleDbOpenHelper.COLUMN_ID_CONFLICT)));
item.setUri(cursor.getString(cursor
.getColumnIndex(ConflictBattleDbOpenHelper.COLUMN_URL_CONFLICT)));
return item;
}
protected Battle cursorToItemBattle(Cursor cursor) {
Battle item = new Battle();
item.setId(cursor.getLong(cursor
.getColumnIndex(ConflictBattleDbOpenHelper.COLUMN_ID_BATTLE)));
item.setUri(cursor.getString(cursor
.getColumnIndex(ConflictBattleDbOpenHelper.COLUMN_URL_BATTLE)));
item.setPlace(cursor.getString(cursor
.getColumnIndex(ConflictBattleDbOpenHelper.COLUMN_PLACE_BATTLE)));
return item;
}
protected ContentValues itemToContentValuesConflict(Conflict item) {
ContentValues values = new ContentValues();
if (item.getId() != null) {
values.put(ConflictBattleDbOpenHelper.COLUMN_ID_CONFLICT, item.getId());
}
values.put(ConflictBattleDbOpenHelper.COLUMN_URL_CONFLICT, item.getUri());
return values;
}
protected ContentValues itemToContentValuesBattle(Battle item) {
ContentValues values = new ContentValues();
if (item.getId() != null) {
values.put(ConflictBattleDbOpenHelper.COLUMN_ID_BATTLE, item.getId());
}
values.put(ConflictBattleDbOpenHelper.COLUMN_URL_BATTLE, item.getUri());
values.put(ConflictBattleDbOpenHelper.COLUMN_PLACE_BATTLE, item.getPlace());
return values;
}
}
|
Ruby
|
UTF-8
| 456
| 3.5
| 4
|
[] |
no_license
|
# Reimplment Enumerable#reduce
def reduce(list, initial)
@accumulator = initial
list.each do |value|
@accumulator = yield(@accumulator, value)
end
@accumulator
end
p reduce(5..10, 0) { |sum, element| sum + element }
p reduce(5..10, 1) { |product, n| product * n }
p reduce([1, 2, 3, 4], 0) { |sum, element| sum + element }
p reduce(1..4, 0) { |sum, element| sum + element }
p reduce(["a", "b", "c", "d"], "") { |sum, element| sum + element }
|
C++
|
UTF-8
| 2,325
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
//
// Timer.h
// MSO
//
// Created by Erik Frisk on 10/09/15.
// Copyright (c) 2015 Linköping University. All rights reserved.
//
#ifndef _TIMER_H
#define _TIMER_H
#if defined(WIN32) || defined(_WINDOWS_)
#include <ctime>
#else
#include <sys/resource.h>
#endif
class Timer {
#if defined(WIN32) || defined(_WINDOWS_)
clock_t tictime;
clock_t toctime;
#else
struct rusage ticusage;
struct rusage tocusage;
// Subtract two values of type struct timeval.
// Taken from The GNU C Library Manual at
// http://www.gnu.org/software/libtool/manual/libc/Elapsed-Time.html
int timeval_subtract(struct timeval *result,
struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000) {
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
tv_usec is certainly positive. */
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
};
#endif
public:
Timer() { tic(); };
~Timer( ) { };
#if defined(WIN32) || defined(_WINDOWS_)
void tic() { tictime=clock(); toctime=0; };
void toc() { toctime=clock(); };
double elapsed()
{
if( toctime>0 ) {
return ((double)((double)(toctime-tictime)*1000/(double)CLOCKS_PER_SEC));
} else {
return(-1);
}
};
#else
void tic() { getrusage(RUSAGE_SELF,&ticusage); tocusage=ticusage; };
void toc() { getrusage(RUSAGE_SELF,&tocusage); };
double elapsed()
{
struct timeval diffs;
struct timeval diffu;
timeval_subtract(&diffu,&tocusage.ru_utime,&ticusage.ru_utime);
timeval_subtract(&diffs,&tocusage.ru_stime,&ticusage.ru_stime);
double deltasT=1000*(diffs.tv_sec+1e-6*diffs.tv_usec);
double deltauT=1000*(diffu.tv_sec+1e-6*diffu.tv_usec);
double deltaT = deltauT;//+deltasT;
if( deltauT+deltasT>0 ) {
return deltaT;
} else {
return -1.0;
}
};
#endif
};
#endif
|
SQL
|
UTF-8
| 506
| 2.71875
| 3
|
[] |
no_license
|
--Group 13
--property_options.sql
--October 19, 2016
--WEBD3201
-- Dropping tables clear out any existing data
DROP TABLE IF EXISTS property_options;
--Creates the table again
CREATE TABLE property_options(
value INT PRIMARY KEY,
property VARCHAR(30) NOT NULL
);
--Inserts rows inside the table
INSERT INTO property_options (value, property) VALUES (1, 'AC');
INSERT INTO property_options (value, property) VALUES (2, 'Pool');
INSERT INTO property_options (value, property) VALUES (4, 'Fireplace');
|
C++
|
UTF-8
| 1,642
| 2.953125
| 3
|
[] |
no_license
|
//
// Created by jelly on 2020/01/06.
//
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
vector<int> v;
int a[27][2];
bool check[27];
void goPreorder(int i) {
if (!check[i]) {
v.push_back(i);
check[i] = true;
}
if (a[i][0] && !check[a[i][0]]) {
goPreorder(a[i][0]);
}
if (a[i][1] && !check[a[i][1]]) {
goPreorder(a[i][1]);
}
}
void goMid(int i) {
if (!check[i]) {
check[i] = true;
}
if (a[i][0] && !check[a[i][0]]) {
goMid(a[i][0]);
}
v.push_back(i);
if (a[i][1] && !check[a[i][1]]) {
goMid(a[i][1]);
}
}
void goLast(int i) {
if (!check[i]) {
check[i] = true;
}
if (a[i][0] && !check[a[i][0]]) {
goLast(a[i][0]);
}
if (a[i][1] && !check[a[i][1]]) {
goLast(a[i][1]);
}
v.push_back(i);
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
char root, left, right;
cin >> root >> left >> right;
root -= 64;
left -= 64;
right -= 64;
if (left > 0) {
a[root][0] = left;
}
if (right > 0) {
a[root][1] = right;
}
}
goPreorder(1);
for (int c : v) {
cout << char(c + 64);
}
cout << endl;
memset(check, false, sizeof(check));
v.clear();
goMid(1);
for (int c : v) {
cout << char(c + 64);
}
cout << endl;
memset(check, false, sizeof(check));
v.clear();
goLast(1);
for (int c : v) {
cout << char(c + 64);
}
cout << endl;
return 0;
}
|
C#
|
UTF-8
| 1,748
| 2.515625
| 3
|
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BasicAttack : Ability {
//public float damage = 10f;
/// <summary>
/// Constructor for Basic Attack, put in the gameobject of the object that basic attack will be added to.
/// </summary>
/// <param name="obj">The object that will be using the ability</param>
public BasicAttack(GameObject obj)
{
Initialize(obj);
}
public override void Initialize(GameObject obj)
{
base.Initialize(obj);
anim = gameObject.GetComponentInChildren<Animator>();
range_max = 1;
range_min = 0;
dwell_time = 1.0f;
abilityName = "Basic Attack";
abilityImage = Resources.Load <Sprite>("UI/Ability/warriorSkill3") ;
if (abilityImage == null)
Debug.Log("Unable to load image");
//Debug.Log("Adding " + abilityName + " to " + parent.name);
}
public override bool UseSkill(GameObject target)
{
if(base.UseSkill(target))
{
Skill(target);
return true;
}
else
{
return false;
}
}
private void Skill(GameObject target)
{
if (anim != null)
{
Debug.Log(string.Format("Using Skill {0}. Attacker={1} Defender={2}", abilityName, gameObject.name, target.name));
rotateAtObj(target);
anim.SetTrigger("MeleeAttack");
//justin set attack string array choice hereS
gameObject.GetComponent<Actor>().PlaySound("attack");
}
target.GetComponent<Actor>().TakeDamage(damage,gameObject);
DwellTime.Attack(dwell_time);
}
}
|
C++
|
UTF-8
| 704
| 3
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
#include <wchar.h>
extern "C" {
size_t wcslen(const wchar_t* str)
{
size_t len = 0;
while (*(str++))
++len;
return len;
}
wchar_t* wcscpy(wchar_t* dest, const wchar_t* src)
{
wchar_t* originalDest = dest;
while ((*dest++ = *src++) != '\0')
;
return originalDest;
}
int wcscmp(const wchar_t* s1, const wchar_t* s2)
{
while (*s1 == *s2++)
if (*s1++ == 0)
return 0;
return *(const wchar_t*)s1 - *(const wchar_t*)--s2;
}
wchar_t* wcschr(const wchar_t* str, int c)
{
wchar_t ch = c;
for (;; ++str) {
if (*str == ch)
return const_cast<wchar_t*>(str);
if (!*str)
return nullptr;
}
}
}
|
TypeScript
|
UTF-8
| 3,540
| 2.953125
| 3
|
[] |
no_license
|
import { getSubjectAvg } from '../components/subject/Subject';
import { IGrade, IUserSubject } from '../@types';
export default class GradeHelper {
public static getDate(grade: IGrade, separator?: string): string {
let date = new Date(grade.date);
if (!date) {
return 'invalid date format';
}
if (!separator) {
separator = '.';
}
let d = date.getDate().toString();
let m = (date.getMonth() + 1).toString();
let y = date.getFullYear().toString();
d = (d.length === 1) ? `0${d}` : d;
m = (m.length === 1) ? `0${m}` : m;
y = (y.length === 1) ? `0${y}` : y;
return `${d}${separator}${m}${separator}${y}`;
}
public static valueToString(grade: IGrade | number): string {
let val;
if (typeof grade == 'number') {
val = grade.toFixed(2);
} else {
val = grade.value.toFixed(2);
}
if (val.charAt(val.length - 2) === '0') {
val = val.charAt(0);
}
if (val.charAt(val.length - 1) === '0') {
val = val.substr(0, 3);
}
return val;
}
public static getAllGrades(subjects: IUserSubject[]) {
let grades: number[] = [];
subjects.forEach(s => {
s.grades.forEach(g => { grades.push(g.value); });
});
return grades;
}
public static getAllGradesByDate(subjects: IUserSubject[]) {
let grades: IGrade[] = [];
subjects.forEach(s => {
grades.push(...s.grades);
});
grades.sort((a, b) => {
return (a.date > b.date)
? 1
: (a.date < b.date)
? -1
: 0
});
return grades;
}
public static getAllGradesByDateWithSubject(subjects: IUserSubject[]) {
type GradeWithName = {
grade: IGrade,
name: string
};
let withName: GradeWithName[] = [];
subjects.forEach(s => {
let gwns: GradeWithName[] = s.grades.map(g => {
return {
grade: g,
name: s.name
}
});
withName.push(...gwns);
});
withName.sort((a, b) => {
return (a.grade.date > b.grade.date)
? 1
: (a.grade.date < b.grade.date)
? -1
: 0
});
return withName;
}
public static getAllGradesValuesByDate(subjects: IUserSubject[]) {
return GradeHelper.getAllGradesByDate(subjects).map(g => g.value);
}
public static getAllAvgs(subjects: IUserSubject[]) {
let grades: number[] = [];
subjects.forEach(s => {
grades.push(getSubjectAvg(s));
});
return grades;
}
public static getTotalAvg(subjects: IUserSubject[]) {
let grades = GradeHelper.getAllGradesByDate(subjects);
if (grades.length === 0) {
return 0;
}
let weightsSum = Math.max(grades.map(g => g.weight).reduce((p, c) => p + c), 1);
return grades.map(g => g.value * g.weight).reduce((p, c) => p + c) / weightsSum;
}
public static getSortedByDate(grades: IGrade[]) {
let arr = [...grades];
return arr.sort((a, b) => {
return a.date > b.date
? 1
: a.date < b.date
? -1
: 0;
});
}
}
|
JavaScript
|
UTF-8
| 3,221
| 3.125
| 3
|
[
"MIT"
] |
permissive
|
'use strict';
var currentEventId;
// Call this function when the page loads (the "ready" event)
$(document).ready(function() {
initializePage();
$('.join_class').click(function(){
// AJAX request
$.get("/data", addEvent);
});
});
/*
* Function that is called when the document is ready.
*/
function initializePage() {
console.log("Javascript connected!");
$(".test").click(eventClick);
var dataURL = "/data";
$.get(dataURL, changeLoginData);
$.get(dataURL, hideJoinedEvents);
}
function changeLoginData(result){
var resultFound = false;
for(var i = 1; i < result.logindata.length; i++){
if(result.logindata[i].currentusr == "1"){
document.getElementById("username").innerHTML = result.logindata[i].username + " (Logout)";
$('#loginbuttonsalt').html('<button id="newEvent" type="button" class="btn btn-info btn-large">Create New Event</button> <button id="viewEvent" type="button" class="btn btn-info btn-large">Events You've Joined</button>');
$('#loginbuttons').html(' <button id="newEvent" type="button" class="btn btn-info btn-large">Create New Event</button> </br> </br> <button id="viewEvent" type="button" class="btn btn-info btn-large">Events You've Created/Joined</button>');
resultFound = true;
}
}
if(!resultFound){
document.getElementById("username").innerHTML = result.logindata[0].username;
//Don't let guests join events
$(".join_class").toggle();
}
}
function hideJoinedEvents(result){
console.log(result);
var joined_events_temp;
for(var i = 1; i < result.logindata.length; i++){
if(result.logindata[i].currentusr == "1"){
joined_events_temp = result.logindata[i].joined_events;
}
}
var joined_events = [];
for(var eventObj in joined_events_temp){
joined_events.push(joined_events_temp[eventObj].id);
}
console.log(this);
$(".test").each(function(){
console.log(getIDFromHTML(this));
console.log(getIDFromHTML(this)+" at "+joined_events.indexOf(getIDFromHTML(this)));
if(joined_events.indexOf(getIDFromHTML(this)) != -1){
console.log($(this).find(".join_class").toggle());
}
});
}
// Function that adds JSON information on events when title is clicked
function eventClick(e) {
// Cancel the default action, which prevents the page from reloading
e.preventDefault();
// In an event listener, $(this) is the element that fired the event
var eventClicked = $(this).closest(".test");
var eventInfo = $(eventClicked).find(".info");
//$(eventInfo).toggle();
var htmlResult = eventClicked[0];
currentEventId = getIDFromHTML(htmlResult);
console.log("id from html: " + currentEventId);
}
function getIDFromHTML(htmlString){
var lat = $($(htmlString).find("#lat")[0]).html();
console.log($(htmlString).find("#lat"));
var amp = '&'
var lng = $($(htmlString).find("#lng")[0]).html();
return lat+amp+lng;
}
/*
* Add event to current user account
*/
function addEvent(result){
console.log("HIT ID = "+currentEventId)
// find current user
var curr;
for(var i = 0; i < result["logindata"].length; i++){
// if current user then assign to curr
if(result["logindata"][i].currentusr == "1"){
$.post('/view/:id', { 'id': currentEventId, 'user':result["logindata"][i].username });
}
}
}
|
Markdown
|
UTF-8
| 1,986
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
---
layout: post
title: Monkey测试
date: 2017-03-07
tags: [Android, Test]
categories: Android
author: JayaTang
description: Monkey测试是Android平台自动化测试的一种手段
---
Monkey测试是Android平台自动化测试的一种手段,通过Monkey程序可以模拟用户触摸屏幕、滑动Trackball、按键等操作来对设备上的程序进行压力测试。
## 基础语法
基础语法如下:
```
$ adb shell monkey [options]
$ adb shell monkey -p your.package.name -v number
$ monkey -p(Package的意思)指定包名 -v(Log级别)number(次数)
```
- 常用命令举例:
> adb shell monkey -p com.example.administrator.aorise -v 100 > D:\monkey-log.txt
- 普通的提测版本建议number设置十万次;上线版本建议做3*五十万次。
## 环境搭建
1. [JDK下载](http://www.oracle.com/technetwork/java/javase/downloads/index.html):需要设置Java环境变量。Java环境变量设置自行百度。

2. ~~[Android 命令行工具](https://developer.android.com/studio/index.html)~~:需要设置Android环境变量。也可以不设置,直接在本地..\Android\sdk\platform-tools文件夹下打开cmd命令窗执行adb命令。

## LOG查看
- 程序无响应的问题:在日志中搜索 “ANR”。
- 程序崩溃的问题:在日志中搜索 “Exception”“Fatal” (如出现空指针异常 NullPointerException,肯定是有bug)。
## 运行步骤
> 1. 使用数据线连接Android设备和电脑(根据提示安装好Android设备驱动)。
> 2. 在本地..\Android\sdk\platform-tools文件夹下打开cmd命令窗。
> 3. ~~在cmd命令窗输入adb命令:adb devices 查看Android设备是否连接成功。~~
> 4. 在cmd命令窗输入monkey命令:adb shell monkey [options]
> 5. 按下回车[Enter]等待运行。
> 6. 获取本地电脑上的LOG日志。
|
Python
|
UTF-8
| 1,349
| 3.34375
| 3
|
[] |
no_license
|
"""
This script adds selected data from a CSV file to an existing TSV-file.
Name: Rebecca Davidsson, student number: 11252138.
"""
import csv
import re
with open("HPI_csv.csv") as tsvfile:
HPI = csv.reader(tsvfile, delimiter=';')
# Skip header
next(HPI)
HPIdata = []
for row in HPI:
HPIdata.append(row)
with open("world_population.tsv") as tsvfile:
reader = csv.reader(tsvfile, delimiter='\t')
# Skip header
next(reader)
WORLDdata = []
for line in reader:
WORLDdata.append(line)
# Open a new tsv file
with open("test.tsv", "w") as output:
writer = csv.writer(output, delimiter='\t')
all = []
# Iterate through every row in HPI data and WORLDdata
# to find corresponding country
for row in HPIdata:
for line in WORLDdata:
if line[1] == row[0]:
line.append(float(row[3].replace(',', '.')))
line.append(float(row[2].replace(',', '.')))
line.append(float(row[4].rstrip("%")))
line.append(float(row[5].replace(',', '.')))
line.append(float(row[6].replace(',', '.')))
all.append(line)
writer.writerows(all)
|
Markdown
|
UTF-8
| 4,136
| 3.265625
| 3
|
[] |
no_license
|
Salad-Project
=============
Salad Project
Dan Freed
Thomas Selby
CPSC 112
Salad Project
The Salad Project, as we envision it, is an application designed to make it easy for users to design and order healthy salads in an informative and calculated way. We believe that this can be turned into a real business here in New Haven with relatively low startup costs.
The app is designed to provide salads that meet the nutritional and caloric needs of the user, as determined by a dietician and optimized by a workout schedule and physical activity. The way it works is that a user would have a profile in which the user would input physical activity data - with the support of a dietician if desired, or for a basic test case a simple rubric – and desired caloric and nutritional inputs. The system would then output a salad designed to help the individual meet his or her nutritional goals that would be created and delivered to a central repository, potentially the food truck locations near the Yale Whale.
Business Plan
The plan is currently to set up and execute a Minimum Viable Product (MVP) pilot here in New Haven, targeting our friends at various graduate schools at Yale. We envision selling subscriptions for various levels, beginning perhaps at 3 salads per week and increasing to include smoothies and other healthy foods and snacks.
When a user signs up they will automatically receive a quick and easy 15 minute consultation with a certified dietician in order to evaluate their current health status, fitness and nutritional goals. Plans can be tailored in a number of ways, including weight loss, muscle gain, increased nutritional intake, etc.
In conjunction with user input, the dietician will then prescribe a diet, which can be as specific as needed: calories per meal, calories per day, meals per day, protein and fat percentage per meal and any other restrictions such as gluten free, dairy free, food allergies etc.
This input information will then serve as optimization constraints for the customer’s food. We envision starting with salads, but intend to expand – as described above – to include smoothies, breakfast, dinner, snacks and other menu items. The pickup point will be a vending machine that acts as a food pick up locker. This makes the delivery process much easier. The customer will go to a vending machine located close to their normal lunch location, scan a code from their phone and their personal meal will be dispensed.
The MVP
The MVP pilot will consist of the sale of 100 salad subscriptions at $8/per salad including 3-5 salads per week which would total between $2,400 and $4,000 of revenue. A friend of the founding teams is a current student at the school of public health and certified dietician, and has committed to giving the consultations and recording and entering data into our system. Based on the information entered and user input, salads would be created and produced, providing that all orders were received by 10 am to allow time for logistics.
Salads would be created using a scale to measure the ingredients and comply with the diet plan. One member of the founding team, Dan Freed, has years of experience in high level food service and could easily prepare 100 salads in two hours. We would then organize a pick up table and schedule at a convenient location, most likely near the food carts.
If the pilot was successful, with repeat orders, over a period of a few weeks we would have the confidence to If we can successfully run this operation for one month then we could look at ways to expand. Even without high volume, this would be a profitable business with 100 subscribers.
Use Case:
Input: Calories, Ingredients
Output: Ingredient amounts, nutritional information, order number, cost?
Usage case:
User opens application and enters name, pick up time, information
Enters desired calorie count
Chooses from a list of proteins
Chooses from a list of veggies
Chooses from a list of dry ingredients
Chooses bread or croutons
Chooses Dressing
Output order number to user
Output Nutritional info, calories, fat, protein etc.
Output ingredient amounts
|
JavaScript
|
UTF-8
| 385
| 3.234375
| 3
|
[] |
no_license
|
let json = "{ bad json }";
try {
let user = json.parse(json); // <--여기서 에러가 발생하므로
alert(user.name); //이 코드는 동작하지 않습니다.
} catch (e) {
//에러가 발생하면 제어 흐름이 catch 문으로 넘어옵니다.
alert("데이터에 에러가 있어 재요청을 시도합니다.");
alert(e.name);
alert(e.message);
}
|
TypeScript
|
UTF-8
| 371
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
import { GraphQLList, GraphQLType, isListType, isNonNullType } from 'graphql';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function extractListType(type: GraphQLType): GraphQLList<any> | undefined {
if (isListType(type)) {
return type;
}
if (isNonNullType(type)) {
return extractListType(type.ofType);
}
return undefined;
}
|
Ruby
|
UTF-8
| 120
| 3.484375
| 3
|
[] |
no_license
|
puts 'Type some things!'
words = []
puts words
while (thing = gets.chomp) != ''
words.push thing
end
puts words.sort
|
Markdown
|
UTF-8
| 1,271
| 3.1875
| 3
|
[] |
no_license
|
# avl_tree
## Description
This is the C code for an AVL (self-balancing binary) Tree. The code is split into two header files and a test driver function (main.c).
## Topography
The two header files (avl_tree.h and avl_node.h) contain the code for the AVL Tree. The third header file _string_ops.h_ contains some useful string operations.
The avl_node.h header file is all internal code and does not contain any API functions.
The avl_tree.h header file contains some API functions and some internal functions (API functions are clearly
listed at the top).
## Installation
Simply copy the header files into the directory you wish to work in. You can copy the *main.c* file too if you
would like to test the code.
Check that you have the required dependencies.
## Dependencies
None.
## Usage
The code should be used as follows:
1. On create, assign an _avl_tree_t*_ pointer to the return value of make_avl_tree().
2. Use the operations _avl_insert(avl_tree_t*, char*)_, _avl_search(avl_tree_t*, char*)_, and _avl_delete(avl_tree_t*, char*)_.
## Notes
This AVL tree uses max-left-subtree replacement for deleting a node with two children (i.e. the in-order predecessor).
Other implementations may use min-right-subtree replacement (i.e. the in-order successor).
|
Markdown
|
UTF-8
| 2,336
| 3.21875
| 3
|
[] |
no_license
|
---
title: Select
book: userguide
chapter: form-components
slug: select
weight: 90
---
A select field will display a list of values in a drop down list to users. Users can select one of the values.

#### Label
The label for this field that will appear next to it.
#### Placeholder
The placeholder text that will appear before an option is selected.
#### Data Source Type
Select the type of data the options will be pulled from.
##### Values
These are the values that will be selected on this field. The Value column is what will be stored in the database and the Label is what is shown to the users.
##### Raw Json
Enter a JSON Array to use. It should be formatted as an array of objects with named properties.
##### URL
Enter a url with a data source in JSON Array format.
#### Value Property
If Raw JSON or URL is selected, enter the name of the property on the objects that will contain the value that will be stored in the database.
#### Search Query Name
If URL is selected, enter the name of the search query parameter to filter requests with. Example, if your url is `http://api.dogs.com/dogs`, and this option is set to `type`, and the user types `nice` in the select field, then this component will send a request to `http://api.dogs.com/dogs?type=nice` and update the select items with the results. If this option is omitted, no new requests will be made when user enters text in the select field.
#### Item Template
If Raw JSON or URL is selected, use the template field to determine how the values will be displayed in the select box. You can use the **item** variable to access the current object in the array. For example, you can embed the value by using {{ item.value }} in a template.
#### Custom CSS Class
A custom CSS class to add to this component. You may add multiple class names separated by a space.
#### Tab Index
Sets the `tabindex` attribute of this component to override the tab order of the form. See the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex\) on `tabindex` for more information on how it works.

#### Required
If checked, the field will be required to have a value.
|
Python
|
UTF-8
| 1,188
| 2.84375
| 3
|
[] |
no_license
|
# HAHA
__author__ = 'ahmadauliawiguna'
import numpy as np
import os #import library untuk akses fitur OS
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
import pylab as pl
cwd = os.getcwd()
raw_data = cwd + "/dataset/seeds_dataset.csv"
dataset = np.loadtxt(raw_data, delimiter=",",dtype=None)
jumlah_baris = dataset.shape[0]
jumlah_kolom= dataset.shape[1]
#
X = dataset[:,0:jumlah_kolom-1] #load semua baris, load kolom ke 0 sampai dengan kolom ke JUMLAH KOLOM - 1
y = dataset[: , jumlah_kolom-1] #load kolom paling kanan
# AWAL
pca = PCA(n_components=7).fit(X)
pca_2d = pca.transform(X)
kmeans = KMeans(n_clusters=4, random_state=111)
kmeans.fit(X)
y_kmeans = kmeans.predict(X)
contoh = [[14.16,14.4,0.8584,5.658,3.129,3.072,5.176]]
#contoh dikelompokkan di cluster ke berapa
cluster_ke_berapa = kmeans.predict(contoh)[0]
#tampilkan titik pusatnya
centers = kmeans.cluster_centers_
n_clusters = len(centers)
pl.figure('K-means dengan 4 clusters')
pl.scatter(X[:, 0], X[:, 1], c=y_kmeans)
pl.scatter(centers[:, 0], centers[:, 1], c='black', s=200, alpha=0.5);
pl.scatter(contoh[0][0], contoh[0][1], c="blue",s=350,alpha=0.8,marker="*");
pl.show()
|
C++
|
UTF-8
| 2,202
| 3.390625
| 3
|
[] |
no_license
|
//Function Definitions
#include "pathList.h"
using namespace std;
//Store the path into a Node
PathList::Node::Node(char* p, const int& lineNum){
next = NULL;
path = new char[strlen(p)+1];
strcpy(path,p);
plist = new PostingList(lineNum);
}
//Delete the path
PathList::Node::~Node(){
delete[] path;
delete plist;
}
PathList::PathList(char* p, const int& lineNum){
//Initialise head with NULL
head = new Node(p, lineNum);
numNodes = 1;
}
//Insertion of input taken into the List, without holding duplicates
void PathList::add(char* path, const int& lineNum){
Node* temp = head;
while(1){
//If there is same line again, add that we found the word
if (!strcmp(temp->path,path)){
temp->plist->add(lineNum);
break;
}
//If we meet the word in the line for the first time
if (temp->next==NULL){
Node* n = new Node(path, lineNum);
temp->next = n;
numNodes++;
break;
}
//Keep searching in our List
temp = temp->next;
}
}
PostingList* PathList::getPlist(char* pathName){
Node* temp = head;
while(1){
//If we found the pathName
if (!strcmp(temp->path,pathName)){
return temp->plist;
break;
}
//Keep searching in our List
temp = temp->next;
}
return NULL;
}
char* PathList::getMinMaxPath(int& times, const char* cmd){
Node* temp = head;
times=temp->plist->getTimes();
char* minMaxPath = new char[strlen(temp->path)+1];
strcpy(minMaxPath,temp->path);
temp = temp->next;
int curr=0;
while(temp!= NULL){
curr = temp->plist->getTimes();
if((curr > times && !strcmp(cmd,"maxcount")) || (curr < times && !strcmp(cmd,"mincount"))){
times = curr;
delete[] minMaxPath;
minMaxPath = new char[strlen(temp->path)+1];
strcpy(minMaxPath,temp->path);
}
temp = temp->next;
}
return minMaxPath;
}
char** PathList::returnAsArray(){
char** paths = new char*[numNodes];
Node* temp = head;
int i=0;
while(temp!= NULL){
paths[i] = new char[strlen(temp->path)+1];
strcpy(paths[i++],temp->path);
temp = temp->next;
}
return paths;
}
int PathList::countPaths(){
return numNodes;
}
//PathList Destructor
PathList::~PathList(){
Node* temp = NULL;
while(head!= NULL){
temp = head;
head = head->next;
delete temp;
}
}
|
Java
|
UTF-8
| 272
| 2.171875
| 2
|
[] |
no_license
|
import java.text.SimpleDateFormat;
import java.util.Scanner;
public class test4 {
public static void main(String[] args) {
test3 post =new test3();
post.inserttest3();
System.out.println("" + post.title + ","+ post.description + "," + post.createDate);
}
}
|
Markdown
|
UTF-8
| 1,729
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
# NFCTagTechnology Class API
Use the NFCTagTechnology to connect to NFC tags and to determine their type.
**NOTE: As of Rhodes version 3.3.3, the [Barcode](barcode-api), [NFC](../rhodes/device-caps#nfc), and [Signature Capture](../rhodes/device-caps#signature-capture) APIs, as well as [Rhom data encryption](../rhodes/rhom#database-encryption) are removed from Rhodes. These features are only supported in Zebra RhoMobile Suite. If you wish to use these features, you will need to [upgrade to RhoMobile Suite](../rhomobile-install). Your application's build.yml will also need to be modified to [indicate the application type is 'Rhoelements'](../rhoelements/rhoelements2-native#enabling-motorola-device-capabilities). Additionally, a [RhoElements license](../rhoelements/licensing) is required.**
## Enabling NFC
To use the NFC methods, you need to enable NFC on the Android device and ensure that the version is 2.3.3 or later. Do this by adding that capability to the build.yml file:
:::yaml
android:
version 2.3.3
extensions:
- nfc
## Properties
The NFCTagTechnology class has several properties to determine the type of the NFC tag.
ISODEP = 'IsoDep'
MIFARE_CLASSIC = 'MifareClassic'
MIFARE_ULTRALIGHT = 'MifareUltralight'
NDEF = 'Ndef'
NDEF_FORMATABLE = 'NdefFormatable'
NFCA = 'NfcA'
NFCB = 'NfcB'
NFCF = 'NfcF'
NFCV = 'NfcV'
## get_name
Returns string - the name of the NFC tag.
:::ruby
Rho::NFCTagTechnology.get_name
## connect
Connects to an NFC tag.
## close
Closes a connection with an NFC tag.
:::ruby
Rho::NFCTagTechnology.close
## is_connected
Returns true if the application is connected with an NFC tag, false otherwise.
:::ruby
Rho::NFCTagTechnology.is_connected
|
JavaScript
|
UTF-8
| 1,651
| 2.921875
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
// Just register click handlers when the page is loaded
// Load announcements immediately as well
function loadPage() {
initialLoad();
$("#search").click(function (e) {
e.preventDefault();
var value = $("#contains").val();
search(value);
});
$("#reset").click(function (e) {
e.preventDefault();
$("#contains").val("");
search(null);
})
}
// Fetches the announcements
function initialLoad() {
var content = retrieveContent("sixth-announce");
if(content == false || content == null) {
search(null);
return;
}
loadAnnouncements(JSON.parse(content));
}
// Searches the announcements based on the user's query
function search(parameter) {
query("/fetch/announcements/list/", {"limit": 15, "contains": parameter}, function(data) {
loadAnnouncements(data);
}, function(data) {
sendAlert("An unexpected error occurred. Error Code H01", "Error");
});
}
// Load the announcements from the server, cache then display them.
function loadAnnouncements(data) {
cacheContent("sixth-announce", JSON.stringify(data));
$("#announcements").empty();
$.each(data["content"]["records"], function(index, item){
var date = new Date(item["DateAdded"] * 1000);
var displayDate = prependZero(date.getDate()) + "/" + prependZero(date.getMonth() + 1) + "/" + (date.getYear() + 1900) + " " + prependZero(date.getHours()) + ":" + prependZero(date.getMinutes());
$("#announcements").append('<div class="segment"><h2 class="title">' + item["Title"] + '</h2><p class="subtitle">Added ' + displayDate + '. Sent to ' + item["GroupName"] + '.</p><p>' + item["Content"] + '</p></div><br>');
});
}
|
Ruby
|
UTF-8
| 467
| 3.53125
| 4
|
[] |
no_license
|
class Raindrops
class << self
def convert(number)
response_string = ""
primes = {3 => "Pling", 5 => "Plang", 7 => "Plong"}
primes.each do |prime, response|
if prime_factor?(prime, number)
response_string += response
end
end
response_string = number.to_s if response_string == ""
response_string
end
def prime_factor?(prime_factor, number)
if (number/prime_factor) == (number/prime_factor.to_f)
true
end
end
end
end
|
Python
|
UTF-8
| 6,596
| 3.296875
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env python
# coding: utf-8
# # Details - Max Mean Activation
# This notebook complements the [docs](https://luminovo.gitlab.io/public/midnite/latest/visualization.html) and explains the modular max mean activation optimization method in detail.
#
# Max mean activation is an optimization in image space to maximize the mean of activations of some selected neurons.
# In[1]:
get_ipython().run_cell_magic('capture', '', '%matplotlib inline \n%load_ext autoreload\n%autoreload 2 \n%cd ../src')
# ## Preparation: Load Pretrained Model
# As in other examples, we use a pre-trained alexnet.
# In[2]:
import torchvision.models as models
from torch.nn.modules import Softmax
alexnet = models.alexnet(pretrained=True)
alexnet.classifier.add_module("softmax", Softmax(dim=1))
alexnet.eval();
# ## Channelwise Regularization/Transformation Comparisons
# Regularization is the most important part for max mean activation to pick up the information that is required. In the following, we will examine the effect of different regularizers.
# ### Baseline: No Regularization
# For illustration, we optimize for some channel of the 9th feature layer in alexnet.
# In[3]:
from midnite.visualization.base import *
from plot_utils import show
show(PixelActivation(
alexnet.features[:9],
SplitSelector(ChannelSplit(), [1]),
).visualize())
# ### Weight Decay
# Decays the gradient during optimization, i.e. causes less relevant parts of the optimized image to vanish.
# In[4]:
show(PixelActivation(
alexnet.features[:9],
SplitSelector(ChannelSplit(), [1]),
regularization = [WeightDecay(decay_factor=1e-3)]
).visualize())
# ### Blur Filter
# Performs simple blurring after each iteration. However, blurring has the issue that edges are not preserved.
# In[5]:
show(PixelActivation(
alexnet.features[:9],
SplitSelector(ChannelSplit(), [1]),
transform = BlurTransform()
).visualize())
# ### Bilateral Filter
# Very similar to blurring, but preserves edges.
# In[6]:
show(PixelActivation(
alexnet.features[:9],
SplitSelector(ChannelSplit(), [1]),
transform=BilateralTransform()
).visualize())
# ### Random Robustness Transformations
# After each iteration, random translation, rotation, and scaling are applied. The resulting optimized image is then robust to such transformations.
# In[7]:
show(PixelActivation(
alexnet.features[:9],
SplitSelector(ChannelSplit(), [1]),
transform=RandomTransform()
).visualize())
# ### Resizing Transform
# Image is scaled after each iteration.
# This has the advantage that low-frequency patterns can be picked up more easily.
# Since the image is scaled up after each step, we use an initial size of 50 pixels (instead of the default 250).
# In[8]:
show(PixelActivation(
alexnet.features[:9],
SplitSelector(ChannelSplit(), [1]),
transform=ResizeTransform(),
init_size=50
).visualize())
# ### Total Variation Regularizer
# During optimization, adds total variation to the loss (punishes difference in adjacent pixels).
# In[9]:
show(PixelActivation(
alexnet.features[:9],
SplitSelector(ChannelSplit(), [1]),
regularization=[TVRegularization(coefficient=5e2)]
).visualize())
# ## Combining Regularizers
# To obtain a better image, we use:
# - weight decay to gray out irrelevant parts
# - blur (or biliteral filter) for penalizing high-frequency noise
# - resizing to capture low-frequency patterns
# - random transformations to get robust image
# - total variation to get more natural looking image
# In[10]:
show(PixelActivation(
alexnet.features[:9],
SplitSelector(ChannelSplit(), [1]),
transform=RandomTransform()+BlurTransform()+ResizeTransform(),
regularization=[TVRegularization(), WeightDecay(decay_factor=3e-4)],
init_size=50,
).visualize())
# ## Optimization Parameters
# For our optimization, the relevant parameters are:
# - lr: learning rate for optimization
# - iter_n: number of iterations - transforms and regularizers are applied after each iteration
# - opt_n: number of optimization steps per iteration
#
# Image transformations and filters are only applied after each iteration. Apart from that, the parameters behave as in any optimization.
#
# In the following, we have a look at a few examples:
# In[11]:
import midnite
# use 'cpu' if no GPU available
with midnite.device('cuda:0'):
show(PixelActivation(
alexnet.features[:9],
SplitSelector(ChannelSplit(), [1]),
transform=RandomTransform()+BlurTransform()+ResizeTransform(),
regularization=[TVRegularization(), WeightDecay(decay_factor=3e-4)],
init_size=100,
lr=0.001, # default: 0.01
iter_n=5, # default: 12
opt_n=500, # default: 20
).visualize())
show(PixelActivation(
alexnet.features[:9],
SplitSelector(ChannelSplit(), [1]),
transform=RandomTransform()+BlurTransform()+ResizeTransform(scale_fac=1.05),
regularization=[TVRegularization(), WeightDecay(decay_factor=6e-5)],
init_size=25,
lr=0.1, # default: 0.01
iter_n=50, # default: 12
opt_n=10, # default: 20
).visualize())
# ## Neuron Selections for Optimizaiton
#
# Using an appropriate `NeuronSelector`, we can create an activaiton optimization for any selection neurons.
#
# ### Example 1: Single Neuron
# Note how some parts of the image do not have any influence on the gradient, since the convolutions have not yet progressed as far.
# In[12]:
show(PixelActivation(
alexnet.features[:11],
SplitSelector(NeuronSplit(), [0, 0, 0]),
transform=BlurTransform(),
regularization=[WeightDecay(decay_factor=1e-2)]
).visualize())
# ## Example 2: Class Visualization
# We can optimize for a target class to obtain an image of what the networks understand as that class. In this example, we do this on a GoogLeNet (due to the stronger visual semantics) for imagenet class 783 (Screw).
# In[13]:
from torch.nn import Sequential, Softmax
from plot_utils import show_normalized
googlenet = Sequential(models.googlenet(pretrained=True), Softmax(dim=1))
googlenet.eval()
with midnite.device('cuda:0'):
show_normalized(PixelActivation(
googlenet,
SplitSelector(NeuronSplit(), [783]),
transform=RandomTransform(scale_fac=0)+BilateralTransform()+ResizeTransform(1.005),
opt_n=10,
iter_n=300,
regularization=[WeightDecay(decay_factor=1.5e-7), TVRegularization(coefficient=0.05)],
init_size=300,
lr=0.007
).visualize(), scale=1.5)
|
Markdown
|
UTF-8
| 2,028
| 2.625
| 3
|
[] |
no_license
|
---
title: External Scripts
taxonomy:
category: docs
---
### External Scripts
**replication-manager** can automate route changes with popular proxies. however in some edge cases e.g. pacemaker or keepalived, logic like vip or hardware load balancer api calls can be managed through the external scripts option.
##### `failover-post-script` (2.0), `post-failover-script` (0.7)
| Item | Value |
| ---- | ----- |
| Description | Full path of a post-failover script. This is called after the new leader has been setup. The previous master host and the newly elected master host are passed as sequential arguments. |
| Type | string |
| Default Value | "" |
| Example | "/usr/local/bin/vip-up.sh" |`
Arguments passed to the script:
cluster.oldMaster.Host cluster.master.Host cluster.oldMaster.Port cluster.master.Port
##### `failover-pre-script` (2.0), `pre-failover-script` (0.7)
| Item | Value |
| ---- | ----- |
| Description | Full path of a pre-failover script. This is called after the new leader has been elected. The previous master host and the newly elected master host are passed as sequential arguments. |
| Type | string |
| Default Value | "" |
| Example | "/usr/local/bin/vip-down.sh" |
Arguments passed to the script:
cluster.oldMaster.Host cluster.master.Host cluster.oldMaster.Port cluster.master.Port
### External Proxy & Route
**replication-manager** can inject heartbeat into the route and check that the internal master is alway the one reach via the proxies or the route.
##### `extproxy` (2.0)
| Item | Value |
| ---- | ----- |
| Description | External proxy can be used to specify a route manage with external scripts setup. |
| Type | Boolean |
| Default Value | false|
##### `extproxy-address` (2.0)
| Item | Value |
| ---- | ----- |
| Description | Network address when route is manage via external script, host:[port] format. |
| Type | String |
| Default Value | ""|
|
Java
|
UTF-8
| 1,599
| 2.546875
| 3
|
[] |
no_license
|
package org.chronopolis.earth.domain;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
/**
*
* Created by shake on 9/28/16.
*/
@Entity
public class LastSync {
@Id
@GeneratedValue
private Long id;
@Enumerated(EnumType.STRING)
private SyncType type;
private String node;
private ZonedDateTime time;
public LastSync() {
// Need to pass in Instant (TemporalAccessor) + Zoned UTC
time = ZonedDateTime.from(Instant.EPOCH.atZone(ZoneOffset.UTC));
}
public Long getId() {
return id;
}
public LastSync setId(Long id) {
this.id = id;
return this;
}
public String getNode() {
return node;
}
public LastSync setNode(String node) {
this.node = node;
return this;
}
public SyncType getType() {
return type;
}
public LastSync setType(SyncType type) {
this.type = type;
return this;
}
public ZonedDateTime getTime() {
// ensure we always deal with UTC time
return time.withZoneSameInstant(ZoneOffset.UTC);
}
public LastSync setTime(ZonedDateTime time) {
this.time = time;
return this;
}
public String getFormattedTime() {
// TODO: TEST
return getTime().format(DateTimeFormatter.ISO_INSTANT);
}
}
|
Python
|
UTF-8
| 210
| 3.21875
| 3
|
[] |
no_license
|
from Point import Point
class Rectangle:
point1=None
point2=None
def __init__(self,p1,p2):
self.point1=p1
self.point2=p2
def __str__(self):
return "["+str(self.point1)+" - "+str(self.point2)+"]"
|
C
|
UTF-8
| 320
| 3.875
| 4
|
[] |
no_license
|
// Implement a program that converts degrees in Celsius to Fahrenheit
#include <stdio.h>
#include <cs50.h>
int main (void)
{
// Prompting user for a temperature in C
float C = get_float("C: ");
// Applying formula
float F = ((C * 9) / 5) + 32;
// Printing the result
printf("F: %.1f\n", F);
}
|
Java
|
UTF-8
| 11,351
| 2.03125
| 2
|
[] |
no_license
|
package com.dt.project.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dt.project.config.JsonData;
import com.dt.project.config.ResponseBase;
import com.dt.project.model.dto.UserDto;
import com.dt.project.exception.LsException;
import com.dt.project.mapper.UserMapper;
import com.dt.project.model.UserInfo;
import com.dt.project.model.UserRole;
import com.dt.project.netty.websocket.ChatType;
import com.dt.project.redis.RedisService;
import com.dt.project.service.*;
import com.dt.project.store.ChatStore;
import com.dt.project.store.SsoLoginStore;
import com.dt.project.toos.Constants;
import com.dt.project.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Date;
@Service
public class UserServiceImpl extends JsonData implements UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private HrArchivesEmployeeService hrService;
@Autowired
private ChatStore chatStore;
@Autowired
private UserRoleService userRoleService;
@Autowired
private RedisService redisService;
@Override
public String serviceGetName(Long uId) {
return userMapper.getName(uId);
}
@Override
public UserInfo getUserStatus(Long uid) {
String strRedis = redisService.getStringKey(Constants.USER_STATUS + uid);
JSONObject userJson = JSONObject.parseObject(strRedis);
UserInfo redisUser = JSON.toJavaObject(userJson, UserInfo.class);
if (redisUser == null) {
UserInfo user = userMapper.getUserStatus(uid);
if (uid != null) {
redisService.setString(Constants.USER_STATUS + uid, JSONObject.toJSONString(user));
return user;
}
}
return redisUser;
}
/**
* 用户认证
*
* @param response
* @param userDto
* @return
*/
@Override
@Transactional
public ResponseBase doGetAuthenticationInfo(HttpServletResponse response, UserDto userDto) {
//查询用户信息 更新更新登陆时间
UserInfo user = userMapper.findByUser(userDto.getUserName());
try {
// 账号不存在 异常
if (user == null) {
return JsonData.setResultError("未知账户/没找到帐号,登录失败");
}
if (user.getAccountStatus() == 1) {
return JsonData.setResultError("账号已被锁定,请联系管理员");
}
if (user.getDelOrNot() == 1) {
return JsonData.setResultError("账号凭着已过期/或删除 请联系管理员");
}
userMapper.upUserLandingTime(user.getUid(), new Date().getTime());
chatStore.kickOut(userDto.getUserName() + "token", user.getUid(),
JsonUtils.getJsonTypeError("有人登陆,你被踢下线,若不是本人,请修改密码",
ChatType.KICK_OUT));
String pwd = MD5Util.saltMd5(userDto.getUserName(), userDto.getPwd());
// 登陆校验
SsoLoginStore.login(user, pwd);
//设置token Cookie
JSONObject uJson = put(response, user, userDto.isRememberMe());
//登陆成功后 删除Redis指定数据
String errKey = Constants.ERROR_LOGIN + userDto.getUserName();
redisService.delKey(errKey);
return JsonData.setResultSuccess(uJson);
} catch (LsException ls) {
return setLockingTime(userDto);
}
}
private JSONObject put(HttpServletResponse response, UserInfo user, boolean ifRemember) {
long time;
if (ifRemember) {
time = 60 * 60 * 24 * 7L;
} else {
time = 30 * 60L;
}
//设置 JwtToken
String userToken = JwtUtils.genJsonWebToken(user);
JSONObject uJson = new JSONObject();
uJson.put("user", user);
uJson.put("token", userToken);
//设置token
redisService.setString(Constants.TOKEN + ":" + user.getUid(), userToken, time);
//设置Cookie
CookieUtil.set(response, Constants.TOKEN, userToken, ifRemember);
return uJson;
}
private ResponseBase setLockingTime(UserDto userDto) {
int errorNumber = 0;
errorNumber++;
int errorFre;
long lockingTime;
String errKey = Constants.ERROR_LOGIN + userDto.getUserName();
String redisErrorNumber = redisService.getStringKey(errKey);
//报错后 先进来看看 这个账号有没有在Redis里 ---如果里面有 进去
if (redisErrorNumber != null) {
errorFre = (Integer.parseInt(redisErrorNumber) + errorNumber);
redisService.setString(errKey, Integer.toString(errorFre));
} else {
//如果是null 只会走这里
redisService.setString(errKey, Integer.toString(errorNumber));
return JsonData.setResultError("账号或密码错误/你还有" + (4 - errorNumber + "次机会"));
}
if (errorFre >= 4) {
switch (errorFre) {
case 4:
lockingTime = (long) 5;
break;
case 5:
lockingTime = 5L * 5;
break;
case 6:
lockingTime = 10L * 5;
break;
case 7:
lockingTime = 15L * 5;
break;
default:
lockingTime = 60L * 60 * 24;
}
redisService.setString(Constants.TTL_DATE + userDto.getUserName(), "error", lockingTime);
return JsonData.setResultError("账号被锁定!" + lockingTime + "秒");
}
return JsonData.setResultError("账号或密码错误/你还有" + (4 - errorFre + "次机会"));
}
@Override
public List<UserInfo> findByUsers(UserDto pageDto) {
return userMapper.findByUsers(pageDto);
}
@Override
public UserInfo getSingleUser(Long id) {
return userMapper.getSingleUser(id);
}
@Override
public int delUserInfo(String uidIds) {
return userMapper.delUserInfo(uidIds);
}
@Override
public int reUserInfo(String uidIds) {
return userMapper.reUserInfo(uidIds);
}
@Override
public List<UserInfo> findByDelUserInfo() {
return userMapper.findByDelUserInfo();
}
@Override
public UserInfo getUserName(String userName) {
return userMapper.getUserName(userName);
}
@Override
public List<UserInfo> getByUsers() {
return userMapper.getByUsers();
}
@Override
public int upUserPwd(Long uid, String pwd) {
return userMapper.upUserPwd(uid, pwd);
}
/**
* 创建新增用户
*
* @param userMap
* @return
*/
@Override
@Transactional
@SuppressWarnings("unchecked")
public ResponseBase saveUserInfo(Map<String, Object> userMap) {
//获得登陆的时候 生成的token
String userName = (String) userMap.get("userName");
String pwd = (String) userMap.get("pwd");
Boolean checkedUpPwd = (Boolean) userMap.get("pwdAlways");
Boolean checkedUserAlways = (Boolean) userMap.get("uAlways");
Boolean checkedPwdAlways = (Boolean) userMap.get("pwdAlways");
Integer staffValue = (Integer) userMap.get("staffValue");
List<Integer> rolesId = (List<Integer>) userMap.get("rolesId");
//备注
String remark = (String) userMap.get("remark");
if (StringUtils.isBlank(userName) || StringUtils.isBlank(pwd) || checkedUpPwd == null
|| checkedUserAlways == null || checkedPwdAlways == null || staffValue == null || rolesId == null) {
return JsonData.setResultError("新增失败");
}
//这里前端会传空字符串 或者 Long类型数据 要判断
UserInfo userInfo = new UserInfo();
userInfo.setRemark(remark);
userInfo.setCreateDate(new Date().getTime());
userInfo.setCreateUser(ReqUtils.getUserName());
//首次登陆是否修改密码
if (checkedUpPwd) {
userInfo.setFirstLogin(true);
} else {
userInfo.setFirstLogin(false);
}
userInfo.setUserName(userName);
String md5Pwd = MD5Util.saltMd5(userName, pwd);
userInfo.setPwd(md5Pwd);
//如果点击了 用户始终有效
if (checkedUserAlways) {
userInfo.setUserExpirationDate(0L);
} else {
Long userExpirationDate = (Long) userMap.get("userExpirationDate");
//设置 用户有效时间
userInfo.setUserExpirationDate(userExpirationDate);
}
//如果点击了 密码始终有效
if (checkedPwdAlways) {
userInfo.setPwdValidityPeriod(0L);
} else {
//前台会传2个类型参数 根据判断转换 来设计 用户 密码有效时间
Integer pwdValidityPeriod = (Integer) userMap.get("pwdValidityPeriod");
userInfo.setPwdValidityPeriod(DateUtils.getRearDate(pwdValidityPeriod));
}
//新增用户
userMapper.saveUserInfo(userInfo);
Long uid = userInfo.getUid();
Long sid = staffValue.longValue();
//关联员工信息 更新
hrService.bindHrInfo(uid, sid);
//新增角色信息
List<UserRole> urList = new ArrayList<>();
UserRole userRole = new UserRole();
userRole.setUid(uid);
userRole.setRoleIds(rolesId);
urList.add(userRole);
userRoleService.addUserRole(urList);
return JsonData.setResultSuccess("新增成功");
}
/**
* 处理更新用户修改信息
*
* @param userMap
* @return
*/
@Override
@Transactional
public ResponseBase updateUserInfo(Map<String, Object> userMap) {
//更新用户信息
int updateResult = userMapper.upUser(userMap);
if (updateResult != 1) {
return JsonData.setResultError("更新失败,请重新操作");
}
String uMobilePhone = (String) userMap.get("mobilePhone");
if (StringUtils.isNotBlank(uMobilePhone)) {
//更新员工信息
hrService.upHrInfo(userMap);
}
//先判断是否为空
String pwd = (String) userMap.get("pwd");
//如果不是空 说明已经修改了密码
if (StringUtils.isNotBlank(pwd)) {
Integer uid = (Integer) userMap.get("uid");
String userName = (String) userMap.get("userName");
//踢出用户 如果是null 说明没有这个用户在线
chatStore.kickOut(userName + "token", uid.longValue(),
JsonUtils.getJsonTypeError("管理员修改密码,你被踢出",
ChatType.KICK_OUT));
}
return JsonData.setResultSuccess("更新成功");
}
}
|
Swift
|
UTF-8
| 2,178
| 3.375
| 3
|
[
"MIT"
] |
permissive
|
//
// DataTransformers.swift
//
//
// Created by Dick Verbunt on 29/12/15.
// Copyright © 2015 E-sites. All rights reserved.
//
import Foundation
/**
Protocol that should be used when writing your own DataTransformer.
*/
public protocol DataTransformer {
/**
Function used when reading from the characteristic.
Transform Data to the Value
*/
func transform(dataToValue data: Data?) -> MapValue
/**
Function used when writing to the characteristic.
Transform the Value to Data
*/
func transform(valueToData value: MapValue?) -> Data
}
/**
Default transformer from Data to Data and back.
*/
class DataDataTransformer: DataTransformer {
func transform(dataToValue data: Data?) -> MapValue {
return data ?? Data()
}
func transform(valueToData value: MapValue?) -> Data {
guard let value = value as? Data else {
return Data()
}
return value
}
}
/**
Default transformer from Data to String and back.
*/
class StringDataTransformer: DataTransformer {
func transform(dataToValue data: Data?) -> MapValue {
guard let data = data,
let string = String(data: data, encoding: String.Encoding.utf8) else {
return String()
}
return string
}
func transform(valueToData value: MapValue?) -> Data {
guard let value = value as? String,
let data = value.data(using: .utf8) else {
return Data()
}
return data
}
}
/**
UInt transformer from Data to String and back.
*/
class UIntDataTransformer<T:MapValue> : DataTransformer where T:UnsignedInteger {
func transform(dataToValue data: Data?) -> MapValue {
guard let data = data else {
return T()
}
var value = T()
(data as NSData).getBytes(&value, length: MemoryLayout<T>.size)
return value
}
func transform(valueToData value: MapValue?) -> Data {
guard var value = value as? T else {
return Data()
}
return Data(bytes: &value, count: MemoryLayout<UInt8>.size)
}
}
|
JavaScript
|
UTF-8
| 749
| 2.796875
| 3
|
[] |
no_license
|
let i =0;
let slider = document.querySelector('.showcase');
let images = [];
images[0] = '/resources/img/check2.jpg';
images[1] = '/resources/img/check.jpg';
images[2] = '/resources/img/China-online-education.jpg';
function changeImage(){
slider.style.background = `url(${images[i]}) no-repeat center center/cover`;
if(i < images.length-1){
i++
}else {
i=0;}
}
setInterval("changeImage()", 3000);
// js for navigation
function openNav() {
document.getElementById("myNav").style.width = "50%";
}
function closeNav() {
document.getElementById("myNav").style.width = "0";
}
// close navigation after clicking on the link
function closeOnSelect(){
document.getElementById("closeOnSelect").addEventListener('click', closeNav());
}
|
C
|
UTF-8
| 3,989
| 2.5625
| 3
|
[] |
no_license
|
/*
* \file
* Modbus RTU Master Implement Function 01, 03, 05, 06 Code
*
* \copyright
* Copyright (C) MOXA Inc. All rights reserved.
* This software is distributed under the terms of the
* MOXA License. See the file COPYING-MOXA for details.
*
* \date 2021/06/24
* First release
*
* \author
* Jerry YH Cheng
*/
/*****************************************************************************
* Include files
****************************************************************************/
#include "rtu_master.h"
/*****************************************************************************
* Public functions
****************************************************************************/
uint16_t crc_calc(uint8_t *data, int len)
{
int i;
uint32_t reg_crc = 0xFFFF;
while (len--)
{
reg_crc ^= *data++; /* XOR each bytes */
for (i = 0; i < 8; i++) /* Left shift each bits */
{
if (reg_crc & 0x01) /* LSB=1 */
{
reg_crc = (reg_crc >> 1) ^ 0xA001;
}
else
{
reg_crc = reg_crc >> 1;
}
}
}
return reg_crc;
}
void set_rtu_01_read_coils(uint8_t *rtu_frame, uint8_t slave_id, uint16_t reg_addr, uint16_t reg_num)
{
if (reg_num > 2000)
{
fprintf(stderr, "Out of range read amount\n");
return;
}
rtu_frame[R_W_SINGLE_FIELD_SLAVE_ID] = slave_id;
rtu_frame[R_W_SINGLE_FIELD_FUNCTION_CODE] = 0x01;
rtu_frame[R_W_SINGLE_FIELD_HI_REG_ADDR] = (reg_addr >> 8) & 0xff;
rtu_frame[R_W_SINGLE_FIELD_LO_REG_ADDR] = reg_addr & 0xff;
rtu_frame[R_W_SINGLE_FIELD_HI_REG_VAL] = (reg_num >> 8) & 0xff;
rtu_frame[R_W_SINGLE_FIELD_LO_REG_VAL] = reg_num & 0xff;
uint16_t crc_tmp = crc_calc(rtu_frame, R_W_SINGLE_CRC_LEN);
rtu_frame[R_W_SINGLE_FIELD_HI_CRC] = crc_tmp & 0xff;
rtu_frame[R_W_SINGLE_FIELD_LO_CRC] = (crc_tmp >> 8) & 0xff;
}
void set_rtu_03_read_holding_registers(uint8_t *rtu_frame, uint8_t slave_id, uint16_t reg_addr, uint16_t reg_num)
{
if (reg_num > 125)
{
fprintf(stderr, "Out of range read amount\n");
return;
}
rtu_frame[R_W_SINGLE_FIELD_SLAVE_ID] = slave_id;
rtu_frame[R_W_SINGLE_FIELD_FUNCTION_CODE] = 0x03;
rtu_frame[R_W_SINGLE_FIELD_HI_REG_ADDR] = (reg_addr >> 8) & 0xff;
rtu_frame[R_W_SINGLE_FIELD_LO_REG_ADDR] = reg_addr & 0xff;
rtu_frame[R_W_SINGLE_FIELD_HI_REG_VAL] = (reg_num >> 8) & 0xff;
rtu_frame[R_W_SINGLE_FIELD_LO_REG_VAL] = reg_num & 0xff;
uint16_t crc_tmp = crc_calc(rtu_frame, R_W_SINGLE_CRC_LEN);
rtu_frame[R_W_SINGLE_FIELD_HI_CRC] = crc_tmp & 0xff;
rtu_frame[R_W_SINGLE_FIELD_LO_CRC] = (crc_tmp >> 8) & 0xff;
}
void set_rtu_05_write_single_coil(uint8_t *rtu_frame, uint8_t slave_id, uint16_t reg_addr, uint16_t reg_val)
{
rtu_frame[R_W_SINGLE_FIELD_SLAVE_ID] = slave_id;
rtu_frame[R_W_SINGLE_FIELD_FUNCTION_CODE] = 0x05;
rtu_frame[R_W_SINGLE_FIELD_HI_REG_ADDR] = (reg_addr >> 8) & 0xff;
rtu_frame[R_W_SINGLE_FIELD_HI_REG_VAL] = reg_val ? 0xff : 0x00;
rtu_frame[R_W_SINGLE_FIELD_LO_REG_VAL] = 0x00;
uint16_t crc_tmp = crc_calc(rtu_frame, R_W_SINGLE_CRC_LEN);
rtu_frame[R_W_SINGLE_FIELD_HI_CRC] = crc_tmp & 0xff;
rtu_frame[R_W_SINGLE_FIELD_LO_CRC] = (crc_tmp >> 8) & 0xff;
}
void set_rtu_06_write_single_register(uint8_t *rtu_frame, uint8_t slave_id, uint16_t reg_addr, uint16_t reg_val)
{
rtu_frame[R_W_SINGLE_FIELD_SLAVE_ID] = slave_id;
rtu_frame[R_W_SINGLE_FIELD_FUNCTION_CODE] = 0x06;
rtu_frame[R_W_SINGLE_FIELD_HI_REG_ADDR] = (reg_addr >> 8) & 0xff;
rtu_frame[R_W_SINGLE_FIELD_LO_REG_ADDR] = reg_addr & 0xff;
rtu_frame[R_W_SINGLE_FIELD_HI_REG_VAL] = (reg_val >> 8) & 0xff;
rtu_frame[R_W_SINGLE_FIELD_LO_REG_VAL] = reg_val & 0xff;
uint16_t crc_tmp = crc_calc(rtu_frame, R_W_SINGLE_CRC_LEN);
rtu_frame[R_W_SINGLE_FIELD_HI_CRC] = crc_tmp & 0xff;
rtu_frame[R_W_SINGLE_FIELD_LO_CRC] = (crc_tmp >> 8) & 0xff;
}
|
Ruby
|
UTF-8
| 168
| 2.96875
| 3
|
[] |
no_license
|
n = gets.chomp.to_i
a = []
xNumber = 0
1.upto(Math.sqrt(n)) do |i|
if n % i == 0
a << i.to_s + (n/i).to_s
a << (n/i).to_s + i.to_s
end
end
p a.uniq.count
|
Java
|
UTF-8
| 143
| 2.234375
| 2
|
[] |
no_license
|
package model;
public interface Priority {
public String priority();
public void addScores(int i);
public String timeToStart();
}
|
Java
|
UTF-8
| 469
| 1.835938
| 2
|
[] |
no_license
|
package kr.co.jjjcamping.dao;
import java.util.ArrayList;
import kr.co.jjjcamping.dto.CartDto;
import kr.co.jjjcamping.dto.OrderDto;
import kr.co.jjjcamping.dto.ProductDto;
public interface OrderDao {
public ArrayList<CartDto> order_first(String userid);
public void order_second(OrderDto odto);
public String get_code();
public void cart_del(OrderDto odto);
public ArrayList<OrderDto> deliv_list(String userid);
public void deliv_add(OrderDto odto);
}
|
Ruby
|
UTF-8
| 3,865
| 2.5625
| 3
|
[
"Apache-2.0"
] |
permissive
|
#! /usr/bin/ruby
## -*- Mode: ruby -*-
require 'mysql' ;
require 'OpenGIS' ;
include OpenGIS ;
$dbName = 'test' ;
$tbName = 'foo' ;
$locMin = -10000 ;
$locMax = 10000 ;
$sizMin = 1 ;
$sizMax = 10 ;
$objN = 1000000 ;
#$mode = 'create' ;
#$mode = 'drop' ;
#$mode = 'insert' ;
#$mode = 'count' ;
$mode = 'select' ;
#$mode = 'list' ;
#$testP = TRUE ;
$testP = FALSE ;
##======================================================================
def randValue(min,max)
range = max - min ;
return range * rand() + min ;
end
def randPos(min,max)
return Point::new(randValue(min,max),randValue(min,max)) ;
end
##======================================================================
##======================================================================
class GeoRectObj
attr :name, true ;
attr :loc, true ;
attr :id, true ;
def initialize(name = "", loc = Rectangle::new)
set(name,loc) ;
end
def set(name,loc)
@name = name ;
@loc = loc ;
end
def colString()
return "(name,loc)" ;
end
def to_SQL()
return "('#{@name}',#{@loc.to_SQL()})" ;
end
end
def GeoRectObj::columnDefStr()
columnList = [
"id int auto_increment key",
"name varchar(128)",
"loc geometry not null"] ;
str = "" ;
columnList.each{|col|
str += "," if (str != "") ;
str += col ;
}
return "(" + str + ")" ;
end
def GeoRectObj::columnShowStr()
return "id,name,AsText(loc)" ;
end
##======================================================================
## test routine
##------------------------------
def testCreate()
qstr = ("create table #{$tbName} " + GeoRectObj::columnDefStr()) + ";";
p(qstr) if ($testP) ;
$db.query(qstr) if (!$testP) ;
qstr = ("create spatial index loc_index on #{$tbName} (loc);");
p(qstr);
$db.query(qstr) if (!$testP) ;
end
##------------------------------
def testDrop()
qstr = ("drop table #{$tbName};") ;
p(qstr);
$db.query(qstr) if (!$testP) ;
end
##------------------------------
def testInsert()
(0...$objN).each{|i|
rect = Rectangle::new() ;
rect.setByCenter(randPos($locMin,$locMax),randPos($sizMin,$sizMax)) ;
obj = GeoRectObj::new("bar-#{i}",rect) ;
qstr = ("insert delayed " +
"into #{$tbName} " +
"#{obj.colString()} values #{obj.to_SQL()}" +
";")
p(qstr) if ($testP) ;
$db.query(qstr) if (!$testP) ;
}
end
##------------------------------
def testCount()
rect = Rectangle::new() ;
rect.setByCenter(Point::new(0,0),Point::new(100,100)) ;
qstr = ("select count(*) " +
"from #{$tbName} " +
"where MBRIntersects(loc,#{rect.to_SQL})" +
";");
p(qstr) ;
if(!$testP) then
result = $db.query(qstr) if (!$testP) ;
result.each(){|x|
p(x) ;
}
end
end
##------------------------------
def testSelect()
rect = Rectangle::new() ;
rect.setByCenter(Point::new(0,0),Point::new(100,100)) ;
qstr = ("select #{GeoRectObj::columnShowStr()} " +
"from #{$tbName} " +
"where MBRIntersects(loc,#{rect.to_SQL})" +
";");
p(qstr);
if(!$testP) then
result = $db.query(qstr) if (!$testP) ;
result.each(){|x|
p(x) ;
}
end
end
##------------------------------
def testList()
tbList = $db.list_tables() ;
p(tbList);
end
##======================================================================
## MAIN
$db = Mysql::new('localhost',nil,nil) ;
dbList = $db.list_dbs() ;
$db.select_db($dbName) ;
sTime = Time::now() ;
case($mode)
when 'create'
testCreate() ;
when 'drop'
testDrop() ;
when 'insert'
testInsert() ;
when 'count'
testCount() ;
when 'select'
testSelect() ;
when 'list'
testList() ;
end
eTime = Time::now() ;
spentTime = eTime - sTime ;
$stdout << "info:" << $db.info() << "\n" ;
$stdout << "stat:" << $db.stat() << "\n" ;
$stdout << "#{$mode} takes #{spentTime} sec.\n" ;
$db.close() ;
|
C#
|
UTF-8
| 35,471
| 3.015625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Runtime.Remoting.Messaging;
namespace CodeWarsSolutions
{
public abstract class Task
{
#region https://www.codewars.com/kata/5592e3bd57b64d00f3000047/train/csharp
public static long FindNb(long m)
{
long sum = 0;
long i = 1;
long above = 0;
while (sum < m)
{
i++;
sum = 0;
above += (long)Math.Pow(i - 1, 3);
sum = above + (long)Math.Pow(i, 3);
}
return sum == m
? i
: -1;
}
#endregion
#region https://www.codewars.com/kata/59c01248bf10a47bd1000046/
public static string validator(string password)
{
if(password.Length<3 || password.Length > 20)
{
return "INVALID";
}
var isValid = password.All(i => Char.IsLetterOrDigit(i));
if (isValid)
{
return (password.Where(i => char.IsLetter(i)).Count() > 0 && password.Where(i => char.IsNumber(i)).Count() > 0) ? "VALID" : "INVALID";
}
return "INVALID";
}
#endregion
#region https://www.codewars.com/kata/554ca54ffa7d91b236000023/
public static int CountBits(int n) => Convert.ToString(n,2).Where(i => i == '1').Count();
#endregion
#region https://www.codewars.com/kata/514b92a657cdc65150000006/
public static int Solution(int value)
{
int sum = 0;
for (int i = 3; i < value; i++)
{
if (i % 3 == 0 && i % 5 == 0)
{
sum += i;
}
else
{
if (i % 3 == 0)
{
sum += i;
}
if (i % 5 == 0)
{
sum += i;
}
}
}
return sum;
////LINQ (not mine)
//return Enumerable.Range(0, value)
// .Where(x => x % 3 == 0 || x % 5 == 0)
// .Sum();
}
#endregion
#region https://www.codewars.com/kata/51f2d1cafc9c0f745c00037d/
public static bool Solution(string str, string ending)
{
//if (str.Length < ending.Length) { return false; }
//int index = 0;
//for (int i = str.Length - ending.Length; i < str.Length; i++)
//{
// char first = str[i];
// char second = ending[index];
// index++;
// if (first != second)
// {
// return false;
// }
//}
//return true;
//with string internal methods;
return str.Length < ending.Length ? false : str.Substring(str.Length - ending.Length).Contains(ending);
}
#endregion
#region https://www.codewars.com/kata/54bf1c2cd5b56cc47f0007a1/
public static int DuplicateCount(string str)=> str.ToLower().GroupBy(g => g).Where(s => s.Count() > 1).Select(s => s).Count();
#endregion
#region https://www.codewars.com/kata/5679aa472b8f57fb8c000047
public delegate int SideSum(int[] array, int startIndex, int lastIndex);
public static int FindEvenIndex(int[] arr)
{
SideSum sideSum = (a, sIndex, lIndex) =>
{
int sum = 0;
for (int i = sIndex; i < lIndex; i++)
{
sum += a[i];
}
return sum;
};
for (int i = 0; i < arr.Length; i++)
{
int left = i == 0 ? 0 : sideSum(arr, 0, i);
int startWith = i + 1 > arr.Length ? arr.Length : i + 1;
int right = sideSum(arr, startWith, arr.Length);
if (left == right)
{
return i;
}
}
return -1;
}
#endregion
#region https://www.codewars.com/kata/576757b1df89ecf5bd00073b/
public static String LongestConsec(string[] strarr, int k)
{
if (strarr.Length == 0 || k <= 0)
{
return string.Empty;
}
if (k == 1)
{
return strarr.OrderBy(o => o.Length).Last();
}
List<string> strings = new List<string>();
for (int i=0; i < strarr.Length+1 / k; i++)
{
strings.Add($"{strarr[i]}{strarr[i + 1]}");
}
return strings.OrderBy(o => o.Length).Last();
}
#endregion
#region https://www.codewars.com/kata/57eb8fcdf670e99d9b000272
public static string High(string s)
{
var splited = s.Split(' ');
var list = new List<int>();
foreach(var i in splited)
{
list.Add(LetterToInt(i));
}
return splited[list.IndexOf(list.Max())];
//Some bright guy did in the way i wanted to do...
//return s.Split(' ').OrderBy(a => a.Select(b => b - 96).Sum()).Last();
}
private static int LetterToInt(string s)
{
return s.Select(i => ((int)i-96)).Sum();
}
#endregion
#region https://www.codewars.com/kata/52597aa56021e91c93000cb0
public static int[] MoveZeroes(int[] arr)
{
var zeroes = arr.Where(i => i == 0).ToArray();
var notZeroes = arr.Where(i => i != 0).ToArray();
var rightSequance = new List<int>();
rightSequance.AddRange(notZeroes);
rightSequance.AddRange(zeroes);
return rightSequance.ToArray();
}
#endregion
#region https://www.codewars.com/kata/541c8630095125aba6000c00/
public static int DigitalRoot(long n)
{
int result=0;
string strN = n.ToString();
while (strN.Length != 1)
{
result = 0;
for(int i=0; i < strN.Length; i++)
{
result +=int.Parse(strN[i].ToString());
}
strN = result.ToString();
}
return result;
}
public static int DigitalRoot(long n, string s) => (int) (1 + (n - 1) % 9);
#endregion https://www.codewars.com/kata/541c8630095125aba6000c00/
#region https://www.codewars.com/kata/520b9d2ad5c005041100000f/
public static string PigIt(string str)
{
var arr = str.Split(' ');
List<string> newArr = new List<string>();
foreach (var el in arr)
{
var temp = el[0];
newArr.Add($"{el.Remove(0, 1)}{temp}ay");
}
return string.Join(" ", newArr);
//with Linq
//return string.Join(" ", str.Split().Select(i => i.Substring(1) + i[0] + "ay"));
}
#endregion https://www.codewars.com/kata/520b9d2ad5c005041100000f/
#region https://www.codewars.com/kata/54da539698b8a2ad76000228/
public static bool IsValidWalk(string[] walk)
{
int countWest = 0;
int countNorth = 0;
int countSouth = 0;
int countEast = 0;
foreach (var w in walk)
{
switch (w)
{
case "n":
{
countNorth++;
break;
}
case "s":
{
countSouth++;
break;
}
case "w":
{
countWest++;
break;
}
case "e":
{
countEast++;
break;
}
}
}
bool isPoint = countNorth == countSouth && countWest == countEast;
bool isTakenTen = countWest + countNorth + countSouth + countEast == 10;
return isPoint && isTakenTen ? true : false;
}
#endregion
#region https://www.codewars.com/kata/54d512e62a5e54c96200019e/
public static String Factors(int lst)
{
int divider = 2;
int count = 0;
List<string> chars = new List<string>();
while (lst != 1)
{
if (lst % divider == 0)
{
lst /= divider;
count++;
chars.Add(divider.ToString());
}
else
{
divider++;
}
}
return string.Join("*", chars);
}
#endregion
#region https://www.codewars.com/kata/523f5d21c841566fde000009/
public static int[] ArrayDiff(int[] a, int[] b)
{
var aList = a.ToList();
foreach (var el in b)
{
if (aList.Contains(el))
{
aList.RemoveAll(i => { return i == el; });
}
}
foreach (var i in aList)
{
Console.WriteLine(i);
}
return aList.ToArray();
}
#endregion
#region https://www.codewars.com/kata/530e15517bc88ac656000716/
public static string Rot13(string message)
{
string result = "";
foreach (var ch in message)
{
result += GetRotetedCharacter(ch);
}
return result;
}
public static char GetRotetedCharacter(char character)
{
char[] alhabet =
{
'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z'
};
alhabet = Char.IsUpper(character)
? alhabet.Select(c => char.ToUpper(c)).ToArray()
: alhabet;
for (int i = 0; i < alhabet.Length; i++)
{
//try
//{
if (alhabet[i] == character)
{
int temp = i + 13;
int index = 0;
if (temp >= alhabet.Length)
{
index = temp - 26;
return alhabet[index];
}
return alhabet[temp];
}
//}
//catch (IndexOutOfRangeException)
//{
// return Char.IsUpper(character) ? 'A' : 'a';
//}
}
return character;
}
#endregion
#region https://www.codewars.com/kata/5842df8ccbd22792a4000245/
public static string ExpandForm(long num)
{
string numStr = num.ToString();
List<string> list = new List<string>();
for (int i = 0; i < numStr.Length; i++)
{
if (numStr[i] != '0')
{
if ((numStr.Length - i) < 2)
{
list.Add($"{numStr[i]}");
return string.Join(" + ", list);
}
string toAdd = $"{numStr[i]}" + new string('0', numStr.Length - i - 1);
list.Add(toAdd);
}
}
return string.Join(" + ", list);
}
#endregion
#region https://www.codewars.com/kata/546e2562b03326a88e000020/
public static int SquareDigits(int n)
{
string nStr = n.ToString();
string toReturn = "";
foreach (var number in nStr)
{
double temp = double.Parse(number.ToString());
toReturn += $"{Math.Pow(temp, 2)}";
}
return int.Parse(toReturn);
//via linq
return int.Parse(string.Join("", n.ToString().Select(i => Math.Pow(double.Parse(i.ToString()), 2))));
}
#endregion
#region https://www.codewars.com/kata/5583d268479559400d000064/
public static string BinaryToString(string binary)
{
var bites = new List<string>();
string temp = binary;
for (int i = 0; i < binary.Length / 8; i++)
{
bites.Add(temp.Substring(0, 8));
temp = temp.Remove(0, 8);
}
return string.Join("", bites.Select(x => (char)BinaryToDecimal(x)));
}
static int BinaryToDecimal(string binary)
{
int i = 0;
var toDecimal = binary.Select(
x => x == '1' ? Math.Pow(2, (binary.Length - 1) - i++)
: Math.Pow(0, i++)).Sum() - 1;
return (int)toDecimal;
}
#endregion
#region https://www.codewars.com/kata/54da5a58ea159efa38000836/
public static int find_it(int[] seq)
{
return int.Parse(string.Join("", seq.GroupBy(g => g).Where(g => g.Count() % 2 != 0).Select(g => g.Key)));
}
#endregion
#region https://www.codewars.com/kata/5208f99aee097e6552000148/
public static string BreakCamelCase(string str)
{
var res = str.ToCharArray().Select(x => char.IsUpper(x) ? " " + x : "" + x).ToList();
return string.Join("", res);
}
#endregion
#region https://www.codewars.com/kata/576bb3c4b1abc497ec000065/
public static bool Compare(string s1, string s2)
{
try
{
var str1 = s1.Where(i => !Char.IsLetter(i)).ToArray();
var str2 = s2.Where(i => !Char.IsLetter(i)).ToArray();
var sum1 = str1.Length >= 1 ? 0 : s1.ToUpper().Select(i => i.GetHashCode()).Sum();
var sum2 = str2.Length >= 1 ? 0 : s2.ToUpper().Select(i => i.GetHashCode()).Sum();
return sum1 == sum2;
}
catch (Exception) { return true; }
}
#endregion
#region https://www.codewars.com/kata/5853213063adbd1b9b0000be/
public string[] StreetFighterSelection(string[][] fighters, int[] position, string[] moves)
{
List<string> selectedFighters = new List<string>();
foreach (var move in moves)
{
switch (move)
{
case "up":
{
position[0] = 0;
break;
}
case "right":
{
position[1] = position[1] == 5 ? 0 : position[1] + 1;
break;
}
case "down":
{
position[0] = 1;
break;
}
case "left":
{
position[1] = position[1] == 0 ? 5 : position[1] - 1;
break;
}
}
int i = position[0];
int j = position[1];
selectedFighters.Add(fighters[i][j]);
}
return selectedFighters.ToArray();
}
#endregion
#region https://www.codewars.com/kata/550498447451fbbd7600041c/
public static bool comp(int[] a, int[] b)
{
try
{
if (a.Length != b.Length) { return false; }
else if (a.Length == 0 || b.Length == 0) { return true; }
int count = 0;
var c = a.Select(i => i * i).OrderBy(i => i).ToArray();
b = b.OrderBy(i => i).ToArray();
for (int i = 0; i < b.Length; i++)
{
count = c[i] == b[i] ? count += 1 : count;
}
return count == b.Length;
}
catch (Exception e) { return false; }
}
#endregion
#region https://www.codewars.com/kata/5287e858c6b5a9678200083c/
public static bool Narcissistic(int value)
{
string temp = value.ToString();
int result = 0;
foreach (char c in temp)
{
result += (int)Math.Pow(int.Parse(c.ToString()), temp.Length);
}
return result == value;
}
#endregion
#region https://www.codewars.com/kata/513e08acc600c94f01000001/
public static string Rgb(int r, int g, int b)
{
r = r < 0 ? 0 : r > 255 ? 255 : r;
g = g < 0 ? 0 : g > 255 ? 255 : g;
b = b < 0 ? 0 : b > 255 ? 255 : b;
string rStr = r < 15 && r > 0 ? "0" : null;
rStr += ToHex(r, r == 0 ? "00" : null);
string gStr = g < 15 && g > 0 ? "0" : null;
gStr += ToHex(g, g == 0 ? "00" : null);
string bStr = b < 15 && b > 0 ? "0" : null;
bStr += ToHex(b, b == 0 ? "00" : null);
return string.Join("", rStr, gStr, bStr);
}
public static string ToHex(int value, string hex = null)
{
if (value <= 0 && hex != null)
{
return string.Join("", hex.Reverse());
}
int divided = value / 16;
int remainder = value % 16;
switch (remainder)
{
case 10:
{
hex += 'A';
break;
}
case 11:
{
hex += 'B';
break;
}
case 12:
{
hex += 'C';
break;
}
case 13:
{
hex += 'D';
break;
}
case 14:
{
hex += 'E';
break;
}
case 15:
{
hex += 'F';
break;
}
default:
{
hex += remainder;
break;
}
}
return ToHex(divided, hex);
}
#endregion
#region https://www.codewars.com/kata/596fba44963025c878000039/
public static string Contamination(string text, string character)
{
return text.Length >= 0 || character.Length >= 0 ? string.Join("", text.Select(x => character)) : string.Empty;
}
#endregion
#region https://www.codewars.com/kata/55908aad6620c066bc00002a/
public static bool XO(string input)
{
var x = input.ToLower().Where(i => i == 'x').Count();
var o = input.ToLower().Where(i => i == 'o').Count();
return x == o;
}
#endregion
#region https://www.codewars.com/kata/54df2067ecaa226eca000229/
public static long? RangeSum(long n)
{
if (n <= 0)
{
return null;
}
return (n * (n + 1) / 2);
}
#endregion
#region https://www.codewars.com/kata/57f609022f4d534f05000024/
public static int Stray(int[] numbers)
{
for (int i = 0; i < numbers.Length; i++)
{
int temp = numbers[i];
if (temp != numbers[0] && temp != numbers[1])
{
return temp;
}
}
return numbers[0];
}
#endregion
#region https://www.codewars.com/kata/54d512e62a5e54c96200019e/
//public static String Factors(int lst)
//{
// int divider = 2;
// int count = 0;
// List<string> chars = new List<string>();
// while (lst != 1)
// {
// if (lst % divider == 0)
// {
// lst /= divider;
// count++;
// chars.Add(divider.ToString());
// }
// else
// {
// divider++;
// }
// }
// return string.Join("*", chars);
//}
#endregion
#region https://www.codewars.com/kata/5526fc09a1bbd946250002dc/
public static int Find(int[] integers)
{
var odd = integers.Where(i => i % 2 == 0).ToArray();
var even = integers.Where(i => i % 2 != 0).ToArray();
return odd.Length > even.Length ? even[0] : odd[0];
}
#endregion
#region https://www.codewars.com/kata/56b5afb4ed1f6d5fb0000991/
public static string RevRot(string strng, int sz)
{
Console.WriteLine($"{strng}, {sz}");
List<string> list = new List<string>();
int length = strng.Length;
string output = "";
if (sz <= 0 || sz > strng.Length) { return ""; }
while (length != 0 && length >= sz)
{
string temp = strng.Substring(0, sz);
list.Add(temp);
strng = strng.Remove(0, sz);
length -= sz;
}
for (int i = 0; i < list.Count; i++)
{
var temp2 = list[i];
int sum = 0;
foreach (var el in temp2)
{
sum += (int)Math.Pow((int)el - 48, 3);
}
if (sum % 2 == 0)
{
char[] arr = temp2.ToCharArray();
Array.Reverse(arr);
output += new string(arr);
}
else
{
char temp3 = temp2[0];
output += $"{temp2.Remove(0, 1)}{temp3}";
}
}
return output.ToString();
}
#endregion
#region https://www.codewars.com/kata/52c31f8e6605bcc646000082/
public static int[] TwoSum(int[] numbers, int target)
{
List<int> list = new List<int>();
for (int i = 0; i < numbers.Length; i++)
{
int temp;
for (int j = i + 1; j < numbers.Length; j++)
{
temp = numbers[i] + numbers[j];
if (temp == target)
{
list.Add(i);
list.Add(j);
break;
}
}
}
return list.ToArray();
}
#endregion
#region https://www.codewars.com/kata/52efefcbcdf57161d4000091/
public static Dictionary<char, int> Count(string str)
{
Dictionary<char, int> list = new Dictionary<char, int>();
char temp = ' ';
int count = 0;
var sortedStr = str.OrderBy(s => s).ToArray();
for (int i = 0; i < sortedStr.Length; i += count)
{
temp = sortedStr[i];
count = 0;
for (int j = 0; j < sortedStr.Length; j++)
{
if (sortedStr[i] == sortedStr[j])
{
count++;
}
}
list.Add(temp, count);
}
return list;
}
#endregion
#region https://www.codewars.com/kata/56606694ec01347ce800001b/
public static bool IsTriangle(int a, int b, int c)
{
return a > 0 && b > 0 &&
a + b > c && a + c > b && b + c > a ?
true : false;
}
#endregion
#region https://www.codewars.com/kata/545cedaa9943f7fe7b000048/
public static bool IsPangram(string str)
{
char[] alphabet =
{
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'
};
if (str.Length >= 26)
{
str = str.ToLower();
int count = 0;
for (int i = 0; i < alphabet.Length; i++)
{
for (int j = 0; j < str.Length; j++)
{
if (alphabet[i] == str[j])
{
Console.WriteLine($"letters : {alphabet[i]} and {str[j]} are the same!");
count++;
Console.WriteLine(count);
break;
}
}
}
return count >= 26 ? true : false;
}
else
{
return false;
}
}
#endregion
#region https://www.codewars.com/kata/57a0556c7cb1f31ab3000ad7/
public static string MakeUpperCase(string str)
{
return str.ToUpper();
}
#endregion
#region https://www.codewars.com/kata/55eca815d0d20962e1000106/
public static int[] GenerateRange(int min, int max, int step)
{
List<int> arr = new List<int>();
for (; min <= max; min += step)
{
arr.Add(min);
}
return arr.ToArray();
}
#endregion
#region https://www.codewars.com/kata/5264d2b162488dc400000001
public static string SpinWords(string sentence)
{
var words = sentence.Split(' ');
string result = null;
for (int i = 0; i < words.Length; i++)
{
char[] temp = words[i].ToCharArray();
if (temp.Length >= 5)
{
Array.Reverse(temp);
result += new string(temp);
}
else
{
result += new string(temp);
}
result += " ";
}
result = result.Remove(result.LastIndexOf(" "), 1);
return result;
}
#endregion
#region https://www.codewars.com/kata/5388f0e00b24c5635e000fc6/
public class Swapper
{
public object[] Arguments { get; private set; }
public Swapper(object[] args)
{
Arguments = args;
}
public void SwapValues()
{
object temp = Arguments[0];
Arguments[0] = Arguments[1];
Arguments[1] = temp;
}
}
#endregion
#region https://www.codewars.com/kata/5772da22b89313a4d50012f7/
public static string Greet(string name, string owner)
{
if (name.Length != owner.Length) { return "Hello guest"; }
else
{
int count = 0;
for (int i = 0; i < name.Length; i++)
{
if (name[i] == owner[i])
{
count++;
}
}
if (count == name.Length) { return "Hello boss"; }
}
return "Hello guest";
}
#endregion
#region https://www.codewars.com/kata/5949481f86420f59480000e7/
public static string OddOrEven(int[] array)
{
int sum = 0;
string odd = "odd";
string even = "even";
if (array.Length < 1)
{
return even;
}
foreach (var i in array)
{
sum += i;
}
Console.WriteLine(sum);
if (sum % 2 == 0)
{
return even;
}
else { return odd; }
}
#endregion
#region https://www.codewars.com/kata/5839edaa6754d6fec10000a2/
public static char FindMissingLetter(char[] array)
{
char result = ' ';
int temp = Convert.ToInt32(array[0]);
for (int i = 1; i < array.Length; i++)
{
int temp1 = Convert.ToInt32(array[i]);
Console.WriteLine($"temp: {temp}\ntemp1: {temp1}");
int diff = temp1 - temp;
Console.WriteLine($"Difference between them: {diff}");
if (diff == 1)
{
temp = temp1;
Console.WriteLine("THERE ARE NO DIFFERENCE!");
}
else
{
result = Convert.ToChar(temp + 1);
Console.WriteLine("THERE ARE DIFFERENCE!");
}
}
return result;
}
#endregion
#region https://www.codewars.com/kata/5626b561280a42ecc50000d1/
public class SumDigPower
{
public static long[] SumDigPow(long a, long b)
{
List<long> longs = new List<long>();
for (long i = a; i < b; i++) //every step we'll send some value [a...b] into method IsEureka, if we have true, we'll add this value to massive
{
if (IsEureka(i))
{
longs.Add(i);
}
}
return longs.ToArray();
}
public static bool IsEureka(long x)
{
string strX = Convert.ToString(x);
long sum = 0;
long temp = 0;
for (int i = 0; i < strX.Length; i++)
{
temp = Convert.ToInt64(strX[i]) - 48;
sum += (int)Math.Pow((temp), (i + 1));
}
if (x == sum)
{
return true;
}
else
{
return false;
}
}
}
#endregion
#region https://www.codewars.com/kata/55685cd7ad70877c23000102/
public static int MakeNegative(int number)
{
return Math.Abs(number) * -1;
}
#endregion
#region https://www.codewars.com/kata/55c45be3b2079eccff00010f/
public static string Order(string words)
{
string finalString = "";
string stringTemp = "";
int intTemp = 0;
List<string> strings = new List<string>();
strings.AddRange(words.Split(' '));
List<int> numb = new List<int>();
for (int i = 0; i < strings.Count; i++)
{
string temp = strings[i];
for (int j = 0; j < temp.Length; j++)
{
if (Char.IsNumber(temp[j]))
{
numb.Add(temp[j]);
}
}
}
for (int i = 0; i < numb.Count; i++)
{
for (int j = i + 1; j < numb.Count; j++)
{
if (numb[i] > numb[j])
{
intTemp = numb[i];
stringTemp = strings[i];
strings[i] = strings[j];
numb[i] = numb[j];
strings[j] = stringTemp;
numb[j] = intTemp;
}
}
}
for (int i = 0; i < strings.Count - 1; i++)
{
finalString += $"{strings[i]} ";
}
return finalString += $"{strings[strings.Count - 1]}";
}
#endregion
#region https://www.codewars.com/kata/59752e1f064d1261cb0000ec/
public static string WhatTimeIsIt(double angle)
{
if (angle < 30)
{
angle += angle;
angle = (int)angle;
if (angle <= 9)
{
return $"12:0{angle}";
}
return $"12:{angle}";
}
int min = 0;
int hour = 0;
double angle1 = angle;
string result = "";
angle += angle;
hour = (int)angle / 60;
bool hourIsExist = hour > 0;
if (hour <= 9)
{
result = $"0{hour}:";
}
else
{
result = $"{hour}:";
}
if (hourIsExist)
{
min = (int)angle - (60 * hour);
if (min <= 9)
{
result += $"0{min}";
}
else
result += $"{min}";
}
else
{
min = (int)angle;
result += $"{min}";
}
return result;
}
#endregion
#region https://www.codewars.com/kata/54e6533c92449cc251001667/
public static IEnumerable<T> UniqueInOrder<T>(IEnumerable<T> iterable)
{
T previous = default(T);
foreach (T current in iterable)
{
if (!current.Equals(previous))
{
previous = current;
yield return current;
}
}
}
#endregion
#region https://www.codewars.com/kata/5544c7a5cb454edb3c000047/
public static int bouncingBall(double h, double bounce, double window)
{
int count = 0;
if (h > 0 && bounce > 0 && bounce < 1 && h > window)
{
while (h >= window)
{
count++;
h *= bounce;
if (h > window)
{
count++;
}
}
if (count == 2) { return 1; }
else
{
return count;
}
}
else { return -1; }
}
#endregion
}
}
|
Python
|
UTF-8
| 4,452
| 2.71875
| 3
|
[] |
no_license
|
import sys
import pandas as pd
import numpy as np
import utils
def train_of_classificator(training_data, m_norma):
w1 = np.array([[0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0]])
w2 = np.array([[0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0]])
w3 = np.array([[0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0]])
w4 = np.array([[0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0]])
b1 = 0.0
b2 = 0.0
b3 = 0.0
b4 = 0.0
learning_rate = 0.01
Hat = utils.Sorting_Hat(10, 1)
for epoch in range(3):
for index, row in training_data.iterrows():
fit1 = (row['Herbology'] - training_data['Herbology'].mean()) / training_data['Herbology'].std()
fit2 = (row['Muggle Studies'] - training_data['Muggle Studies'].mean()) / training_data['Muggle Studies'].std()
fit3 = (row['Charms'] - training_data['Charms'].mean()) / training_data['Charms'].std()
fit4 = (row['Divination'] - training_data['Divination'].mean()) / training_data['Divination'].std()
fit5 = (row['Defense Against the Dark Arts'] - training_data['Defense Against the Dark Arts'].mean()) / training_data[
'Defense Against the Dark Arts'].std()
fit6 = (row['Ancient Runes'] - training_data['Ancient Runes'].mean()) / training_data['Ancient Runes'].std()
fit7 = (row['History of Magic'] - training_data['History of Magic'].mean()) / training_data['History of Magic'].std()
fit8 = (row['Flying'] - training_data['Flying'].mean()) / training_data['Flying'].std()
fit9 = (row['Transfiguration'] - training_data['Transfiguration'].mean()) / training_data['Transfiguration'].std()
fit10 = (row['Potions'] - training_data['Potions'].mean()) / training_data['Potions'].std()
if row['Hogwarts House'] == 'Ravenclaw':
x1 = []
t = 1
x1 = [fit1, fit2, fit3, fit4, fit5, fit6, fit7, fit8, fit9, fit10]
x1 = np.array(x1)
Yhat = Hat(x1, w1, b1)
delta = Yhat - t
x1 = x1.reshape(1, -1)
w1 = w1 - learning_rate * (x1.T.dot(delta)) / m_norma
b1 = b1 - learning_rate * (delta) / m_norma
if row['Hogwarts House'] == 'Gryffindor':
x2 = []
t = 1
x2 = [fit1, fit2, fit3, fit4, fit5, fit6, fit7, fit8, fit9, fit10]
x2 = np.array(x2)
Yhat = Hat(x2, w2, b2)
delta = Yhat - t
x2 = x2.reshape(1, -1)
w2 = w2 - learning_rate * (x2.T.dot(delta)) / m_norma
b2 = b2 - learning_rate * (delta) / m_norma
if row['Hogwarts House'] == 'Slytherin':
x3 = []
t = 1
x3 = [fit1, fit2, fit3, fit4, fit5, fit6, fit7, fit8, fit9, fit10]
x3 = np.array(x3)
Yhat = Hat(x3, w3, b3)
delta = Yhat - t
x3 = x3.reshape(1, -1)
w3 = w3 - learning_rate * (x3.T.dot(delta)) / m_norma
b3 = b3 - learning_rate * (delta) / m_norma
if row['Hogwarts House'] == 'Hufflepuff':
x4 = []
t = 1
x4 = [fit1, fit2, fit3, fit4, fit5, fit6, fit7, fit8, fit9, fit10]
x4 = np.array(x4)
Yhat = Hat(x4, w4, b4)
delta = Yhat - t
x4 = x4.reshape(1, -1)
w4 = w4 - learning_rate * (x4.T.dot(delta)) / m_norma
b4 = b4 - learning_rate * (delta) / m_norma
with open('weights_for_prediction.csv', 'w') as file:
file.write('Weights,bias\n')
file.write(str(w1.T).replace('\n','').strip('[]') + ',' + str(b1).strip('[]') + '\n')
file.write(str(w2.T).replace('\n','').strip('[]') + ',' + str(b2).strip('[]') + '\n')
file.write(str(w3.T).replace('\n','').strip('[]') + ',' + str(b3).strip('[]') + '\n')
file.write(str(w4.T).replace('\n','').strip('[]') + ',' + str(b4).strip('[]') + '\n')
try:
data_to_train = pd.read_csv(sys.argv[1])
data_to_train2 = data_to_train
data_to_train = data_to_train.dropna()
train_of_classificator(data_to_train, len(data_to_train.index))
except:
print('There is no data! Try once again with data')
|
PHP
|
UTF-8
| 704
| 2.6875
| 3
|
[
"Apache-2.0"
] |
permissive
|
<?php declare(strict_types=1);
// Load composer autoload
require __DIR__ . "/../vendor/autoload.php";
// Use classes
use App\Bot;
// Initialize dotenv
if (file_exists(__DIR__ . "/../.env")) {
// Check if a .env file is in the root directory
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . "/..");
} elseif (file_exists(__DIR__ . "/.env")) {
// Otherwise, in this directory
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
} else {
die("Environment variables is not found. Verify your .env file\n");
}
// Load dotenv
$dotenv->load();
// Initialize the bot
$bot = new Bot();
// Set output path
$bot->setOutputPath(__DIR__ . "/../storage/data/");
// Run the bot
$bot->run();
|
Rust
|
UTF-8
| 507
| 3.125
| 3
|
[] |
no_license
|
pub fn solve() {
let c1 = (273025_u32 .. 767253).filter(|&x| is_ok_password(x)).count();
println!("Day 04, part 1: {} ", c1);
}
fn is_ok_password(number : u32) -> bool {
let mut has_repeated_digits = false;
let mut n = number;
loop {
let last_digit = n % 10;
n = n / 10;
if n == 0 || n % 10 > last_digit {
break;
}
if n % 10 == last_digit {
has_repeated_digits = true;
}
}
n == 0 && has_repeated_digits
}
|
JavaScript
|
UTF-8
| 2,411
| 2.578125
| 3
|
[] |
no_license
|
const express = require('express');
const router = express.Router();
// User Model
let User = require('../models/user');
//Admin Model
let Admin = require('../models/admin');
// Add Route
router.get('/add', ensureAuthenticated, function(req, res){
res.render('add_user', {
title:'Add User'
});
});
// Add Submit POST Route
router.post('/add', ensureAuthenticated,function(req, res){
req.checkBody('name','Name is required').notEmpty();
req.checkBody('email','Email is required').notEmpty();
req.checkBody('password','password is required').notEmpty();
// Get Errors
let errors = req.validationErrors();
if(errors){
res.render('add_user', {
title:'Add User',
errors:errors
});
} else {
let user = new User();
user.name = req.body.name;
user.email = req.body.email;
user.password = req.body.password;
user.save(function(err){
if(err){
console.log(err);
return;
} else {
req.flash('success','User Added');
res.redirect('/');
}
});
}
});
// Load Edit Form
router.get('/edit/:id', ensureAuthenticated, function(req, res){
User.findById(req.params.id, function(err, user){
res.render('edit_user', {
title:'Edit User',
user:user
});
});
});
// Update Submit POST Route
router.post('/edit/:id',ensureAuthenticated, function(req, res){
let user = {};
user.name = req.body.name;
user.email = req.body.email;
user.password = req.body.password;
let query = {_id:req.params.id}
User.update(query, user, function(err){
if(err){
console.log(err);
return;
} else {
req.flash('success', 'User Updated');
res.redirect('/');
}
});
});
//Delete request
router.delete('/:id', function(req, res){
let query = {_id:req.params.id}
User.findById(req.params.id, function(err, user){
User.remove(query, function(err){
if(err){
console.log(err);
}
res.send('Success');
});
});
});
// Get Single User
router.get('/:id', function(req, res){
User.findById(req.params.id, function(err, user){
res.render('user', {
user:user
});
});
});
// Access Control
function ensureAuthenticated(req, res, next){
if(req.isAuthenticated()){
return next();
} else {
req.flash('danger', 'Please login');
res.redirect('/admins/login');
}
}
module.exports = router;
|
TypeScript
|
UTF-8
| 462
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
import { Field, ObjectType, ID } from 'type-graphql';
@ObjectType()
export class Hospital {
@Field({ nullable: true })
id: number;
@Field({ nullable: true })
name: string;
@Field({ nullable: true })
address?: string;
}
@ObjectType()
export class GraphDoctorDto {
@Field(() => ID)
id: number;
@Field({ nullable: true })
name?: string;
@Field({ nullable: true })
address?: string;
@Field(type => Hospital)
hospital?: Hospital;
}
|
Python
|
UTF-8
| 959
| 3.609375
| 4
|
[] |
no_license
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
def hex2str(hex_string):
items = list()
for i in range(0, len(hex_string), 2):
hex2 = hex_string[i] + hex_string[i + 1]
char = chr(int(hex2, 16))
items.append(char)
return ''.join(items)
def str2hex(text):
items = list()
for c in text:
# 'P' -> 0x50 -> 50
hex_char = hex(ord(c))[2:].upper()
items.append(hex_char)
return ''.join(items)
if __name__ == '__main__':
assert hex2str("504F53542068747470733A") == "POST https:"
assert str2hex(hex2str("504F53542068747470733A")) == "504F53542068747470733A"
assert str2hex("POST https:") == "504F53542068747470733A"
assert hex2str(str2hex("POST https:")) == "POST https:"
hex_text = "504F53542068747470733A"
text = hex2str(hex_text)
print('"{}"'.format(text))
text = "POST https:"
hex_text = str2hex(text)
print(hex_text)
|
Python
|
UTF-8
| 3,615
| 2.9375
| 3
|
[
"Apache-2.0"
] |
permissive
|
"""
functions for finding files
"""
from datetime import datetime, timedelta
from pathlib import Path
import typing as T
import numpy as np
from .utils import filename2datetime
FILE_FORMATS = [".h5", ".nc"]
def config(path: Path) -> Path:
"""given a path or config filename, return the full path to config file"""
return find_stem(path, stem="config", suffix="nml")
def simsize(path: Path, suffix: str = None) -> Path:
"""gets path to simsize file"""
return find_stem(path, stem="simsize", suffix=suffix)
def frame(simdir: Path, time: datetime, *, file_format: str = None) -> Path:
"""
the frame filenames can have different file formats
"""
simdir = Path(simdir).expanduser()
stem = (
time.strftime("%Y%m%d")
+ f"_{time.hour*3600 + time.minute*60 + time.second:05d}."
+ f"{time.microsecond:06d}"
)
suffixes = [f".{file_format}"] if file_format else FILE_FORMATS
for ext in suffixes:
fn = simdir / (stem + ext)
if fn.is_file():
return fn
# %% WORKAROUND for real32 file ticks. This will be removed when datetime-fortran is implemented
MAX_OFFSET = timedelta(seconds=1) # 10 ms precision, allow extra accumulated tolerance
pat = time.strftime("%Y%m%d") + "_*"
for ext in suffixes:
file_times = []
files = list(simdir.glob(pat + ext))
for fn in files:
file_times.append(filename2datetime(fn))
if file_times:
afile_times = np.array(file_times)
i = abs(afile_times - time).argmin() # type: ignore
if abs(afile_times[i] - time) <= MAX_OFFSET:
return files[i]
raise FileNotFoundError(f"{stem}{suffixes} not found in {simdir}")
def grid(path: Path, *, suffix=None) -> Path:
"""given a path or filename, return the full path to simgrid file
we don't override FILE_FORMATS to allow outputs from a prior sim in a different
file format to be used in this sim.
"""
return find_stem(path, stem="simgrid", suffix=suffix)
def find_stem(path: Path, stem: str, suffix: str = None) -> Path:
"""find file containing stem"""
path = Path(path).expanduser()
if path.is_file():
if stem in path.stem:
return path
else:
found = find_stem(path.parent, stem, path.suffix)
if not found:
raise FileNotFoundError(f"{stem} not found in {path.parent}")
return found
if suffix:
if isinstance(suffix, str):
if not suffix.startswith("."):
suffix = "." + suffix
suffixes = [suffix]
else:
suffixes = suffix
else:
suffixes = FILE_FORMATS
if path.is_dir():
for p in (path, path / "inputs"):
for suff in suffixes:
f = p / (stem + suff)
if f.is_file():
return f
raise FileNotFoundError(f"{stem} not found in {path}")
def inputs(direc: Path, input_dir: T.Optional[Path] = None) -> Path:
"""
find input parameter directory
direc: pathlib.Path
top level simulation dir
input_dir: pathlib.Path
relative to top level, the parameter dir. E.g. inputs/precip, input/Efield
"""
direc = Path(direc).expanduser()
if input_dir:
input_path = Path(input_dir).expanduser()
if not input_path.is_absolute():
input_path = direc / input_path
else:
input_path = direc
if not input_path.is_dir():
raise NotADirectoryError(direc)
return input_path
|
Java
|
UTF-8
| 405
| 2.546875
| 3
|
[] |
no_license
|
package com.example.android.popularmovies;
/**
* Interface that receives clicks from movie trailer list items.
*/
public interface IMovieTrailerListItemClickListener
{
/**
* Called when a movie trailer list item is clicked.
*
* @param clickedItemIndex the index of the movie trailer item in the list that was clicked.
*/
public void onMovieTrailerListItemClick(int clickedItemIndex);
}
|
Markdown
|
UTF-8
| 1,498
| 2.640625
| 3
|
[] |
no_license
|
# Serverless Page to PDF
Highly customizable, ready to deploy serverless AWS API to extract pdf of webpages.
## Installation
```sh
npm install
```
Serverless API Deployment. Make sure before deployment you set your credentials in profile
```sh
npm run deploy
```
### Usage
API serves your POST requests and returns pdf of provided url.
Request will have JSON body like this.
```javascript
{
"url": "https://google.com", /* required */
"s3Url": "value", /* optional (S3 bucket url to upload pdf. If not provided, it will return generated pdf) */
"basicAuth": { /* optional (if url contain basic authentication, puppeteer will try to authenticate) */
"username": "your username",
"password": "your password",
},
"headers": { /* optional (requested url headers, like you send in normal requests to that url) */
"x-api-key": "someapikey",
"...": "..."
},
"pdfOptions": { /* optional (custom pdfOptions) */
"format": "A4", /* default */
"printBackground": true /* default */
},
"waitUntil": "value", /* optional (supported values "load","domcontentloaded",("networkidle0" - default),"networkidle2" */
"selector": "value" /* optional (css selector to wait) */
}
```
[PDF Options](https://github.com/GoogleChrome/puppeteer/blob/v1.12.2/docs/api.md#pagepdfoptions)
Note: Headless_shell version must match the version of chrome that is set in puppeteer v1.11.0.
Please do not update puppeteer to last version,
that will cause fail to launch chrome and endpoint request timeout.
|
Markdown
|
UTF-8
| 5,291
| 2.609375
| 3
|
[] |
no_license
|
---
description: "Recipe of Speedy Pancakes: Plain"
title: "Recipe of Speedy Pancakes: Plain"
slug: 1967-recipe-of-speedy-pancakes-plain
date: 2021-03-11T07:57:20.302Z
image: https://img-global.cpcdn.com/recipes/f00a784212c35495/680x482cq70/pancakes-plain-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/f00a784212c35495/680x482cq70/pancakes-plain-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/f00a784212c35495/680x482cq70/pancakes-plain-recipe-main-photo.jpg
author: Marguerite Barrett
ratingvalue: 4.7
reviewcount: 43449
recipeingredient:
- "2 cups flour"
- "1/4 cup ganulated sugar"
- "1 tsp baking powder"
- "1 tsp baking soda"
- "1/2 tsp salt or a good few cranks of your salt grinder"
- "1 1/2 cups milk soy or almond is fine"
- "1/4 cup melted butter or oil cannola or vegetable preferably"
- "2 tsp vanilla extract"
- "1 large egg or 2 medium eggs or 3 small eggs"
recipeinstructions:
- "If you don't have a type of milk in your fridge, you can substitute it with a fourth or third the amount of creamer (depending on how sweet you like your pancakes, I like mine sweeter so I use a third), and the rest with water. For 1 1/2 cups milk, that'd be about 1/3 creamer and 3/4 cup water, with some adjustment to your own taste."
- "In a medium sized mixing bowl, crack the eggs (check for shell flakes! They taste awful), and add the oil, milk, vanilla, and whisk well."
- "Add the salt, baking powder, baking soda, and sugar, and whisk well again."
- "Finally, add the flour in 2 parts as you whisk, and make sure there are no lumps but don't mix past "no lumps", or the pancakes can come out stiff or too chewy."
- "Put a bit of oil in a pan and turn the burner to medium low for a power burner and medium for a regular, and when its hot enough that the oil is steaming, ladle out your pancakes. (big might require a few ladles, small ones will require only one)"
- "Cook the pancakes until bubbles start popping on the surface, and then flip them over, and cook until lightly browned, or you can squish them with the spatula and no raw batter squirts out."
- "Plate them up and eat."
categories:
- Recipe
tags:
- pancakes
- plain
katakunci: pancakes plain
nutrition: 282 calories
recipecuisine: American
preptime: "PT40M"
cooktime: "PT40M"
recipeyield: "1"
recipecategory: Dessert
---

Hello everybody, I hope you're having an incredible day today. Today, I will show you a way to prepare a distinctive dish, pancakes: plain. It is one of my favorites. This time, I will make it a little bit unique. This will be really delicious.
Pancakes: Plain is one of the most popular of current trending foods in the world. It's easy, it's fast, it tastes delicious. It's enjoyed by millions daily. They're fine and they look fantastic. Pancakes: Plain is something which I have loved my whole life.
To get started with this particular recipe, we have to first prepare a few components. You can cook pancakes: plain using 9 ingredients and 7 steps. Here is how you can achieve that.
<!--inarticleads1-->
##### The ingredients needed to make Pancakes: Plain:
1. Take 2 cups flour
1. Make ready 1/4 cup ganulated sugar
1. Take 1 tsp baking powder
1. Prepare 1 tsp baking soda
1. Get 1/2 tsp salt (or a good few cranks of your salt grinder)
1. Prepare 1 1/2 cups milk (soy or almond is fine)
1. Make ready 1/4 cup melted butter or oil (cannola or vegetable, preferably)
1. Get 2 tsp vanilla extract
1. Get 1 large egg, or 2 medium eggs, or 3 small eggs
<!--inarticleads2-->
##### Instructions to make Pancakes: Plain:
1. If you don't have a type of milk in your fridge, you can substitute it with a fourth or third the amount of creamer (depending on how sweet you like your pancakes, I like mine sweeter so I use a third), and the rest with water. For 1 1/2 cups milk, that'd be about 1/3 creamer and 3/4 cup water, with some adjustment to your own taste.
1. In a medium sized mixing bowl, crack the eggs (check for shell flakes! They taste awful), and add the oil, milk, vanilla, and whisk well.
1. Add the salt, baking powder, baking soda, and sugar, and whisk well again.
1. Finally, add the flour in 2 parts as you whisk, and make sure there are no lumps but don't mix past "no lumps", or the pancakes can come out stiff or too chewy.
1. Put a bit of oil in a pan and turn the burner to medium low for a power burner and medium for a regular, and when its hot enough that the oil is steaming, ladle out your pancakes. (big might require a few ladles, small ones will require only one)
1. Cook the pancakes until bubbles start popping on the surface, and then flip them over, and cook until lightly browned, or you can squish them with the spatula and no raw batter squirts out.
1. Plate them up and eat.
So that's going to wrap it up for this exceptional food pancakes: plain recipe. Thanks so much for reading. I am confident that you can make this at home. There is gonna be more interesting food in home recipes coming up. Don't forget to bookmark this page in your browser, and share it to your loved ones, colleague and friends. Thank you for reading. Go on get cooking!
|
TypeScript
|
UTF-8
| 2,949
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
import { NextApiRequest, NextApiResponse } from "next";
import _startCase from "lodash/startCase";
import connectDB from "../../config/connectDB";
import { Item, List } from "../../models";
import errorHandler from "../../utils/errorHandler";
import badMethodHandler from "../../utils/badMethodHandler";
// Original task items
const item1 = new Item({
task: "Welcome to your todo list",
completed: false,
});
const item2 = new Item({
task: "Hit the + button to add a new item",
completed: false,
});
const item3 = new Item({
task: "Hit the delete button to delete an item",
completed: false,
});
const item4 = new Item({
task: "Tap the task name to go back to all your tasks",
completed: false,
});
const item5 = new Item({
task: "Tap the moon icon to switch between dark and light modes",
completed: false,
});
const defaultItems = [item1, item2, item3, item4, item5];
export default async (req: NextApiRequest, res: NextApiResponse) => {
await connectDB();
const {
method,
query: { id },
} = req;
const customListName = _startCase(req.query.customListName as string);
switch (method) {
case "GET":
try {
const foundList = await List.findOne({ name: customListName });
if (foundList) {
return res.status(200).json({
listTitle: foundList.name,
items: foundList.items,
});
} else {
const newList = await List.create({
name: customListName,
items: defaultItems,
});
return res.status(201).json({
listTitle: newList.name,
items: newList.items,
});
}
} catch (err) {
return errorHandler(err, res);
}
case "POST":
const { text } = req.body;
const item = new Item({
task: text,
completed: false,
});
try {
await List.findOneAndUpdate({ name: customListName }, { $push: { items: { ...item } } });
return res.status(201).json({
item,
});
} catch (err) {
return errorHandler(err, res);
}
case "PATCH":
const { completed } = req.body;
try {
const newList = await List.findOneAndUpdate(
{ name: customListName, "items._id": id },
{ "items.$.completed": completed }
);
if (!newList) return res.status(404).json(`List ${customListName} Not found`);
return res.status(200).json({
items: newList.items,
});
} catch (err) {
return errorHandler(err, res);
}
case "DELETE":
try {
await List.findOneAndUpdate({ name: customListName }, { $pull: { items: { _id: id } } });
return res.status(200).json({
success: true,
});
} catch (err) {
return errorHandler(err, res);
}
default:
badMethodHandler(method, res, ["GET", "POST", "PATCH", "DELETE"]);
}
};
|
C++
|
UTF-8
| 1,142
| 2.65625
| 3
|
[] |
no_license
|
#ifndef PARALLEL_GAME_OF_LIFE_PARALLEL_SIMULATOR_H_
#define PARALLEL_GAME_OF_LIFE_PARALLEL_SIMULATOR_H_
#include <pthread.h>
#include <vector>
#include <iostream>
#include "state.h"
#include "simulator.h"
#include "row_thread.h"
class RowThread;
class ParallelSimulator: public Simulator {
public:
friend class RowThread;
ParallelSimulator();
ParallelSimulator(const State& initial, int thread_cnt);
friend std::ostream& operator<<(std::ostream& out, const ParallelSimulator& p_simulator);
void Simulate(int steps);
void Stop();
void Quit();
bool IsRunning() const {
return running_;
}
bool IsStopped() const {
return stopped_;
}
private:
void Initialize();
void Step();
void InitializeThreads();
int working_threads_;
bool stopped_;
bool running_;
bool ended_;
bool threads_initialized_;
State next_state_;
std::vector<RowThread> threads;
pthread_mutex_t new_step_mutex;
pthread_cond_t new_step_cond;
pthread_mutex_t finish_mutex;
pthread_cond_t finish_cond;
};
#endif // PARALLEL_GAME_OF_LIFE_PARALLEL_SIMULATOR_H_
|
Java
|
UTF-8
| 17,631
| 2.25
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.redoute.datamap.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Level;
import org.jfree.util.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.redoute.datamap.dao.IPictureDAO;
import com.redoute.datamap.database.DatabaseSpring;
import com.redoute.datamap.entity.Picture;
import com.redoute.datamap.factory.IFactoryPicture;
import com.redoute.datamap.log.Logger;
import com.redoute.datamap.util.DAOUtil;
import com.redoute.datamap.util.HTML5CanvasURLUtil.HTML5CanvasURLParsingException;
import com.redoute.datamap.util.PictureFileHelper;
/**
* {Insert class description here}
*
* @author bcivel
*/
@Repository
public class PictureDAO implements IPictureDAO {
/** Associated {@link org.apache.log4j.Logger} to this class */
private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(PictureDAO.class);
/**
* Description of the variable here.
*/
@Autowired
private DatabaseSpring databaseSpring;
@Autowired
private IFactoryPicture factoryPicture;
@Autowired
private PictureFileHelper pictureFileHelper;
@Override
public Picture findPictureByKey(String id) {
Picture result = null;
final String query = "SELECT * FROM picture WHERE id = ?";
Connection connection = this.databaseSpring.connect();
try {
PreparedStatement preStat = connection.prepareStatement(query);
try {
preStat.setString(1, id);
ResultSet resultSet = preStat.executeQuery();
try {
if (resultSet.first()) {
result = loadPictureFromResultSet(resultSet);
}
} catch (SQLException exception) {
Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
} finally {
resultSet.close();
}
} catch (SQLException exception) {
Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
} finally {
preStat.close();
}
} catch (SQLException exception) {
Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
Logger.log(PictureDAO.class.getName(), Level.WARN, e.toString());
}
}
return result;
}
@Override
public void createPicture(Picture picture) {
Connection connection = this.databaseSpring.connect();
PreparedStatement statement = null;
try {
statement = connection.prepareStatement("INSERT INTO picture (`id`, `application`, `page`, `picture`, `localpath`) VALUES (?, ?, ?, ?, ?)");
statement.setInt(1, 0);
statement.setString(2, picture.getApplication());
statement.setString(3, picture.getPage());
statement.setString(4, picture.getPicture());
statement.setString(5, pictureFileHelper.createLocalPath(picture));
statement.executeUpdate();
pictureFileHelper.save(picture, false);
} catch (SQLException e) {
LOG.error("Unable to create picture " + picture + " due to a database error", e);
} catch (HTML5CanvasURLParsingException e) {
LOG.error("Unable to create picture " + picture + " due to a base64 format error", e);
} finally {
DAOUtil.closeResources(statement, connection);
}
}
@Override
public void deletePicture(Picture picture) {
StringBuilder query = new StringBuilder();
query.append("delete from picture where `id`=? ");
Connection connection = this.databaseSpring.connect();
try {
PreparedStatement preStat = connection.prepareStatement(query.toString());
try {
preStat.setString(1, picture.getId().toString());
preStat.executeUpdate();
} catch (SQLException exception) {
Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
} finally {
preStat.close();
}
} catch (SQLException exception) {
Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
Logger.log(PictureDAO.class.getName(), Level.WARN, e.toString());
}
}
pictureFileHelper.save(picture, false);
}
@Override
public List<Picture> findAllPicture() {
List<Picture> list = null;
final String query = "SELECT * FROM picture";
Connection connection = this.databaseSpring.connect();
try {
PreparedStatement preStat = connection.prepareStatement(query);
try {
ResultSet resultSet = preStat.executeQuery();
list = new ArrayList<Picture>();
try {
while (resultSet.next()) {
list.add(this.loadPictureFromResultSet(resultSet));
}
} catch (SQLException exception) {
Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
} finally {
resultSet.close();
}
} catch (SQLException exception) {
Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
} finally {
preStat.close();
}
} catch (SQLException exception) {
Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
Logger.log(PictureDAO.class.getName(), Level.WARN, e.toString());
}
}
return list;
}
@Override
public List<Picture> findPictureListByCriteria(String individualSearch, String joinedSearch) {
List<Picture> pictureList = new ArrayList<Picture>();
StringBuilder searchSQL = new StringBuilder();
StringBuilder searchSQL2 = new StringBuilder();
StringBuilder query = new StringBuilder();
query.append("SELECT p.id, p.application, p.page, p.picture, '' as base64, p.localpath FROM picture p ");
if (!joinedSearch.equals("")){
query.append(" join datamap d on p.page=d.page and p.picture=d.picture and p.application=d.application");
}
query.append(" where 1=1 ");
if (!joinedSearch.equals("")){
searchSQL.append(joinedSearch);
}
if (!individualSearch.equals("")) {
if (!individualSearch.startsWith(" AND ")) {
individualSearch = " AND " + individualSearch;
}
searchSQL.append(individualSearch);
}
query.append(searchSQL2);
query.append(searchSQL);
query.append(" group by p.page,p.picture ");
Connection connection = this.databaseSpring.connect();
try {
PreparedStatement preStat = connection.prepareStatement(query.toString());
try {
ResultSet resultSet = preStat.executeQuery();
try {
while (resultSet.next()) {
pictureList.add(this.loadPictureFromResultSet(resultSet));
}
} catch (SQLException exception) {
Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
} finally {
resultSet.close();
}
} catch (SQLException exception) {
Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
} finally {
preStat.close();
}
} catch (SQLException exception) {
Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
Logger.log(PictureDAO.class.getName(), Level.ERROR, e.toString());
}
}
return pictureList;
}
private Picture loadPictureFromResultSet(ResultSet resultSet) throws SQLException {
Integer id = resultSet.getInt("id");
String application = resultSet.getString("application");
String page = resultSet.getString("page");
String picture = resultSet.getString("picture");
String base64 = resultSet.getString("base64");
String localPath = resultSet.getString("localpath");
Picture pic = factoryPicture.create(id, application, page, picture, base64, localPath);
return DAOUtil.isEmpty(localPath) ? pic : pictureFileHelper.load(pic);
}
@Override
public void updatePicture(String id, String columnName, String value) {
if (columnName.equals("base64")) {
updateFilePicture(id, value);
} else {
updateDatabasePicture(id, columnName, value);
}
}
private void updateDatabasePicture(String id, String columnName, String value) {
boolean throwExcep = false;
StringBuilder query = new StringBuilder();
query.append("update picture set `");
query.append(columnName);
query.append("`=? where `id`=? ");
Connection connection = this.databaseSpring.connect();
try {
PreparedStatement preStat = connection.prepareStatement(query.toString());
try {
preStat.setString(1, value);
preStat.setString(2, id);
preStat.executeUpdate();
throwExcep = false;
} catch (SQLException exception) {
Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
} finally {
preStat.close();
}
} catch (SQLException exception) {
Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
Logger.log(PictureDAO.class.getName(), Level.WARN, e.toString());
}
}
}
private void updateFilePicture(String id, String value) {
Picture pic = findPictureByKey(id);
pic.setBase64(value);
try {
if (DAOUtil.isEmpty(pic.getLocalPath())) {
pic.setLocalPath(pictureFileHelper.createLocalPath(pic));
updatePicture(id, "localpath", pic.getLocalPath());
}
pictureFileHelper.save(pic, true);
} catch (HTML5CanvasURLParsingException e) {
Log.error("Unable to update picture " + pic, e);
}
}
@Override
public Integer getNumberOfPicturePerCrtiteria(String searchTerm, String inds) {
Integer result = 0;
StringBuilder query = new StringBuilder();
StringBuilder gSearch = new StringBuilder();
String searchSQL = "";
query.append("SELECT count(*) FROM picture");
gSearch.append(" where (`id` like '%");
gSearch.append(searchTerm);
gSearch.append("%'");
gSearch.append(" or `page` like '%");
gSearch.append(searchTerm);
gSearch.append("%'");
gSearch.append(" or `application` like '%");
gSearch.append(searchTerm);
gSearch.append("%'");
gSearch.append(" or `picture` like '%");
gSearch.append(searchTerm);
gSearch.append("%')");
if (!searchTerm.equals("") && !inds.equals("")) {
searchSQL = gSearch.toString() + " and " + inds;
} else if (!inds.equals("")) {
searchSQL = " where " + inds;
} else if (!searchTerm.equals("")) {
searchSQL = gSearch.toString();
}
query.append(searchSQL);
Connection connection = this.databaseSpring.connect();
try {
PreparedStatement preStat = connection.prepareStatement(query.toString());
try {
ResultSet resultSet = preStat.executeQuery();
try {
if (resultSet.first()) {
result = resultSet.getInt(1);
}
} catch (SQLException exception) {
Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
} finally {
resultSet.close();
}
} catch (SQLException exception) {
Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
} finally {
preStat.close();
}
} catch (SQLException exception) {
Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
Logger.log(PictureDAO.class.getName(), Level.ERROR, e.toString());
}
}
return result;
}
@Override
public List<Picture> findPicturePerClause(String whereClause) {
List<Picture> list = null;
StringBuilder query = new StringBuilder();
query.append("SELECT * FROM picture where 1=1 ");
query.append(whereClause);
Connection connection = this.databaseSpring.connect();
try {
PreparedStatement preStat = connection.prepareStatement(query.toString());
try {
ResultSet resultSet = preStat.executeQuery();
list = new ArrayList<Picture>();
try {
while (resultSet.next()) {
list.add(this.loadPictureFromResultSet(resultSet));
}
} catch (SQLException exception) {
Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
} finally {
resultSet.close();
}
} catch (SQLException exception) {
Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
} finally {
preStat.close();
}
} catch (SQLException exception) {
Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
Logger.log(PictureDAO.class.getName(), Level.WARN, e.toString());
}
}
return list;
}
@Override
public List<String> findDistinctValuesfromColumn(String colName) {
List<String> result = new ArrayList<String>();
StringBuilder query = new StringBuilder();
query.append("SELECT distinct ");
query.append(colName);
query.append(" FROM picture order by ");
query.append(colName);
query.append(" asc");
Connection connection = this.databaseSpring.connect();
try {
PreparedStatement preStat = connection.prepareStatement(query.toString());
try {
ResultSet resultSet = preStat.executeQuery();
try {
while (resultSet.next()) {
result.add(resultSet.getString(1)== null ? "" : resultSet.getString(1) );
}
resultSet.close();
} catch (SQLException exception) {
Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
} finally {
resultSet.close();
}
} catch (SQLException exception) {
Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
} finally {
preStat.close();
}
} catch (SQLException exception) {
Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
} finally {
try {
if (connection != null) {
Logger.log(PictureDAO.class.getName(), Level.INFO, "Disconnecting to jdbc/qualityfollowup from findDistinctValuesfromParameter");
connection.close();
}
} catch (SQLException e) {
Logger.log(PictureDAO.class.getName(), Level.WARN, e.toString());
}
}
return result; }
}
|
Java
|
UTF-8
| 6,765
| 1.734375
| 2
|
[] |
no_license
|
package tw.edu.chit.struts.action.teacher;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;
import tw.edu.chit.model.Rcact;
import tw.edu.chit.model.Rcjour;
import tw.edu.chit.model.domain.UserCredential;
import tw.edu.chit.service.CourseManager;
import tw.edu.chit.struts.action.BaseLookupDispatchAction;
import tw.edu.chit.util.Toolket;
public class Rcjour_ViewAction extends BaseLookupDispatchAction {
/**
* 更新作業
*/
public ActionForward Update(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception{
HttpSession session = request.getSession(false);
CourseManager manager = (CourseManager) getBean("courseManager");
UserCredential user = (UserCredential) session.getAttribute("Credential");
DynaActionForm aForm = (DynaActionForm) form;
Toolket.resetCheckboxCookie(response, "rcjour");
ActionMessages messages = new ActionMessages();
String oids = aForm.getString("oid_s");
String Table = "Rcjour";
manager.removeRcTableBy(Table, oids);
String idno = user.getMember().getAccount();
String schoolYear = aForm.getString("schoolYear");
String projno = aForm.getString("projno");
String title = aForm.getString("title");
String authorno = aForm.getString("authorno");
String comAuthorno = aForm.getString("COM_authorno");
String kindid = aForm.getString("kindid");
String jname = aForm.getString("jname");
String volume = aForm.getString("volume");
String period = aForm.getString("period");
String pmonth = aForm.getString("pmonth");
String pyear = aForm.getString("pyear");
String intor = aForm.getString("intor");
String type = aForm.getString("type");
String place = aForm.getString("place");
String approve = aForm.getString("approve");
String approveTemp = aForm.getString("approveTemp");
Rcjour rcjour = new Rcjour();
rcjour.setIdno(idno);
rcjour.setSchoolYear(Short.parseShort(schoolYear));
rcjour.setProjno(projno);
rcjour.setTitle(title);
rcjour.setAuthorno(authorno);
rcjour.setComAuthorno(comAuthorno);
rcjour.setKindid(kindid);
rcjour.setJname(jname);
rcjour.setVolume(volume);
rcjour.setPeriod(period);
rcjour.setPmonth(Short.parseShort(pmonth));
rcjour.setPyear(Short.parseShort(pyear));
rcjour.setIntor(intor);
rcjour.setType(type);
rcjour.setLastModified(new Date());
rcjour.setPlace(place);
rcjour.setApprove(approve); //預設存入狀態=處理中 Rccode.Oid=96
rcjour.setApproveTemp(approveTemp);
manager.updateObject(rcjour);
messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "Course.messageN1", "更新完成"));
saveMessages(request, messages);
session.removeAttribute("RcjourList");
setContentPage(request.getSession(false), "teacher/Rcjour.jsp");
return mapping.findForward("Main");
}
/**
* 刪除刪除
*/
public ActionForward Delete(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception{
HttpSession session = request.getSession(false);
CourseManager manager = (CourseManager) getBean("courseManager");
UserCredential user = (UserCredential) session.getAttribute("Credential");
DynaActionForm aForm = (DynaActionForm) form;
Toolket.resetCheckboxCookie(response, "rcjour");
String oids = aForm.getString("oid_s");
String Table = "Rcjour";
manager.removeRcTableBy(Table, oids);
session.removeAttribute("RcjourList");
setContentPage(request.getSession(false), "teacher/Rcjour.jsp");
return mapping.findForward("Main");
}
/**
* 返回
*/
public ActionForward Back(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception{
setContentPage(request.getSession(false), "teacher/Rcjour.jsp");
return mapping.findForward("Main");
}
/**
* 匯出/列印
*/
public ActionForward PrintOut(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
HttpSession session = request.getSession(false);
CourseManager manager = (CourseManager) getBean("courseManager");
DynaActionForm aForm = (DynaActionForm) form;
UserCredential user = (UserCredential) session.getAttribute("Credential");
ActionMessages messages = new ActionMessages();
String COM_authorno = aForm.getString("COM_authorno");
if (COM_authorno.equals("Y")){
COM_authorno = "是";
}else if (COM_authorno.equals("N")){
COM_authorno = "否";
}
//session.setAttribute("idno", aForm.get("idno"));
session.setAttribute("school_year", aForm.get("schoolYear"));
session.setAttribute("projno", aForm.get("projno"));
session.setAttribute("title", aForm.get("title"));
session.setAttribute("kindid", manager.ezGetString("Select name From Rccode Where Oid="+aForm.getString("kindid")));
session.setAttribute("authorno", manager.ezGetString("Select name From Rccode Where Oid="+aForm.getString("authorno")));
session.setAttribute("COM_authorno", COM_authorno);
session.setAttribute("jname", aForm.get("jname"));
session.setAttribute("type", manager.ezGetString("Select name From Rccode Where Oid="+aForm.getString("type")));
session.setAttribute("place", manager.ezGetString("Select name From Rccode Where Oid="+aForm.getString("place")));
session.setAttribute("volume", aForm.get("volume"));
session.setAttribute("period", aForm.get("period"));
session.setAttribute("pyear", aForm.get("pyear"));
session.setAttribute("pmonth", aForm.get("pmonth"));
session.setAttribute("intor", aForm.get("intor"));
messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "Course.messageN1", "如果沒有反應,請檢查是否阻擋彈跳視窗"));
saveMessages(request, messages);
session.removeAttribute("RcjourList");
setContentPage(request.getSession(false), "teacher/Rcjour_Out.jsp");
return mapping.findForward("Main");
}
@Override
protected Map<String, String> getKeyMethodMap() {
// TODO Auto-generated method stub
Map<String, String> map = new HashMap<String, String>();
map.put("Update", "Update");
map.put("Delete", "Delete");
map.put("Back", "Back");
map.put("PrintOut", "PrintOut");
return map;
}
}
|
Python
|
UTF-8
| 6,374
| 2.75
| 3
|
[
"LicenseRef-scancode-philippe-de-muyter",
"GPL-2.0-only",
"GPL-1.0-or-later"
] |
permissive
|
#!/usr/bin/env python3
import sys
import json
import html
from reportlab.lib.pagesizes import letter
from reportlab.platypus import Frame, Paragraph, Spacer, PageBreak,PageTemplate, BaseDocTemplate
from reportlab.platypus.tableofcontents import TableOfContents
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import cm
styles = getSampleStyleSheet()
text_colors = { "GREEN": "#00DB00", "RED": "#FF0000", "REDYELLOW": "#FFA500", "BLUE": "#0000FF",
"DARKGREY": "#5C5C5C", "YELLOW": "#ebeb21", "MAGENTA": "#FF00FF", "CYAN": "#00FFFF", "LIGHT_GREY": "#A6A6A6"}
# Required to automatically set Page Numbers
class PageTemplateWithCount(PageTemplate):
def __init__(self, id, frames, **kw):
PageTemplate.__init__(self, id, frames, **kw)
def beforeDrawPage(self, canvas, doc):
page_num = canvas.getPageNumber()
canvas.drawRightString(10.5*cm, 1*cm, str(page_num))
# Required to automatically set the Table of Contents
class MyDocTemplate(BaseDocTemplate):
def __init__(self, filename, **kw):
self.allowSplitting = 0
BaseDocTemplate.__init__(self, filename, **kw)
template = PageTemplateWithCount("normal", [Frame(2.5*cm, 2.5*cm, 15*cm, 25*cm, id='F1')])
self.addPageTemplates(template)
def afterFlowable(self, flowable):
if flowable.__class__.__name__ == "Paragraph":
text = flowable.getPlainText()
style = flowable.style.name
if style == "Heading1":
self.notify("TOCEntry", (0, text, self.page))
if style == "Heading2":
self.notify("TOCEntry", (1, text, self.page))
if style == "Heading3":
self.notify("TOCEntry", (2, text, self.page))
# Poor take at dynamicly generating styles depending on depth(?)
def get_level_styles(level):
global styles
indent_value = 10 * (level - 1);
# Overriding some default stylings
level_styles = {
"title": ParagraphStyle(
**dict(styles[f"Heading{level}"].__dict__,
**{ "leftIndent": indent_value })),
"text": ParagraphStyle(
**dict(styles["Code"].__dict__,
**{ "backColor": "#F0F0F0",
"borderPadding": 5, "borderWidth": 1,
"borderColor": "black", "borderRadius": 5,
"leftIndent": 5 + indent_value})),
"info": ParagraphStyle(
**dict(styles["Italic"].__dict__,
**{ "leftIndent": indent_value })),
}
return level_styles
def get_colors_by_text(colors):
new_colors = {}
for (color, words) in colors.items():
for word in words:
new_colors[html.escape(word)] = color
return new_colors
def build_main_section(section, title, level=1):
styles = get_level_styles(level)
has_links = "infos" in section.keys() and len(section["infos"]) > 0
has_lines = "lines" in section.keys() and len(section["lines"]) > 1
has_children = "sections" in section.keys() and len(section["sections"].keys()) > 0
# Only display data for Sections with results
show_section = has_lines or has_children
elements = []
if show_section:
elements.append(Paragraph(title, style=styles["title"]))
# Print info if any
if show_section and has_links:
for info in section["infos"]:
words = info.split()
# Join all lines and encode any links that might be present.
words = map(lambda word: f'<a href="{word}" color="blue">{word}</a>' if "http" in word else word, words)
words = " ".join(words)
elements.append(Paragraph(words, style=styles["info"] ))
# Print lines if any
if "lines" in section.keys() and len(section["lines"]) > 1:
colors_by_line = list(map(lambda x: x["colors"], section["lines"]))
lines = list(map(lambda x: html.escape(x["clean_text"]), section["lines"]))
for (idx, line) in enumerate(lines):
colors = colors_by_line[idx]
colored_text = get_colors_by_text(colors)
colored_line = line
for (text, color) in colored_text.items():
if color == "REDYELLOW":
colored_line = colored_line.replace(text, f'<font color="{text_colors[color]}"><b>{text}</b></font>')
else:
colored_line = colored_line.replace(text, f'<font color="{text_colors[color]}">{text}</font>')
lines[idx] = colored_line
elements.append(Spacer(0, 10))
line = "<br/>".join(lines)
# If it's a top level entry remove the line break caused by an empty "clean_text"
if level == 1: line = line[5:]
elements.append(Paragraph(line, style=styles["text"]))
# Print child sections
if has_children:
for child_title in section["sections"].keys():
element_list = build_main_section(section["sections"][child_title], child_title, level + 1)
elements.extend(element_list)
# Add spacing at the end of section. The deeper the level the smaller the spacing.
if show_section:
elements.append(Spacer(1, 40 - (10 * level)))
return elements
def main():
with open(JSON_PATH) as file:
# Read and parse JSON file
data = json.loads(file.read())
# Default pdf values
doc = MyDocTemplate(PDF_PATH)
toc = TableOfContents()
toc.levelStyles = [
ParagraphStyle(name = "Heading1", fontSize = 14, leading=16),
ParagraphStyle(name = "Heading2", fontSize = 12, leading=14, leftIndent = 10),
ParagraphStyle(name = "Heading3", fontSize = 10, leading=12, leftIndent = 20),
]
elements = [Paragraph("PEAS Report", style=styles["Title"]), Spacer(0, 30), toc, PageBreak()]
# Iterate over all top level sections and build their elements.
for title in data.keys():
element_list = build_main_section(data[title], title)
elements.extend(element_list)
doc.multiBuild(elements)
# Start execution
if __name__ == "__main__":
try:
JSON_PATH = sys.argv[1]
PDF_PATH = sys.argv[2]
except IndexError as err:
print("Error: Please pass the peas.json file and the path to save the pdf\njson2pdf.py <json_file> <pdf_file.pdf>")
sys.exit(1)
main()
|
Python
|
UTF-8
| 549
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
import random
for c, k in enumerate([1024,2048,4096,8192,16384,32768,65536]):
file = open("ex3_"+str(c)+".txt", "w")
table = open("tableNew.txt", "r")
file.write(str(k)+"\n")
file.write(str(k)+"\n")
file.write(str(60)+"\n")
file.write(str(1)+"\n")
for line in table.readlines():
file.write(line)
file.write("1\n")
for bu in range(k):
b = random.randint(0,1)
i1 = random.randint(0,59)
i2 = random.randint(0,59)
file.write("{} {} {}".format(b,i1,i2)+"\n")
file.close()
|
Java
|
UTF-8
| 735
| 1.710938
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.qouteall.immersive_portals.mixin.common.portal_generation;
import com.qouteall.immersive_portals.portal.custom_portal_gen.CustomPortalGenManagement;
import net.minecraft.server.management.PlayerList;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(PlayerList.class)
public class MixinPlayerManager_P {
@Inject(
method = "Lnet/minecraft/server/management/PlayerList;reloadResources()V",
at = @At("RETURN")
)
private void onOnDatapackReloaded(CallbackInfo ci) {
CustomPortalGenManagement.onDatapackReload();
}
}
|
TypeScript
|
UTF-8
| 5,729
| 2.53125
| 3
|
[] |
no_license
|
import Vue from 'vue'
import Vuex from 'vuex'
import { AppState } from './State'
import { Day } from './classes/Day'
import { Card } from './cards/job-cards'
import { EventCard } from './cards/event-cards'
import { clone } from './utilities'
Vue.use(Vuex)
export default new Vuex.Store({
state: new AppState(),
mutations: {
startSimulation: function (state: AppState) {
state.hasStarted = true
state.currentDay = 0
const day = state.sprintDays[state.currentDay]
day.price = state.prices[state.price]
day.isInteractive = true
},
resetCountdown: function (state: AppState) {
state.countdownProgress = 10000
},
clearAnnouncements: function (state: AppState) {
state.announcements.length = 0
},
switchView: function (state: AppState, newView: string) {
state.currentView = newView
},
nextSprint: function (state: AppState) {
state.sprint++
if(state.sprint > state.maxSprints) {
const endResult = state.businessObject.processEndGame()
state.ending = endResult
state.currentView = 'end'
}
else {
state.currentDay = -1
state.progress = 0
for (let i = 0; i < state.sprintDays.length; i++) {
const day = state.sprintDays[i]
day.result = null
day.tasks.length = 0
day.isInteractive = true
}
}
},
autoPopulateDays: function (state: AppState) {
for (let i = 0; i < state.sprintDays.length; i++) {
const day = state.sprintDays[i]
while(day.tasks.length < 2) {
state.selectedTaskIndex = Math.floor((Math.random() * 6))
day.tasks.push(clone(state.tasks[state.selectedTaskIndex]))
}
}
},
tickCountdown: function (state: AppState) {
state.countdownProgress -= state.tickSpeed
if(state.countdownProgress <= 0) {
state.countdownProgress = 0
}
},
tick: function (state: AppState) {
state.progress += 0.1
let didCompleteDay = false
if(state.progress > 10) {
didCompleteDay = true
const day = state.sprintDays[state.currentDay]
const result = state.businessObject.dayComplete(
day,
(event: EventCard) => {
state.announcements.length = 0
state.announcements.push(event)
}
)
day.result = result.dayHistory
state.isPaused = result.didTriggerEvent
state.progress = 0.1
state.currentDay++
}
if(state.currentDay > 13) {
state.businessObject.sprintComplete(state.sprint)
}
else {
if(didCompleteDay) {
const day = state.sprintDays[state.currentDay]
const newPrice = state.prices[state.price]
day.price = newPrice
day.isInteractive = false
}
}
},
unpause: function (state: AppState) {
state.isPaused = false
},
updatePrice: function (state: AppState, price: number) {
state.price = price
},
setSelectedTaskIndex: function (state: AppState, index: number) {
state.selectedTaskIndex = index
},
addSelectedTaskToDay: function (state: AppState, day: Day) {
if (day.tasks.length < 2 && day.isInteractive) {
const task = clone(state.tasks[state.selectedTaskIndex])
day.tasks.push(task)
}
},
removeTaskFromDay: function (state: AppState, payload) {
console.log('remove task', arguments)
const leftOverTasks: Card[] = []
for (let i = 0; i < payload.day.tasks.length; i++) {
const task = payload.day.tasks[i]
if(payload.task != task) {
leftOverTasks.push(task)
}
}
payload.day.tasks = leftOverTasks
},
acceptFirstEvent: function (state: AppState) {
const event = state.announcements.shift()
if(!event) { return }
event.onAccept(state.businessObject)
state.businessObject.assets.unshift(event) // Add it to our current assets
},
rejectFirstEvent: function (state: AppState) {
const event = state.announcements.shift()
event?.onReject(state.businessObject)
}
},
actions: {
startCountdown: function (context) {
context.commit('resetCountdown')
context.dispatch('tickCountdown')
},
tickCountdown: function (context) {
context.commit('tickCountdown')
if(context.state.countdownProgress <= 0) {
context.dispatch('startSimulation')
}
else {
setTimeout( () => {
context.dispatch('tickCountdown')
}, context.state.tickSpeed)
}
},
startSimulation: function (context) {
context.commit('startSimulation')
context.dispatch('tick')
},
tick: function (context) {
context.commit('tick')
if(context.state.currentDay > 13) {
setTimeout(() => {
context.dispatch('nextSprint')
}, 3000)
}
else if(!context.state.isPaused) {
setTimeout(() => {
context.dispatch('tick')
}, context.state.tickSpeed)
}
},
acceptEvent: function (context) {
context.commit('acceptFirstEvent')
context.dispatch('resumeSimulation')
},
rejectEvent: function (context) {
context.commit('rejectFirstEvent')
context.dispatch('resumeSimulation')
},
resumeSimulation: function (context) {
if(context.state.hasStarted) {
context.commit('clearAnnouncements')
context.commit('unpause')
context.dispatch('tick')
}
},
nextSprint: function (context) {
context.commit('nextSprint')
context.dispatch('startCountdown')
}
}
})
|
C#
|
UTF-8
| 398
| 2.96875
| 3
|
[] |
no_license
|
string input = // ...
string pattern = @"(\w{1,3} )?1?\d: (?<line>[^\r\n]+)(\r?\n\s+(?<line>[^\r\n]+))*";
foreach (Match m in Regex.Matches(input, pattern))
{
if(m.Success)
{
string entry = string.Join(Environment.NewLine,
m.Groups["line"].Captures.Cast<Capture>().Select(x=>x.Value));
// ...
}
}
|
Ruby
|
UTF-8
| 848
| 2.5625
| 3
|
[] |
no_license
|
class Relationship < ApplicationRecord
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
validates :follower_id, presence: true
validates :followed_id, presence: true
validate :followed_is_streamer, :followed_is_not_follower
def favorite
update_attribute(:favorited, true)
end
def unfavorite
update_attribute(:favorited, false)
end
private
def followed_is_streamer
@streamer = User.where(["id = ? and streamer = ?", followed_id, true])
if @streamer.nil? || @streamer.blank?
errors.add(:followed_id, "Oh Dear (づಠ╭╮ಠ)づ You Can't Follow Non-Streamers")
end
end
def followed_is_not_follower
if followed_id == follower_id
errors.add(:followed_id, "Wow! You Must Really Think You're Something (づಠ╭╮ಠ)づ You Can't Follow Yourself")
end
end
end
|
Java
|
UTF-8
| 10,631
| 1.828125
| 2
|
[] |
no_license
|
package net.student.service.impl;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.GenericRawResults;
import com.j256.ormlite.misc.TransactionManager;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import net.student.constants.Constants;
import net.student.constants.CustomerException;
import net.student.model.FeeItem;
import net.student.model.User;
import net.student.request.JqGridQuerier;
import net.student.response.JsonResult;
import net.student.response.QueryResult;
import net.student.service.IFeeItemService;
/**
* 费用Service实现类
* @author 果冻
*
*/
@Service
public class FeeItemService implements IFeeItemService {
@Autowired
private Dao<FeeItem, String> feeItemDao;
@Override
public QueryResult<FeeItem> queryFeeItems(JqGridQuerier<FeeItem, String> querier) throws Exception {
Long page = querier.getPage();
Long rows = querier.getRows();
Long start = (page - 1) * rows;
QueryBuilder<FeeItem, String> queryBuilder = feeItemDao.queryBuilder();
Where<FeeItem, String> where = queryBuilder.where();
if (StringUtils.isNotBlank(querier.getSidx()) && StringUtils.isNotBlank(querier.getSord())) {
if (querier.getSord().equals(JqGridQuerier.ASC)) {
queryBuilder.orderBy(querier.getSidx(), true);
} else {
queryBuilder.orderBy(querier.getSidx(), false);
}
} else {
queryBuilder.orderBy("itemId", false);
}
int count = querier.transferQueryCondition(where);
if (count ==0) {
where.raw("1=1");
}
QueryResult<FeeItem> queryResult = new QueryResult<FeeItem>();
long totalRecord = feeItemDao.countOf(queryBuilder.setCountOf(true).prepare());
long totalPage = totalRecord % rows == 0 ? totalRecord / rows : totalRecord / rows + 1;
queryResult.setTotal(totalPage);
List<FeeItem> list = feeItemDao.query(queryBuilder.setCountOf(false).limit(rows).offset(start).prepare());
queryResult.setRecords(totalRecord);
queryResult.setRows(list);
queryResult.setPage(page);
return queryResult;
}
@Override
public void saveFeeItem(FeeItem feeItem) throws Exception {
long count = feeItemDao.queryRawValue("select count(1) from feeitem where itemid=?", feeItem.getItemId());
if (count > 0) {
throw new CustomerException("feeItem.message.duplicateId");
}
count = feeItemDao.queryRawValue("select count(1) from feeitem where itemname=?", feeItem.getItemName());
if (count > 0) {
throw new CustomerException("feeItem.message.duplicateName");
}
feeItemDao.create(feeItem);
}
@Override
public void updateFeeItem(FeeItem feeItem) throws Exception {
long count = feeItemDao.queryRawValue("select count(1) from feeitem where itemname=? and itemid<>?", feeItem.getItemName(), feeItem.getItemId());
if (count > 0) {
throw new CustomerException("feeItem.message.duplicateName");
}
FeeItem oldOne = feeItemDao.queryForId(feeItem.getItemId());
feeItem.setCreatedDate(oldOne.getCreatedDate());
feeItemDao.update(feeItem);
}
@Override
public void delFeeItem(String ids) throws Exception {
String[] feeItemIds = ids.split(",");
List<Integer> idList = new ArrayList<Integer>();
for (String feeItemId : feeItemIds) {
long count = feeItemDao.queryRawValue("select count(1) from payment where itemid = " + feeItemId);
if (count == 0) {
count = feeItemDao.queryRawValue("select count(1) from userfeeitem where itemid = " + feeItemId);
if (count == 0) {
count = feeItemDao.queryRawValue("select count(1) from paidlog where itemid = " + feeItemId);
}
if (count > 0) {
continue;
}
} else {
continue;
}
idList.add(Integer.parseInt(feeItemId));
}
if (idList.size() == 0) {
throw new CustomerException("commmon.message.constraintException", "");
}
PreparedQuery<FeeItem> criteria = feeItemDao.queryBuilder().where().in("itemId", idList).prepare();
List<FeeItem> list = feeItemDao.query(criteria);
feeItemDao.delete(list);
}
@Override
public JSON selectFeeItems(User user) throws Exception {
JSONArray selectResults = new JSONArray();
JSONObject nameResult = new JSONObject();
JSONObject priceResult = new JSONObject();
List<FeeItem> list = null;
if (user.getUserType() == User.USERTYPE_ADMIN) {
list = feeItemDao.queryForAll();
} else {
list = new ArrayList<FeeItem>();
GenericRawResults<String[]> rawResult = feeItemDao.queryRaw("select f.itemid, f.itemname, f.price from feeitem f"+
" where exists (select 1 from userfeeitem u where u.userid=? and u.itemid=f.itemid)", user.getUserId().toString());
for (String[] raws : rawResult) {
FeeItem feeItem = new FeeItem();
feeItem.setItemId(raws[0]);
feeItem.setItemName(raws[1]);
feeItem.setPrice(Long.valueOf(raws[2]));
list.add(feeItem);
}
}
if (list != null) {
DecimalFormat df = new DecimalFormat("0.00");
for (FeeItem feeItem : list) {
nameResult.put(feeItem.getItemId(), feeItem.getItemName());
double price = feeItem.getPrice()/1000.00;
priceResult.put(feeItem.getItemId(), df.format(price));
}
selectResults.add(nameResult);
selectResults.add(priceResult);
}
return selectResults;
}
@Override
public JsonResult importFeeItems(InputStream is, HttpSession session) throws Exception {
JsonResult result = new JsonResult();
JSONObject jsonObject = new JSONObject();
JSONArray errorArray = new JSONArray();
JSONArray updateArray = new JSONArray();
final List<FeeItem> feeItems = new ArrayList<FeeItem>();
HSSFWorkbook wb = new HSSFWorkbook(is);
int sheetCount = wb.getNumberOfSheets();
for (int i = 0; i < sheetCount; i++) {
HSSFSheet sh = wb.getSheetAt(i);
int rowCount = sh.getLastRowNum();
for (int j = 1; j < rowCount + 1; j++) {
HSSFRow row = sh.getRow(j);
if(row == null) {
continue;
}
FeeItem feeItem = new FeeItem();
HSSFCell cell0 = row.getCell(0);
HSSFCell cell1 = row.getCell(1);
HSSFCell cell2 = row.getCell(2);
HSSFCell cell3 = row.getCell(3);
if (cell0 == null || cell1 == null || cell2 == null) {
errorArray.add("第" + (j + 1) + "行数据不完整");
continue;
}
if (cell0.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
feeItem.setItemId(StringUtils.trim(BigDecimal.valueOf(cell0.getNumericCellValue()).toPlainString()));
} else {
feeItem.setItemId(StringUtils.trim(cell0.getStringCellValue()));
}
feeItem.setItemName(StringUtils.trim(row.getCell(1).getStringCellValue()));
if (cell2.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
feeItem.setPrice(Math.round(cell2.getNumericCellValue() * 1000));
} else if (StringUtils.isNotBlank(cell2.getStringCellValue())){
feeItem.setPrice(Math.round(Double.valueOf(cell2.getStringCellValue()) * 1000));
}
feeItem.setRemark(StringUtils.trim(cell3.getStringCellValue()));
if (StringUtils.isBlank(feeItem.getItemId()) || StringUtils.isBlank(feeItem.getItemName())
|| feeItem.getPrice() == null) {
errorArray.add("第" + (j + 1) + "行数据不完整");
continue;
}
feeItems.add(feeItem);
}
}
wb.close();
is.close();
Date now = new Date();
if (feeItems.isEmpty()) {
result.setSuccess(false);
jsonObject.put("msg", "excel文件数据不合法");
} else {
List<FeeItem> oldFeeItems = feeItemDao.queryForAll();
int newCount = 0;
for (FeeItem feeItem : feeItems) {
int index = oldFeeItems.indexOf(feeItem);
if (index != -1) {
FeeItem oldOne = oldFeeItems.get(index);
feeItem.setCreatedDate(oldOne.getCreatedDate());
feeItem.setLastUpdatedDate(now);
updateArray.add(feeItem.getItemId());
} else {
feeItem.setCreatedDate(now);
newCount++;
}
}
if (updateArray.size() > 0) {
session.setAttribute(Constants.SESSION_IMPORT_FEEITEM_NAME, feeItems);
result.setSuccess(false);
} else {
TransactionManager.callInTransaction(feeItemDao.getConnectionSource(), new Callable<Void>() {
public Void call() throws Exception {
for (FeeItem feeItem : feeItems) {
feeItemDao.create(feeItem);
}
return null;
}
});
result.setSuccess(true);
jsonObject.put("msg", "新增收费项目" + newCount + "条");
}
}
jsonObject.put("errors", errorArray);
jsonObject.put("confirms", updateArray);
result.setInfo(jsonObject);
return result;
}
@Override
public JsonResult importFeeItems(final List<FeeItem> feeItems) throws Exception {
JsonResult result = new JsonResult();
List<FeeItem> oldFeeItemList = feeItemDao.queryForAll();
int newCount = 0,updateCount = 0;
Date now = new Date();
for (FeeItem feeItem : feeItems) {
int index = oldFeeItemList.indexOf(feeItem);
if (index != -1) {
FeeItem oldOne = oldFeeItemList.get(index);
feeItem.setCreatedDate(oldOne.getCreatedDate());
feeItem.setLastUpdatedDate(now);
updateCount++;
} else {
feeItem.setCreatedDate(now);
newCount++;
}
}
TransactionManager.callInTransaction(feeItemDao.getConnectionSource(), new Callable<Void>() {
public Void call() throws Exception {
for (FeeItem feeItem : feeItems) {
feeItemDao.createOrUpdate(feeItem);
}
return null;
}
});
result.setSuccess(true);
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg", "新增收费项目" + newCount + "条, 更新收费项目" + updateCount + "条");
result.setInfo(jsonObject);
return result;
}
}
|
SQL
|
UTF-8
| 3,491
| 4.09375
| 4
|
[] |
no_license
|
DROP DATABASE IF EXISTS exampledb;
CREATE DATABASE exampledb
DEFAULT CHARACTER SET utf8
DEFAULT COLLATE utf8_general_ci;
CREATE TABLE IF NOT EXISTS `exampledb`.`student` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `name_UNIQUE` (`name` ASC))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `exampledb`.`teacher` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `name_UNIQUE` (`name` ASC))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `exampledb`.`course` (
`id` INT NOT NULL AUTO_INCREMENT,
`title` VARCHAR(45) NULL,
`teacher_id` INT NOT NULL,
PRIMARY KEY (`id`, `teacher_id`),
UNIQUE INDEX `title_UNIQUE` (`title` ASC),
INDEX `fk_course_teacher1_idx` (`teacher_id` ASC),
CONSTRAINT `fk_course_teacher1`
FOREIGN KEY (`teacher_id`)
REFERENCES `exampledb`.`teacher` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `exampledb`.`student_has_course` (
`student_id` INT NOT NULL,
`course_id` INT NOT NULL,
PRIMARY KEY (`student_id`, `course_id`),
INDEX `fk_student_has_course_course1_idx` (`course_id` ASC),
INDEX `fk_student_has_course_student_idx` (`student_id` ASC),
CONSTRAINT `fk_student_has_course_student`
FOREIGN KEY (`student_id`)
REFERENCES `exampledb`.`student` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_student_has_course_course1`
FOREIGN KEY (`course_id`)
REFERENCES `exampledb`.`course` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
INSERT INTO `exampledb`.`student` (`name`) VALUES ('Роман Нордштрем');
INSERT INTO `exampledb`.`student` (`name`) VALUES ('Елена Соловьева');
INSERT INTO `exampledb`.`student` (`name`) VALUES ('Яна Петрова');
INSERT INTO `exampledb`.`student` (`name`) VALUES ('Михаил Волынов');
INSERT INTO `exampledb`.`student` (`name`) VALUES ('Дмитрий Комбаров');
INSERT INTO `exampledb`.`student` (`name`) VALUES ('Кирилл Комбаров');
INSERT INTO `exampledb`.`teacher` (`name`) VALUES ('Александр Емелин');
INSERT INTO `exampledb`.`teacher` (`name`) VALUES ('Александр Жебрак');
INSERT INTO `exampledb`.`course` (`title`, `teacher_id`) VALUES ('Python', 1);
INSERT INTO `exampledb`.`course` (`title`, `teacher_id`) VALUES ('Mobile Development', 2);
INSERT INTO `exampledb`.`course` (`title`, `teacher_id`) VALUES ('Machine Learning', 2);
INSERT INTO `exampledb`.`student_has_course` (`student_id`, `course_id`) VALUES (1, 1);
INSERT INTO `exampledb`.`student_has_course` (`student_id`, `course_id`) VALUES (2, 1);
INSERT INTO `exampledb`.`student_has_course` (`student_id`, `course_id`) VALUES (3, 1);
INSERT INTO `exampledb`.`student_has_course` (`student_id`, `course_id`) VALUES (4, 1);
INSERT INTO `exampledb`.`student_has_course` (`student_id`, `course_id`) VALUES (2, 2);
INSERT INTO `exampledb`.`student_has_course` (`student_id`, `course_id`) VALUES (2, 3);
# Показываем SELECT
# Показываем ORDER_BY
# Показываем WHERE
# JOIN student+student_has_course
# LEFT JOIN student+student_has_course
# JOIN course+teacher
# Показываем студентов, не участвующих ни в одном курсе 2мя способами (LEFT JOIN с условием или NOT IN)
# Выбираем преподов и кол-во курсов, которые они преподают (SELECT name, COUNT(teacher_id) FROM teacher LEFT JOIN course on teacher.id=course.teacher_id GROUP BY course.teacher_id;)
|
C
|
UTF-8
| 3,930
| 2.703125
| 3
|
[] |
no_license
|
/** Converts an integer to an ASCII string with the given radix.
@file itoa.c
@ingroup misclib
@author Christian Dönges <cd@platypus-projects.de>
@note The master repository for this file is at
<a href="https://github.com/cdoenges/misclib">https://github.com/cdoenges/misclib</a>
LICENSE
This software is open source software under the "Simplified BSD License"
as approved by the Open Source Initiative (OSI)
<http://opensource.org/licenses/bsd-license.php>:
Copyright (c) 2011, Christian Doenges (Christian Dönges) All rights
reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Platypus Projects GmbH nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <assert.h>
#include <errno.h>
#include "itoa.h"
char *intoa(int value, char *pDst, size_t buflen, int base) {
char const *digitToAscii = "0123456789abcdef";
char *ptr = pDst;
char *pR;
int tmp;
assert(NULL != pDst);
assert(buflen > 0);
// Check if base is valid.
if ((base < 2) || (base > 16)) {
errno = EINVAL;
return NULL;
}
do {
int digit;
if (0 == buflen--) {
return NULL;
}
tmp = value;
value /= base;
digit = tmp - value * base;
*ptr++ = digitToAscii[digit];
} while (0 != value);
// Handle negative numbers.
if (tmp < 0) {
if (0 == buflen--) {
return NULL;
}
*ptr++ = '-';
} // if negative
if (0 == buflen--) {
return NULL;
}
*ptr++ = '\0'; // Terminate string.
// Reverse the string.
pR = pDst;
while (pR < ptr) {
char currentchar = *ptr;
*ptr-- = *pR;
*pR++ = currentchar;
}
return pDst;
} // intoa()
char *itoa(int value, char *pDst, int base) {
char const *digitToAscii = "0123456789abcdef";
char *ptr = pDst;
char *pR;
int tmp;
assert(NULL != pDst);
// Check if base is valid.
if ((base < 2) || (base > 16)) {
errno = EINVAL;
return NULL;
}
do {
int digit;
tmp = value;
value /= base;
digit = tmp - value * base;
*ptr++ = digitToAscii[digit];
} while (0 != value);
// Handle negative numbers.
if (tmp < 0) {
*ptr++ = '-';
}
*ptr-- = '\0'; // Terminate string.
// Reverse the string.
pR = pDst;
while (pR < ptr) {
char currentchar = *ptr;
*ptr-- = *pR;
*pR++ = currentchar;
}
return pDst;
} // itoa()
|
Python
|
UTF-8
| 17,791
| 3.515625
| 4
|
[
"MIT"
] |
permissive
|
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.7.1
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Finite Square Well Potential
# Here are some plots and code related to the PHAS0004: Atoms, Stars and the Universe course as taught in 2020 to the first year students of UCL Physics and Astronomy. In this note book we are going to be looking at the finite square well potential.
# +
import numpy as np #import the numpy library as np
import matplotlib.pyplot as plt #import the pyplot library as plt
import matplotlib.style #Some style nonsense
import matplotlib as mpl #Some more style nonsense
import math #Import math so that math.pi can be used
import scipy.constants #Import scipy.constants so that hbar and electron_mass can be used
from scipy.optimize import fsolve # Import fsolve for the numerical solving
from scipy import integrate # Import integrate for numerical integration
#Set default figure size
#mpl.rcParams['figure.figsize'] = [12.0, 8.0] #Inches... of course it is inches
mpl.rcParams["legend.frameon"] = False #Turn off the box around the legend
mpl.rcParams['figure.dpi']=150 # dots per inch
# -
# ## Finite square well potential
#
# During the course we discussed the infinite square well potential, which had a potential of the form
# $$V(x)=\begin{cases}
# 0 & \text{if } 0 \leq x \leq L \\
# U & \text{otherwise}
# \end{cases}$$
#
# Now we will try and plot this function..
# +
#Define a function which will operate on an array of x values all at once
def finiteV(x):
conds = [x < 0, (x >= 0) & (x <= 1), x > 1] #The three regions of x
funcs = [lambda x: 1000, lambda x: 0, # #0 in the middle and 1000 outsides
lambda x: 1000] #the lambda keyword is allowing us to define a quick function
return np.piecewise(x, conds, funcs) #Now do the piecewise calculation and return it
# +
#Now let's plot our potential
fig, ax = plt.subplots() #I like to make plots using this silly fig,ax method but plot how you like
x = np.linspace(-0.5, 1.5, 1000) # 1000 x values between -0.5 and 1.5
ax.fill_between(x,finiteV(x),0) #Fill between the V(x) values and 0
ax.set_title(r"Finite Square Well") #Set the plot title
ax.set_xlabel("$x / L$") # Set the x-axis label
ax.set_ylabel("$V(x)$") # Set the y-axis label
ax.set_yticklabels([]) #Remove the y-axis label as w
ax.annotate(r'$V(x)=U$', xy=(1.25,500), xycoords="data", #Label on right-hand side
va="center", ha="center",c="w") #horizontal and vertical alignment and color=white
ax.annotate(r'$V(x)=0$', xy=(0.5,500), xycoords="data", #Label in middle side
va="center", ha="center") #horizontal and vertical alignment
ax.annotate(r'$V(x)=U$', xy=(-0.25,500), xycoords="data", #Label on left-hand side
va="center", ha="center",c="w") #horizontal and vertical alignment and color=white
ax.annotate(r'Region C', xy=(1.25,300), xycoords="data", #Label on right-hand side
va="center", ha="center",c="w") #horizontal and vertical alignment and color=white
ax.annotate(r'Region B', xy=(0.5,300), xycoords="data", #Label in middle side
va="center", ha="center") #horizontal and vertical alignment
ax.annotate(r'Region A', xy=(-0.25,300), xycoords="data", #Label on left-hand side
va="center", ha="center",c="w") #horizontal and vertical alignment and color=white
# -
# ## TISE in the Finite Square Well
#
# The Time Independent Schrödinger Equation (TISE) in Regions A & C is given by:
# $$ -\frac{\hbar^2}{2m} \frac{\partial^2 \psi(x)}{\partial x^2} +U \psi(x) = E \psi(x)$$
# which can be rewritten as:
# $$ \frac{\partial^2 \psi(x)}{\partial x^2} = \frac{2m}{\hbar^2}\left(U-E\right) \psi(x)$$
#
# In Region B the TISE is
# $$ \frac{\partial^2 \psi(x)}{\partial x^2} = -\frac{2m}{\hbar^2} E \psi(x)$$
#
#
#
#
# ## Solutions in the finite well
#
# There are two cases for the solution $E>U$ and $E<U$, lets start with the second one since that is more fun.
# ### Case: $E<U$
# In this case it is convenient to define a new parameter $k_0^2 = \frac{2m}{\hbar^2}\left(U -E\right)$ so that we can write the TISE in Regions A&C as:
# $$ \frac{\partial^2 \psi(x)}{\partial x^2} = k_0^2 \psi(x)$$
# The general solutions in these regions are of the form
# $$\psi_A(x) = A \exp(- k_0 x) + B \exp(+ k_0 x)~~~~~~~~~~x<0$$
# $$\psi_C(x) = F \exp(- k_0 x) + G \exp(+ k_0 x)~~~~~~~~~~x>L$$
#
# We will also define another new parameter $k_1^2 =\frac{2m}{\hbar^2} E $ which lets us write the TISE in Region B as
# $$ \frac{\partial^2 \psi_B(x)}{\partial x^2} = -k_1^2 \psi_B(x) ~~~~~~~~~~ 0 \leq x \leq L$$
# The general solutions in this region is of the form
# $$\psi_B(x) = C \sin (k_1 x) + D \cos (k_1 x)$$
#
# #### How many unknowns?
# We have 7 unknowns, $A,B,C,D,F,G$ and the energy $E$. So lets start trying to constrain some of these variables.
#
# Firtsly we know that our wavefunctions must remain finite everywhere if they are to be normalisable. The exponential wavefunctions have the capability of growing exponentially (as we sadly hear daily on the news). So, in region A $(x<0)$ we must set $A$ to zero to avoid an infinite wavefunction as $x\rightarrow \infty$ and in region C ($x>L$) we must set $G$ to zero to avoid an infinite wavefunction as $x\rightarrow -\infty$. This means the wavefunctions in those regions are
# $$ \psi_A(x) = B \exp(+ k_0 x)~~~~~~~~~~x<0$$
# $$\psi_C(x) = F \exp(- k_0 x)~~~~~~~~~~x>L$$
#
# #### Boundary conditions
# We need to require the wavefunctions and the first derivatives of the wavefunctions to be continuous, particularly at $x=0$ and $x=L$.
#
# ##### Boundary conditions at $x=0$
# $$\psi_A(0) = \psi_B(0)$$
# $$B = D$$
# So we can write
# $$ \psi_A(x) = D \exp(+ k_0 x)~~~~~~~~~~x<0$$
# then we can take the first derivatives in all three regions
# $$ \frac{\partial \psi_A(x)}{\partial x} = D k_0 \exp(+ k_0 x)$$
# $$ \frac{\partial \psi_B(x)}{\partial x} = C k_1 \cos( k_1 x) - D k_1 \sin( k_1 x)$$
# $$ \frac{\partial \psi_C(x)}{\partial x} = -F k_0 \exp(- k_0 x)$$
# Applying the boundary condition at $x=0$ we get
# $$ \frac{\partial \psi_A(0)}{\partial x} = \frac{\partial \psi_B(0)}{\partial x}$$
# $$ D k_0 = C k_1 $$
# $$ C = \frac{k_0}{k_1} D $$
# Which allows us to write
# $$\psi_B(x) = \frac{k_0}{k_1} D \sin (k_1 x) + D \cos (k_1 x)$$
# $$ \frac{\partial \psi_B(x)}{\partial x} = D k_0 \cos( k_1 x) - D k_1 \sin( k_1 x)$$
#
# So we have elimated four of the seven unknowns. But to fix the remaining ones is much more complicated.
#
# ##### Boundary conditions at $x=L$
# $$\psi_B(L) = \psi_C(L)$$
# $$ \frac{k_0}{k_1} D \sin (k_1 L) + D \cos (k_1 L) = F \exp(- k_0 L)$$
# and
# $$ \frac{\partial \psi_B(L)}{\partial x} = \frac{\partial \psi_C(L)}{\partial x} $$
# $$ D k_0 \cos( k_1 L) - D k_1 \sin( k_1 L) = -F k_0 \exp(- k_0 L)$$
#
# ## Now it gets messy (yes even messier -- everything below here is not examinable material)
# So let's try and divide the two big messy equations above
# $$ \frac{\frac{k_0}{k_1} D \sin (k_1 L) + D \cos (k_1 L)}{ D k_0 \cos( k_1 L) - D k_1 \sin( k_1 L)} = \frac{F \exp(- k_0 L)}{-F k_0 \exp(- k_0 L)} $$
#
# $$ \frac{k_0 \sin (k_1 L) + k_1 \cos (k_1 L)}{ k_0 k_1 \cos( k_1 L) - k_1^2 \sin( k_1 L)} = \frac{ 1}{- k_0 } $$
#
# $$ k_0^2 \sin (k_1 L) + k_0 k_1 \cos (k_1 L) = -k_0 k_1 \cos( k_1 L) + k_1^2 \sin( k_1 L) $$
#
# $$ k_0^2 \tan (k_1 L) + k_0 k_1 = -k_0 k_1 + k_1^2 \tan( k_1 L) $$
# $$ 2 k_0 k_1 = \left(k_1^2 - k_0^2 \right) \tan( k_1 L) $$
# Now we can insert our definitions of $k_0$ and $k_1$
# $$ 2 \sqrt{\frac{2m}{\hbar^2}\left(U -E\right) } \sqrt{\frac{2m}{\hbar^2} E} = \left[ \frac{2m}{\hbar^2} E - \frac{2m}{\hbar^2}\left(U -E\right) \right] \tan\left(\sqrt{\frac{2m}{\hbar^2} E} L \right) $$
# $$ 2 \frac{\sqrt{\left(U-E\right)E}}{2E - U} = \tan\left(\sqrt{\frac{2m}{\hbar^2} E} L \right) $$
#
# Now, obviously this is a somewhat terrifying mess. But if we pause for a second then we realise that on the left hand side we just have a function of $U$ and $E$, which is obvioulsy only valid for $E < U$. The right hand side is just a functon of $E$ and the particle mass, $m$ and well width $L$.
#
# ### Let's find some solutions
# Obvioulsy the solutions to this equation are when the left hand side is equal to the right hand side. This equaiton has to be solved either graphically or numerically. We will illustrate both below.
#
#
#
# +
#Define functions of E that will be the LHS and RHS of the above
#Energy in eV... although it doesn't actually matter as long as E and U are
# in the same units as this function ends up dimensionless
def LHS(E,U):
return (2*np.sqrt((U-E)*E)/(2*E-U))
#Energy in eV, distance in m, mass in kg
def RHS(E,L,m):
return (np.tan(np.sqrt(2*m*E*scipy.constants.eV/(scipy.constants.hbar**2))*L))
# -
# ### Let's plot those functions
# To plot these functions we need to define the size and width of our well, and also define our particle mass.
# - Width = 0.5nm
# - Height = 25eV
# - Mass = electron mass
#
# Since the well is only 25eV high these solutions are only valid up to E=25eV, since particles above that energy would be free particles.
# +
#Now let's LHS and RHS and see where they cross
fig, ax = plt.subplots() #I like to make plots using this silly fig,ax method but plot how you like
eInEv = np.linspace(0.5, 25, 10000) # 1000 E values between 0.5eV and 25eV
#Precompute the LHS and RHS to remove the poles
lhs=LHS(eInEv,25) # LHS of the equation
lhs[:-1][np.diff(lhs) > 0] = np.nan #Insert a not a number when it changes from -ve to +ve
rhs=RHS(eInEv,0.5e-9,scipy.constants.electron_mass) # RHS of the equation
rhs[:-1][np.diff(rhs) < 0] = np.nan #Insert a not a number when it changes from +ve to -ve
ax.plot(eInEv,lhs,linewidth=3,label="LHS") # Plot the LHS
ax.plot(eInEv,rhs,linewidth=3,label="RHS") # Plot the RHS
ax.set_title(r"Finite Square Well (0.5nm, U=25eV, electron)") # Set the plot title
ax.set_xlabel("$E (eV)$") # Set the x-axis label
plt.legend() # Show the legend
ax.set_ylim(-10,10) # Set the y-axis range from -10 to 10
# -
# ## There are just 5 solutions!
# The five crossing points above are the *only* five solutions to this particular finite square well problem. We could zoom in to find out the exact crossing point or we could use some form of numerical solution.
# +
#Define a function which is LHS-RHS, so when this function is zero we have our solutions
def solveMe(E,*args): #A function with a number of arguments that will be unpacked on the next line
U,L,m=args # Convert the args variable into it's three sub components U, L and m
return LHS(E,U)-RHS(E,L,m) # return LHS-RHS
EGuess=[1,4,10,17,24] # These are numbers from the above plot which are close to the crossing points
EList=np.zeros(len(EGuess)) # Make an empty array to fill with the energies of allowed states
for i in range(len(EGuess)): # Loop from i = 0 to i< length(EGuess) [currently 5]
Et = fsolve(solveMe, EGuess[i], args=(25,0.5e-9,scipy.constants.electron_mass)) # Find root where LHS=RHS
EList[i]=Et # Place ROOT into Elist
print(EList) # Print the 5 allowed energies of bound states
# -
# ## What about the wave functions?
#
# Having our numerical results for the energy we can plot our wavefunctions as a function of position $x$.
#
#
# +
#Define a function which will piecewise return the finite square well solutions
def finitePsi(x,D,E,U,L,m):
k0=np.sqrt(2*m*(U-E)*scipy.constants.eV/(scipy.constants.hbar**2)) #k_0=sqrt(2m(U-E)/hbar^2)
k1=np.sqrt(2*m*E*scipy.constants.eV/(scipy.constants.hbar**2)) #k_1=sqrt(2mE/hbar^2)
F=((k0/k1)*D*np.sin(k1*L)+D*np.cos(k1*L))/np.exp(-k0*L) # F is a mess, see above
conds = [x < 0, (x >= 0) & (x <= L), x > L] #The three regions of x
funcs = [lambda x: D*np.exp(k0*x), #Wavefunction in region A
lambda x: (k0*D*np.sin(k1*x)/k1) + D*np.cos(k1*x), #Wavefunction in region B
lambda x: F*np.exp(-k0*x)] #Wavefunction in region C
return np.piecewise(x, conds, funcs) #Now do the piecewise calculation and return it
#The PDF is just the square of the waveform
def finitePDF(x,D,E,U,L,m):
return finitePsi(x,D,E,U,L,m)**2
# +
#Now let's plot our first 4 probability density functions
fig, ax = plt.subplots() #I like to make plots using this silly fig,ax method but plot how you like
x = np.linspace(-0.5e-9, 1e-9, 1000) #1000 x-values from -0.5nm to 1nm
scaleList=[]
for i in range(4):
tot,err=integrate.quad(finitePDF,-1e-9,1.5e-9,args=(1.,EList[i],25,0.5e-9,scipy.constants.electron_mass))
scaleList.append(np.sqrt(tot))
ax.plot(x,finitePsi(x,1./scaleList[i],EList[i],25,0.5e-9,scipy.constants.electron_mass),linewidth=2,label="n="+str(i+1))
ax.axvline(x=0,linestyle=":",color="black")
ax.axvline(x=0.5e-9,linestyle=":",color="black")
ax.set_ylim(-62000,62000)
ax.set_title(r"Finite Square Well")
ax.set_xlabel("$x / L$")
ax.set_ylabel("$\psi(x)$")
plt.legend()
# +
#Now let's plot our first 4 probability density functions
fig, ax = plt.subplots() #I like to make plots using this silly fig,ax method but plot how you like
x = np.linspace(-0.5e-9, 1.0e-9, 1000)
for i in range(4):
ax.plot(x,finitePDF(x,1./scaleList[i],EList[i],25,0.5e-9,scipy.constants.electron_mass),linewidth=1,label="n="+str(i))
ax.set_title(r"Finite Square Well")
ax.set_xlabel(r"$x$ (m)")
ax.set_ylabel(r"$\rho(x)$")
ax.axvline(x=0,linestyle=":",color="black")
ax.axvline(x=0.5e-9,linestyle=":",color="black")
plt.legend()
# -
# ### Case: $E>U$ (Mathematics non-examinable material)
# We should also, for completeness, touch upon the case where the energy of the particle exceeds the height of the potential well.
#
# The TISE in this region can be written as in terms of $k_2^2=\frac{2m(E-U)}{\hbar^2}$
# $$ \frac{\partial^2 \psi(x)}{\partial x^2} = - k_2^2 \psi(x)$$
#
# The full solution in this region needs complex numbers and will have to wait for next years course. But some observations
# - The solutions will be sinusoidal everywhere
# - The wavelength will be longer outside the well (corresponding to lower kinetic energy)
# - The solutions are not normalisable (since they are like free particle de Broglie solutions and stretch to infinite)
# - This means we can't calculate the probability distribution function
#
# The general solutions in these regions are of the form, where we have used the fact that a linear combination of sine and cosine functions is itself a sine function with a different amplitude and phase (or in fact a cosine function since a cosine function is just a sine function with a phase shift).
# $$\psi_A(x) = A \sin(k_2 x + \phi_A)~~~~~~~~~~x<0$$
# $$\psi_B(x) = B \sin(k_1 x + \phi_B)~~~~~~~~~~0<x<L$$
# $$\psi_C(x) = C \sin(k_2 x + \phi_C) ~~~~~~~~~~x>L$$
#
# In the Region A lets assume this is our input wavefunction and we can pick $A=1$ and $\phi_A=0$. The boundary conditions at $x=0$
# $$\psi_B(0)=\psi_C(0)$$
# $$0 = B \sin(\phi_B)$$
# So $\phi_B=n\pi$, but lets pick $\phi_B=0$ for simplicity.
# $$ \frac{\partial \psi_B(L)}{\partial x} = \frac{\partial \psi_C(L)}{\partial x} $$
# $$ k_2 = k1 B$$
# So $$B=k_2/k_1$$
#
#
# The boundary conditions at $x=L$ five
# $$\psi_B(L)=\psi_C(L)$$
# $$ \frac{k_2}{k_1} \sin(k_1 L) = C\sin(k_2 L + \phi_C)$$
# $$ k_2 \cos(k_1 L) = C k_2 \cos(k_2 L + \phi_C)$$
# So dividing the second equation by $k_2$ and squaring and adding them:
# $$ \frac{k_2^2}{k_1^2} \sin^2(k_1 L) + \cos^2(k_1 L) = C^2 \cos^2(k_2 L + \phi_C) + C^2 \sin^2(k_2 L + \phi_C)$$
# $$ \frac{k_2^2}{k_1^2} \sin^2(k_1 L) + \cos^2(k_1 L) = C^2 $$
#
# $$ C = \sqrt{ \frac{k_2^2}{k_1^2} \sin^2(k_1 L) + \cos^2(k_1 L)} $$
#
# Whilst dividing the equations would give
# $$ \frac{1}{k_1} \tan(k_1 L) = \frac{1}{k_2} \tan(k_2 L + \phi_C)$$
# $$ \phi_C=\arctan\left[\frac{k_2}{k_1} \tan(k_1 L)\right] - k_2 L$$
#Define a function which will piecewise return the finite square well solutions
def finitePsiUnbound(x,E,U,L,m):
k2=np.sqrt(2*m*(E-U)*scipy.constants.eV/(scipy.constants.hbar**2))
k1=np.sqrt(2*m*E*scipy.constants.eV/(scipy.constants.hbar**2))
B=k2/k1
C=np.sqrt((k2*np.sin(k1*L)/k1)**2 + np.cos(k1*L)**2)
phiC=np.arctan(k2*np.tan(k1*L)/k1)-k2*L
conds = [x < 0, (x >= 0) & (x <= L), x > L] #The three regions of x
funcs = [lambda x: np.sin(k2*x),
lambda x: B*np.sin(k1*x),
lambda x: C*np.sin(k2*x+phiC)] #the lambda keyword is allowing us to define a quick function
return np.piecewise(x, conds, funcs) #Now do the piecewise calculation and return it
fig, ax = plt.subplots() #I like to make plots using this silly fig,ax method but plot how you like
x = np.linspace(-0.5e-9, 1e-9, 1000)
eIneV=100
ax.plot(x,finitePsiUnbound(x,eIneV,25,0.5e-9,scipy.constants.electron_mass),linewidth=1,label="E="+str(eIneV)+"eV")
ax.set_title(r"Finite Square Well")
ax.set_xlabel("$x / L$")
ax.set_ylabel("$\psi(x)$")
ax.axvline(x=0,linestyle=":",color="black")
ax.axvline(x=0.5e-9,linestyle=":",color="black")
plt.legend()
# ### Final thoughts
#
# The above plot illustrates one of the features of the finite square well. As you change the energy (always keeping in mind $E>U=25$eV) you see the amplitude of the wave in the right region is sometimes smaller than the amplitude on the left. This is particularly noticeable as $E-U \rightarrow 0$
#
# This is because some of the incoming particles on the left reflect off the potential well (but to model this properly we need to use complex numbers). This effect is similar to quantum tunnelling.
|
Java
|
UTF-8
| 1,650
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
package utils;
import org.junit.Test;
import solvas.rest.utils.JsonListWrapper;
import java.util.Collection;
import static io.github.benas.randombeans.api.EnhancedRandom.random;
import static io.github.benas.randombeans.api.EnhancedRandom.randomCollectionOf;
import static org.junit.Assert.assertEquals;
/**
* Unit testing the JsonListWrapper
*/
public class JsonListWrapperTest {
@Test
public void defaultConstructor() {
Collection<Object> collection = randomCollectionOf(100,Object.class);
JsonListWrapper<Object> obj1 = new JsonListWrapper<>();
obj1.put("key", collection);
JsonListWrapper<Object> obj2 = new JsonListWrapper<>(collection, "key");
assertEquals(obj1, obj2);
}
/**
* Testing the default nokey constructor, this wraps the list under key: 'data'
*/
@Test
public void constructorWithCollectionArgument()
{
Collection<Object> collection = randomCollectionOf(100,Object.class);
JsonListWrapper<Object> listWrapper = new JsonListWrapper<>(collection);
assertEquals("wrapped collection is not correct size",((Collection)listWrapper.get("data")).size(),100);
}
/**
* Testing the constructor with a given key
*/
@Test
public void constructorWithCollectionAndKeyArguments()
{
Collection<Object> collection = randomCollectionOf(100,Object.class);
String key = random(String.class);
JsonListWrapper<Object> listWrapper = new JsonListWrapper<>(collection,key);
assertEquals("wrapped collection is not correct size",((Collection)listWrapper.get(key )).size(),100);
}
}
|
PHP
|
UTF-8
| 10,707
| 2.78125
| 3
|
[] |
no_license
|
<?php
ini_set('display_errors', 1);
ini_set('log_errors', 1);
error_reporting(E_ALL);
function connectionToDB() {
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "LauraAdrian";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
return null;
}
else {
return $conn;
}
}
function dbLogin($uName) {
$connection = connectionToDB();
if($connection != null) {
$sql = "SELECT *
FROM Users
WHERE username = '$uName'";
$resultDB = $connection->query($sql);
if ($resultDB->num_rows > 0) {
while ($row = $resultDB->fetch_assoc()) {
$response = array("firstname"=>$row["fName"], "lastname"=>$row["lName"], "uName"=>$row["username"], "uPass"=>$row["passwrd"], "status" => "SUCCESS");
}
return $response;
}
else {
return array("status" => "401");
}
}
else {
return array("status" => "500");
}
}
function dbRegister($uName, $uPass, $uL, $uF, $email) {
$connection = connectionToDB();
$sql = "SELECT *
FROM Users
WHERE username = '$uName'";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
return array("status" => "403");
}
else {
$sql2 = "INSERT INTO users (fName, lName, username, passwrd, email) VALUES ('$uF', '$uL', '$uName', '$uPass', '$email')";
if(mysqli_query($connection, $sql2)) {
$response = array("firstname"=>$uF, "lastname"=>$uL, "uName"=>$uName,"status" => "SUCCESS");
return $response;
}
else {
return array("status" => "500");
}
}
}
function dbGetPosts(){
$connection = connectionToDB();
$sql = "SELECT * FROM users JOIN posts ON users.username = posts.username";
$result = $connection->query($sql);
$response = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$currentRow = array("firstname"=>$row["fName"], "lastname"=>$row["lName"], "comment"=>$row["comment"], "postDate"=>$row["postDate"], "postID" =>$row["postID"]);
array_push($response, $currentRow);
}
return $response;
}
else {
return array("status" => "406");
}
}
function dbGetPostsDate($date){
$connection = connectionToDB();
$sql = "SELECT * FROM users JOIN posts ON users.username = posts.username WHERE posts.postDate = '$date'";
$result = $connection->query($sql);
$response = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$currentRow = array("firstname"=>$row["fName"], "lastname"=>$row["lName"], "comment"=>$row["comment"], "postDate"=>$row["postDate"], "postID" =>$row["postID"]);
array_push($response, $currentRow);
}
return $response;
}
else {
return array("status" => "407");
}
}
function dbGetReplies($idPost) {
$connection = connectionToDB();
$sql = "SELECT * FROM replies JOIN users ON replies.username = users.username AND replies.postID = '$idPost' ORDER BY replies.replyID";
$result = $connection->query($sql);
$response = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$currentRow = array("firstname"=>$row["fName"], "lastname"=>$row["lName"], "reply" => $row["reply"]);
array_push($response, $currentRow);
}
return $response;
}
else {
return array("status" => "408");
}
}
function dbGetGallery(){
$connection = connectionToDB();
$sql = "SELECT * FROM users JOIN images ON users.username = images.username";
$result = $connection->query($sql);
$response = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$currentRow = array("firstname"=>$row["fName"], "lastname"=>$row["lName"], "postDate"=>$row["postDate"], "image" => $row["image"], "imageID"=>$row["imageId"]);
array_push($response, $currentRow);
}
return $response;
}
else {
return array("status" => "410");
}
}
function dbGetGalleryDate($date) {
$connection = connectionToDB();
$sql = "SELECT * FROM users JOIN images ON users.username = images.username WHERE images.postDate = '$date'";
$result = $connection->query($sql);
$response = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$currentRow = array("firstname"=>$row["fName"], "lastname"=>$row["lName"], "postDate"=>$row["postDate"], "image" => $row["image"], "imageID"=>$row["imageId"]);
array_push($response, $currentRow);
}
return $response;
}
else {
return array("status" => "411");
}
}
function dbGetPostsU($uName) {
$connection = connectionToDB();
$sql = "SELECT * FROM users JOIN posts ON users.username = posts.username AND users.username = '$uName'";
$result = $connection->query($sql);
$response = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$currentRow = array("firstname"=>$row["fName"], "lastname"=>$row["lName"], "comment"=>$row["comment"], "postDate"=>$row["postDate"], "postID" =>$row["postID"]);
array_push($response, $currentRow);
}
return $response;
}
else {
return array("status" => "409");
}
}
function dbPost($comment, $uName) {
$connection = connectionToDB();
$sql2 = "INSERT INTO Posts (comment, username, postDATE) VALUES ('$comment', '$uName', CURRENT_DATE())";
if(mysqli_query($connection, $sql2)) {
$response = array("status" => "SUCCESS");
return $response;
}
else {
return array("status" => "412");
}
}
function dbAddReply($reply, $idPost, $uName) {
$connection = connectionToDB();
$sql2 = "INSERT INTO Replies (reply, username, postID) VALUES ('$reply', '$uName', '$idPost')";
if(mysqli_query($connection, $sql2)) {
$response = array("status" => "SUCCESS");
return $response;
}
else {
return array("status" => "413");
}
}
function dbUpdate($comment, $idPost) {
$connection = connectionToDB();
$sql2 = "UPDATE posts SET comment = '$comment' WHERE posts.postID = '$idPost'";
if(mysqli_query($connection, $sql2)) {
$response = array("status" => "SUCCESS");
return $response;
}
else {
return array("status" => "414");
}
}
function dbAddFavorite($uName, $idPost) {
$connection = connectionToDB();
$sql2 = "SELECT * FROM Favorites WHERE postID = '$idPost' AND username = '$uName'";
$result = $connection->query($sql2);
if ($result->num_rows > 0) {
return array("status" => "415");
}
else {
$sql = "INSERT INTO Favorites (username, postID) VALUES ('$uName', '$idPost')";
if(mysqli_query($connection, $sql)) {
$response = array("status" => "SUCCESS");
return $response;
}
else {
return array("status" => "416");
}
}
}
function dbGetFavorites($uName) {
$connection = connectionToDB();
$sql = "SELECT * FROM favorites f join posts p ON f.postID = p.postID join users u ON p.username = u.username WHERE f.username = '$uName'";
$result = $connection->query($sql);
$response = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$currentRow = array("firstname"=>$row["fName"], "lastname"=>$row["lName"], "comment"=>$row["comment"], "postDate"=>$row["postDate"], "postID" =>$row["postID"]);
array_push($response, $currentRow);
}
return $response;
}
else {
return array("status" => "417");
}
}
function dbDeleteFavorite($idPost) {
$connection = connectionToDB();
$sql = "DELETE FROM Favorites WHERE postID = '$idPost'";
if(mysqli_query($connection, $sql)) {
$response = array("status" => "SUCCESS");
return $response;
}
else {
return array("status" => "418");
}
}
function dbDelete($idPost) {
$connection = connectionToDB();
$sql2 = "DELETE FROM posts WHERE postID = '$idPost'";
if(mysqli_query($connection, $sql2)) {
$response = array("status" => "SUCCESS");
return $response;
}
else {
return array("status" => "419");
}
}
function dbUploadImage($username, $imageName) {
$connection = connectionToDB();
$sql = "INSERT INTO Images (username, image, postDate) VALUES ('$username', 'images/$imageName', CURRENT_DATE())";
if(mysqli_query($connection, $sql)) {
$response = array("status" => "SUCCESS");
return $response;
}
else {
return array("status" => "426");
}
}
function dbGetImagesU($uName) {
$connection = connectionToDB();
$sql = "SELECT * FROM users JOIN images ON users.username = images.username AND users.username = '$uName'";
$result = $connection->query($sql);
$response = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$currentRow = array("firstname"=>$row["fName"], "lastname"=>$row["lName"], "image"=>$row["image"], "postDate"=>$row["postDate"], "imageID" =>$row["imageId"]);
array_push($response, $currentRow);
}
return $response;
}
else {
return array("status" => "420");
}
}
function dbDeleteImage($idImage) {
$connection = connectionToDB();
$sql2 = "DELETE FROM images WHERE imageId = '$idImage'";
if(mysqli_query($connection, $sql2)) {
$response = array("status" => "SUCCESS");
return $response;
}
else {
return array("status" => "421");
}
}
function dbGetFavoriteImages($uName) {
$connection = connectionToDB();
$sql = "SELECT * FROM favoriteimages f join images i ON f.imageId = i.imageId join users u on i.username = u.username WHERE f.username = '$uName'";
$result = $connection->query($sql);
$response = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$currentRow = array("firstname"=>$row["fName"], "lastname"=>$row["lName"], "image"=>$row["image"], "postDate"=>$row["postDate"], "imageID" =>$row["imageId"]);
array_push($response, $currentRow);
}
return $response;
}
else {
return array("status" => "422");
}
}
function dbAddFavoriteImage($uName, $idImage) {
$connection = connectionToDB();
$sql2 = "SELECT * FROM FavoriteImages WHERE imageId = '$idImage' AND username = '$uName'";
$result = $connection->query($sql2);
if ($result->num_rows > 0) {
return array("status" => "423");
}
else {
$sql = "INSERT INTO FavoriteImages (username, imageId) VALUES ('$uName', '$idImage')";
if(mysqli_query($connection, $sql)){
$response = array("status" => "SUCCESS");
return $response;
}
else {
return array("status" => "424");
}
}
}
function dbDeleteFavoriteImage($idImage) {
$connection = connectionToDB();
$sql = "DELETE FROM FavoriteImages WHERE imageId = '$idImage'";
if(mysqli_query($connection, $sql)) {
$response = array("status" => "SUCCESS");
return $response;
}
else {
return array("status" => "425");
}
}
?>
|
Markdown
|
UTF-8
| 786
| 3.671875
| 4
|
[] |
no_license
|
---
title: JavaScript洗牌算法
date: 2020-01-04 08:34:20
tags: JavaScript
categories: 算法
---
#### 洗牌算法
假设有54张扑克牌,按顺序叠放,洗牌之后变成乱序,每张牌的位置随机概率是相同的。
抽象成数组乱序排序,用Math.random生成随机数,使用Fisher–Yates Shuffle的算法,复杂度为O(n)。
这个算法的思想是,数组从后向前遍历,与之前任意元素交换。
使用JavaScript代码实现如下:
```
function shuffle(arr) {
let len = arr.length
let temp
for(let i = len-1; i>=0; i--) {
let index = Math.floor(Math.random() * len);
temp = arr[i]
arr[i] = arr[index]
arr[index] = temp
}
return arr
}
let arr = []
for(i = 0; i< 54; i++) {
arr.push(i + 1)
}
shuffle(arr)
```
|
C
|
UTF-8
| 355
| 3.71875
| 4
|
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
size_t getSize(float *);
int main(void){
float array[20];
printf("\nThe number of bytes in the array is %d"
"\nTHe number os bytes returned by getSize function is %d\n", sizeof(array), getSize(array));
return 0;
}
size_t getSize(float *ptr){
return sizeof(ptr);
}
|
Go
|
UTF-8
| 984
| 2.828125
| 3
|
[] |
no_license
|
package src
import (
"fmt"
"testing"
)
func TestDES(t *testing.T) {
src := []byte("我是一个不知道有多长的明文")
key := []byte("12345678")
str := encryptoDES(src, key)
fmt.Println("加密之后的密文:" + string(str))
str = decryptoDES(str, key)
fmt.Println("解密之后的明文:" + string(str))
}
func Test3DES(t *testing.T) {
src := []byte("我是一个不知道有多长的明文")
key := []byte("12345678abcdefgh87654321")
str := encrypto3DES(src, key)
fmt.Println("加密之后的密文:" + string(str))
str = decrypto3DES(str, key)
fmt.Println("解密之后的明文:" + string(str))
}
func TestAES(t *testing.T) {
src := []byte("我是一个不知道有多长的明文")
// TODO 这里会报错,因为秘钥长度是 17 byte,去掉一个字符就好了
key := []byte("1234abcd4321dcbaw")
str := encryptoAES(src, key)
fmt.Println("加密之后的密文:" + string(str))
str = decryptoAES(str, key)
fmt.Println("解密之后的明文:" + string(str))
}
|
Markdown
|
UTF-8
| 1,848
| 3.0625
| 3
|
[] |
no_license
|
title: Baptism
date: 2014-12-11 14:58:31
tags: scripture
---
> 1 And now I speak concerning baptism. Behold, elders, priests, and teachers were baptized; and they were not baptized save they brought forth fruit meet that they were worthy of it.
>
> 2 Neither did they receive any unto baptism save they came forth with a broken heart and a contrite spirit, and witnessed unto the church that they truly repented of all their sins.
>
> 3 And none were received unto baptism save they took upon them the name of Christ, having a determination to serve him to the end.
>
> 4 And after they had been received unto baptism, and were wrought upon and cleansed by the power of the Holy Ghost, they were numbered among the people of the church of Christ; and their names were taken, that they might be remembered and nourished by the good word of God, to keep them in the right way, to keep them continually watchful unto prayer, relying alone upon the merits of Christ, who was the author and the finisher of their faith.
> ~ Moroni 6
Here is one of the best descriptions of (some of) the requirements of baptism. I think these are very important to remember because they apply not just to _getting_ baptised but also to keeping the benefits of _being_ baptised. None of them are easy to do! Having a broken heart and a contrite spirit all the time is constantly combated by the parts of our hearts that are prideful and contrite is defined as:
> Broken down with grief and penitence; deeply sorrowful for sin because it is displeasing to God; humbly and thoroughly penitent.
> ~ 1913 Webster
Maybe your better than me but I know I don't always my sins as horrible _before_ I do them. Many times is far after I say, "Yeah probably shouldn't have done that" after the fact.
How does seeing these facts effect the way you think about your baptism?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.