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
|
|---|---|---|---|---|---|---|---|
PHP
|
UTF-8
| 1,388
| 2.5625
| 3
|
[] |
no_license
|
<?php
session_start();
if (true) {
print_r( $_POST );
header("Location: http://localhost/BrokerModule1.8/BrokerModule/index.php");
update();
}
function update() {
try{
$host = "localhost";
$port = "5432";
$dbUsername = "postgres";
$dbPassword = "password";
$dbname = "broker";
//create connection
$conn = pg_connect("host={$host} port={$port} dbname={$dbname} user={$dbUsername} password={$dbPassword}");
} catch (PDOException $e) {
echo "Error : " . $e->getMessage() . "<br/>";
die();
}
$email = $_SESSION['Email'];
//to prevent from pgsqli injection
$email = pg_escape_string(stripcslashes($email));
$address1=$_POST['address1'];
$address2=$_POST['address2'];
$city=$_POST['city'];
$state=$_POST['state'];
$pincode=$_POST['pin'];
$experience=$_POST['exp'];
$sql = $conn->prepare("update register set address1=?, address2=?, city=?, state=?, pincode=?, experience=? where email = ?");
$sql->execute([
$address1,
$address2,
$city,
$state,
$pincode,
$experience,
$email,
]);
}
?>
|
PHP
|
UTF-8
| 305
| 2.625
| 3
|
[] |
no_license
|
<?php
namespace Foundation\Form\Filter;
/**
* Replace elements of a string
*
* @package Foundation\form\filter
*/
class Replace extends AbstractFilter
{
public function filterValue($value)
{
return \str_replace($this->ruleSet['pattern'], $this->ruleSet['replace'], $value);
}
}
|
C#
|
UTF-8
| 3,961
| 2.921875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Minesweeper
{
public partial class Winners : Form
{
public Winners()
{
InitializeComponent();
}
public void UpdateWinnersTable()
{
Winner[] winners = Winner.GetWinnersList().OrderBy(a => a.Time).Take(10).ToArray<Winner>();
int timerValue = int.Parse(Game.GameInstance.TimerValue);
int index = -1;
// Store index of passed element.
for (int i = 0; i < winners.Length; i++)
{
if (timerValue <= winners[i].Time)
{
index = i;
break;
}
}
// Change size of Winners form and position of OK button.
this.Size = new Size(300, winners.Length * 30 + 107);
this.okPictureBox.Location = new Point(220, winners.Length * 30 + 41);
Label[] labelsArray = new Label[]
{
this.winnerOneLabel,
this.winnerTwoLabel,
this.winnerThreeLabel,
this.winnerForeLabel,
this.winnerFiveLabel,
this.winnerSixLabel,
this.winnerSevenLabel,
this.winnerEightLabel,
this.winnerNineLabel,
this.winnerTenLabel
};
int winIndex = 0;
for (int i = 0; i < winners.Length + 1; i++)
{
if (i == index)
{
labelsArray[i].Text = string.Format("{0}. {1} sec", (i + 1).ToString(), timerValue);
this.winnerTextBox.Location = new Point(95, i * 25 + 40);
this.winnerTextBox.Visible = true;
}
else
{
labelsArray[i].Text = string.Format("{0}. {1} {2} sec", (i + 1).ToString(), winners[winIndex].Name, winners[winIndex].Time);
winIndex++;
}
}
}
public void ShowWinners()
{
Winner[] winners = Winner.GetWinnersList().OrderBy(a => a.Time).Take(10).ToArray<Winner>();
// Change size of Winners form and position of OK button.
this.Size = new Size(300, winners.Length * 30 + 107);
this.okPictureBox.Location = new Point(220, winners.Length * 30 + 41);
Label[] labelsArray = new Label[]
{
this.winnerOneLabel,
this.winnerTwoLabel,
this.winnerThreeLabel,
this.winnerForeLabel,
this.winnerFiveLabel,
this.winnerSixLabel,
this.winnerSevenLabel,
this.winnerEightLabel,
this.winnerNineLabel,
this.winnerTenLabel
};
for (int i = 0; i < winners.Length; i++)
{
labelsArray[i].Text = string.Format("{0}. {1} {2} sec", (i + 1).ToString(), winners[i].Name, winners[i].Time);
}
}
private void okPictureBox_Click(object sender, EventArgs e)
{
if (this.winnerTextBox.Text != string.Empty && Game.GameInstance.TimerValue != null)
{
Winner.AddWinner(new Winner(this.winnerTextBox.Text, int.Parse(Game.GameInstance.TimerValue)));
}
else if (this.winnerTextBox.Text == string.Empty && Game.GameInstance.TimerValue != null)
{
}
this.Close();
}
}
}
|
JavaScript
|
UTF-8
| 591
| 2.78125
| 3
|
[] |
no_license
|
const concluirTarefa = (atualiza, id) => {
const tarefaCadastradas = JSON.parse(localStorage.getItem('tarefas'))
tarefaCadastradas[id].concluida = !tarefaCadastradas[id].concluida
localStorage.setItem('tarefas', JSON.stringify(tarefaCadastradas))
atualiza()
}
const BotaoConcluir = (atualiza, id) => {
const btnconcluir = document.createElement('button')
btnconcluir.addEventListener('click', ()=>concluirTarefa(atualiza, id))
btnconcluir.classList.add('check-button')
btnconcluir.innerText = 'Concluir'
return btnconcluir
}
export default BotaoConcluir
|
Java
|
UTF-8
| 2,082
| 3.125
| 3
|
[] |
no_license
|
package com.revature.ui.client;
import com.revature.model.Client;
import com.revature.services.bankServices.BankServices;
import com.revature.ui.menu.Menu;
import org.apache.log4j.Logger;
public class TransferMoneyMenu implements Menu {
private static Logger log = Logger.getLogger(TransferMoneyMenu.class);
BankServices bankServices;
Client receiver = null;
double transferAmount;
private Client sender;
public TransferMoneyMenu(Client sender) {
super();
this.sender = sender;
bankServices = new BankServices();
}
@Override
public void display() {
int choice = 0;
do {
System.out.println();
log.info(" === Transfer Funds === ");
log.info("=========================");
System.out.println();
log.info("1. Send Money");
log.info("2. Receive Money");
log.info("3. Back");
try {
choice = Integer.parseInt(userInput.nextLine());
} catch (Exception e) {
}
switch (choice) {
case 1:
log.info("Send Money");
receiver = getReceiverAccountInput();
transferAmount = getTransferAmount();
bankServices.transferFunds(sender, receiver, transferAmount);
break;
case 2:
log.info("Receive Money");
break;
default:
break;
}
} while (choice != 3);
}
public Client getReceiverAccountInput(){
Client receiveUser = null;
log.info("Enter Recipient Username: ");
String recipientUsername = userInput.nextLine();
receiveUser = new Client(recipientUsername);
return receiveUser;
}
public double getTransferAmount(){
log.info("Enter Amount of Money to transfer");
double amount = Double.parseDouble(userInput.nextLine());
return amount;
}
}
|
PHP
|
UTF-8
| 497
| 3.34375
| 3
|
[] |
no_license
|
<?php
abstract class Recorrido {
protected $barrio = NULL;
protected $punto = NULL;
public function __construct($recorrido) {
if (!empty($recorrido)) {
$this->barrio = substr($recorrido, 0, 2);
$puntoSize = sizeof($recorrido) - sizeof($this->barrio); // should be sizeof($id) -2;
$this->punto = substr($recorrido, -$puntoSize;
}
}
public function getPunto() {
return $this->punto;
}
public function getBarrio() {
return $this->barrio;
}
}
?>
|
Markdown
|
UTF-8
| 7,516
| 3.109375
| 3
|
[] |
no_license
|
一六四
“如果姑娘看得起,就给我一名副会主干。否则,即使把我降为堂主,我也心甘情愿。”
白素娟再扫视四名堂主一眼,道:“你们呢?”
四名堂主几乎是齐声道:“只要饶我们不死,我们都愿降级听用。”
白素娟有些犹豫,望向罗奇道:“罗大哥看该怎么办?”
罗奇不动声色道:“一切应由姑娘自行决定,不过姑娘必须想到后果。”
洪大全心里一急,叫道:“罗大侠,你……你要帮洪某讲几句话!”
罗奇哼了声道:“洪大全,在下和白姑娘都不只一次的吃过你的亏,像你这种人,我有必要帮你讲话吗?”
洪大全双颊抽搐着道:“洪某从前……错了……今后归附白……会主,一定竭诚尽忠,若再有三心二意,天诛地灭!”
罗奇淡然笑道:“可惜在下根本无法相信你的话。”
忽听范二叫道:“白会主,你还犹豫什么?若把他留下,等于你自己替自己留下一条祸根!”
洪大全打着哆嗦道:“范头领,咱们无怨无仇,你何苦火上加油?”
范二吼道:“谁说无怨无仇?我范二是陶大头领的忠心手下,白会主是我们大头领的表姊,这样算起来,仇恨可就大了,而且你的所作所为,我范二早已清清楚楚,难道你还不该死吗?”
洪大全脸上已由土色变得惨白,顿了顿道:“范头领,求求你,千万替洪某说几句好话……”
岂知他的话尚未说完,突见寒芒一闪,竟然人头落地。
谁都不曾想到,范二竟然自作主张,未经白素娟和陶静静同意,自行处置了洪大全。
那四名堂主以及白一忠、单大忠、黄道吉一见洪大全身首异处,倒卧在血泊中,全都惊得呆了,双腿一软,齐齐瘫跪在地上。
此刻的范二,已是杀得兴起,双目尽赤,振臂挥刀,又向四名堂主的脖子上砍去,动作快得有如风驰电掣,谁都来不及阻止。
直到四名堂主也全倒了下去,才听自素娟急急叫道:“范头领刀下留人,不能再杀了!”
范二这才停下手来道:“白会主,这个当然要留下,因为咱早就知道他是你堂叔,也是我们大头领的远房表叔。”
说着,抬手拍了拍白一忠肩膀道:“老小于,起来吧!算你大,咱不敢杀你,快向白会主和我们大头领求饶吧!”
只听陶静静道:“那两个也别杀了,留下他们还有用处。”
这时陈大忠早已出去招呼了几名弟兄,把洪大全和四名堂主的尸体拖到附近山上掩埋。
白一忠爬起之后,却又“噗咚”一声跪到白素娟脚下,打着冷颤道:“贤侄女……你……
你要救我一救!”
白素娟连忙拉起白一忠道:“叔父何必如此,你虽然对我无情无义,但侄女却不能不认你这位叔父。过去的事,侄女不会再计较的。”
此刻的白一忠,既感动又惭愧,面色胀得有如猪肝,只是僵在当场,却不知再说什么好白素娟冷冷望向单大忠和黄道吉道:“你们也起来!”
单大忠和黄道吉两腿发麻,好不容易刚站起来又倒了下去,咬牙咧嘴的又挣扎了半晌,才又站起,但全身仍在不停的打颤。
白素娟缓缓说道:“叔父,你现在必定已经明白,回到温宿该做些什么事了?”
白一忠不住点头道:“即使贤侄女不吩咐,这事我也会主动做的。我保证在半月之内,带着南路弟兄,前来向你归顺。”
白素娟道:“不必要他们前来了,叔父只要把南路人马全集中在温宿和拜城,我会前去接收他们的。”
接着又对单大忠和黄道吉道:“我不杀你们,是要你们协助我叔父把这件事办好,只要把事情办好,将来在红灯会仍有你们一席之地。”
单大忠和黄道吉连忙跪地叩谢。
白素娟转头交代陈大忠道:“陈叔叔先把我叔父和他们两个带下去休息,明天我还有事情对他们交代。”
陈大忠立即带着白一忠和单大忠、黄道吉出了大帐。
陶静静不解的道:“表姊为什么不要他们前来,却要到温宿和拜城接收他们呢?”
白素娟道:“这里临近伊犁,红灯会必须和官方划清界线。而最大的原因,是他们来到这里,很多问题,我都无法解决。”
“表姊有什么困难?”
“南路人马,合起来不下万人,我这里如何容纳,仅是食住两项,就难以解决。温宿和拜城是他们既有的驻地,我去接收他们,就不致发生以上两项问题。”
“表姊说得固然有理,但万一对方发生暴动,你又怎么办?”
“我想这种可能性实在太少,红灯会原是我父亲一手创立的,而且洪大全也并未尽得人心。如今洪大全已死,我去接收,可谓名正言顺,也许他们欢迎还来不及。”
“好!既然如此,小妹和手下的两千人马,就决定暂时留下来,以便随同表姊开进温宿拜城,等你接收完毕后,再返回太行山。”
“那太好了,我先谢过表妹!”
“表姊用不着客气,我自小受你照顾,如今帮你做点事,理所当然。”
“时间不早,表妹和范头领以及带来的弟兄,今晚就住在这里吧!明天我还要设筵为你接风洗尘。”
翌日中午,白素娟在大帐内席开两桌,招待陶静静、范二以及他们带来的弟兄,做陪的有三位堂主和罗奇、沙老五。
另外,连白一忠、黄道吉也被邀参加了酒筵。
酒筵散后,白一忠、单大忠、黄道吉立即赶回温宿办事。
白素娟则带着三位堂主,把陶静静、范二等人直送到那处山谷,然后又接受陶静静设筵款待,直到天晚,才返回驻地。
一月后,白一忠和单大忠亲自前来见白素娟,告知南路人马已在温宿和拜城两地集中完毕,并均已表达对白素娟竭诚拥戴意愿。
于是,白素娟在白、单两人陪同下,第二天便率领所属向温宿进发。
罗奇也带着沙老五随队前往。
陶静静也率队随行,不过到达温宿以后,她的人马并未进城,只在城郊驻扎。
白素娟很顺利的便接收了南路弟兄,而且果然受到竭诚拥戴。
陶静静直到白素娟一切安顿就绪后,才率领范二和手下两千人马回到了太行山。
至于白一忠,白素娟本来仍然安排他在会内担任副会主,但他因心中有愧,只好请辞回家乡养老。不消说,白素娟送了他一大笔盘费,并特别派出两名弟兄负责护送。
数月后,太行山传来一项消息:龙千里暴毙了。这消息对白素娟和罗奇来说,都不感到意外。因为陶静静必须除去此人,才能大权在握,重振声威,而龙千里却是应得的报应。
在这几月内,罗奇经常由伊犁到温宿来,但最近一次,却是带着沙老五、郝方和琴娜、天娜姊妹一起来的。这次来是向白素娟辞行,因为罗奇已决定抛却江湖生涯,带琴娜姊妹回到故乡过过平安日子,同时这也是对琴娜姊妹的一种补偿。至于他和白素娟之间将来是否能再续情缘,连他自己也无从说起。
|
Python
|
UTF-8
| 1,718
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
# Libraries
import h5py
from collections import namedtuple
# Helper classes
Channel_Info = namedtuple('ChannelInfo', ['digitisation', 'parange', 'offset', 'sampling_rate', 'raw_signal'])
class OsBp_FAST5():
'''
Reader class for FAST5 file from osmium-tagged oligo translocation experiments
'''
def __init__(self, filename):
'''
:param filename: String
'''
self.filename = filename
self.handle = h5py.File(filename)
def __enter__(self):
return self
def __exit__(self, exception_type, exception_value, traceback):
if self.handle:
self.handle.close()
self.filename = None
def get_channel_raw(self, channel_id):
'''
Extract raw channel data in pA
:param read_id: Int
:return: <Channel_Info>
'''
raw_obj = self.handle['Raw']
channel_name = 'Channel_' + str(channel_id)
if channel_name not in raw_obj:
raise KeyError('Channel "{}" not in: {}'.format(channel_name, self.filename))
channel_obj = raw_obj[channel_name]
# Channel information
_meta_info = channel_obj['Meta'].attrs
digi = _meta_info['digitisation']
parange = _meta_info['range']
offset = _meta_info['offset']
samprate= _meta_info['sample_rate']
# Raw signal
raw_signal = channel_obj['Signal'][()]
return Channel_Info(
raw_signal=raw_signal,
digitisation=digi,
parange=parange,
offset=offset,
sampling_rate=samprate
)
|
C#
|
UTF-8
| 2,537
| 2.609375
| 3
|
[] |
no_license
|
using DataAccess.Dao;
using EntitiesPOJO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess.Mapper
{
public class IdiomaMapper : EntityMapper, ISqlStatements, IObjectMapper
{
private const string DB_COL_IDIOMA = "Nombre_idioma";
private const string DB_COL_ID_IDIOMA = "Id";
private const string DB_COL_IDIOMAS = "IdiomaNuevo";
private const string DB_COL_POPULARIDAD = "Popularidad";
public BaseEntity BuildObject(Dictionary<string, object> row)
{
var idioma = new Idioma
{
Id = GetIntValue(row,DB_COL_ID_IDIOMA),
IdiomaNuevo = GetStringValue(row,DB_COL_IDIOMAS),
Popularidad = GetIntValue(row,DB_COL_POPULARIDAD)
};
return idioma;
}
public List<BaseEntity> BuildObjects(List<Dictionary<string, object>> lstRows)
{
var lstResults = new List<BaseEntity>();
foreach (var row in lstRows)
{
var cliente = BuildObject(row);
lstResults.Add(cliente);
}
return lstResults;
}
public SqlOperation GetCreateStatement(BaseEntity entity)
{
var operation = new SqlOperation { ProcedureName = "sp_registrar_idioma" };
var i = (Idioma)entity;
operation.AddVarcharParam(DB_COL_IDIOMA, i.IdiomaNuevo);
return operation;
}
public SqlOperation GetDeleteStatement(BaseEntity entity)
{
throw new NotImplementedException();
}
public SqlOperation GetRetriveAllStatement()
{
var operation = new SqlOperation { ProcedureName = "sp_devolver_todos_los_idiomas" };
return operation;
}
public SqlOperation GetRetriveStatement(BaseEntity entity)
{
var operation = new SqlOperation { ProcedureName = "sp_existencia_idioma" };
var i = (Idioma)entity;
operation.AddVarcharParam(DB_COL_IDIOMA,i.IdiomaNuevo);
return operation;
}
public SqlOperation GetUpdateStatement(BaseEntity entity)
{
var operation = new SqlOperation { ProcedureName = "sp_modificar_popularidad_idioma" };
var i = (Idioma)entity;
operation.AddVarcharParam(DB_COL_IDIOMA, i.IdiomaNuevo);
return operation;
}
}
}
|
Shell
|
UTF-8
| 861
| 3.65625
| 4
|
[] |
no_license
|
#!/bin/bash
CURRENT=`pwd`
cd $(dirname $0)
if [ $# != 3 ] ; then
echo Error ! $0 app.jar config_dir name
echo PORT in yml/properties file to config AND SPRING_PROFILES_ACTIVE=online
exit 1;
fi
DOCKER_NAME=$3
TAG_NAME=`date +%s`
set -e -x
TMP="/tmp/docker-template/"
rm -rf $TMP
mkdir $TMP
cp $CURRENT/$1 "$TMP/app.jar"
cp -r $CURRENT/$2 "$TMP/config/"
cp Dockerfile "$TMP/Dockerfile"
cd $TMP
sudo /usr/bin/docker build . -t $DOCKER_NAME:$TAG_NAME --build-arg JAR=app.jar
sudo /usr/bin/docker tag $DOCKER_NAME:$TAG_NAME $DOCKER_NAME:latest
sudo /usr/bin/docker ps|grep $DOCKER_NAME && sudo /usr/bin/docker stop $DOCKER_NAME
sudo /usr/bin/docker ps -a|grep $DOCKER_NAME && sudo /usr/bin/docker rm $DOCKER_NAME
sudo /usr/bin/docker run -d --net host --restart always --name $DOCKER_NAME -v /var/log/:/var/log/ $DOCKER_NAME:$TAG_NAME
rm -rf $TMP
|
Java
|
UTF-8
| 553
| 2.53125
| 3
|
[] |
no_license
|
package db.data_processing;
import org.json.simple.JSONObject;
public class Utils {
/**
* Проверка наличия искомого ключа в JSON-объекте.
*/
public static Object checkExist(String key, JSONObject params) {
if (params.containsKey(key)) {
if (params.get(key) instanceof Long) {
Long val = (Long) params.get(key);
return val.intValue();
}
return params.get(key);
} else {
return null;
}
}
}
|
Markdown
|
UTF-8
| 930
| 2.6875
| 3
|
[] |
no_license
|
# Przetwarzanie Formularza Railsowego
Załóżmy, że chcemy dodawać Diga metodą Railsową:
(uwaga, przykład trochę celowo nie zadziała w naszej aplikacji z powodu powodów :)
Między innymi dlatego, że już posiadamy Controller dla `Digs` w naszym API)
```ruby
# not an API ▼
# app/controllers/digs_controller.rb
class DigsController < ApplicationController
# this renders view with form
def new
end
# process form
def create
Dig.create!(dig_params)
# we don't return JSON, but we can redirect user (in this case to root path)
redirect_to root_path
end
private
def dig_params
...
end
end
# config/routes.rb
...
get 'digs', to: 'digs#new'
post 'digs', to 'digs#create'
...
```
```slim
# app/views/digs/new.html.slim
= form_tag digs_path do
= label_tag :title
= text_field_tag :title
br
= label_tag :body
= text_field_tag :body
br
= submit_tag 'Create'
```
|
Shell
|
UTF-8
| 122
| 2.578125
| 3
|
[
"Apache-2.0"
] |
permissive
|
#!/bin/bash
set -e
cd $(dirname $0)
if [ -z "$SKIP_VALIDATE" ]; then
./validate
./validate-ci
fi
./build
./package
|
Markdown
|
UTF-8
| 758
| 2.71875
| 3
|
[] |
no_license
|
# RateMe
The application has been created for TIN university course. RateMe application gathers information about restaurants. Everyone can see all the restaurants, its details and rating. Only logged in users can rate the restaurant. Admin can manage restaurants (CRUD operations).
## Backend Technology Stack
- Java
- Spring Boot
- Hibernate/JPA
- Spock (to be added soon!)
- JWT
- Lombok
- MySQL
## Frontend Technology Stack
- React (HTML/CSS/JS)
- Material-ui
- Bootsratp
*I am a backend developer. It means that my frontend part of application is not perfect. In some places I used bad practises - I am aware of that. Some of bad practises resulted from learning process - it was just too late to rewrite it while having lots of stuff on top of it*
|
Java
|
UTF-8
| 837
| 2.0625
| 2
|
[] |
no_license
|
package jats.utfpl.stfpl.dynexp;
import java.lang.reflect.Type;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
public class D2CimpdecDeserializer implements JsonDeserializer<D2Cimpdec> {
@Override
public D2Cimpdec deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
JsonArray jarr = json.getAsJsonArray();
JsonElement je1 = jarr.get(0);
int knd = je1.getAsInt();
JsonElement je2 = jarr.get(1);
Ci2mpdec imp = context.deserialize(je2, Ci2mpdec.class);
D2Cimpdec ret = new D2Cimpdec(knd, imp);
return ret;
}
}
|
Java
|
UTF-8
| 1,517
| 2.09375
| 2
|
[] |
no_license
|
package com.fileEncryption.joblauncher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class JobLauncherController {
@Autowired
JobLauncher jobLauncher;
@Autowired
Job job;
@GetMapping("/encryptFile")
public String encryptFileJobLauncher(@RequestParam(name="fileName") String fileName,
@RequestParam(name = "threads") String threadCount) throws Exception {
Logger logger = LoggerFactory.getLogger(this.getClass());
try {
JobParameters jobParameters = new JobParametersBuilder().addString("fileName", fileName)
.addLong("threads", Long.parseLong(threadCount)).toJobParameters();
jobLauncher.run(job, jobParameters);
} catch (Exception e) {
logger.info(e.getMessage());
}
return "Done";
}
}
|
C++
|
UTF-8
| 3,556
| 2.78125
| 3
|
[] |
no_license
|
/*************************************************************************
Trajet_Compose - Classe fille
-------------------
début : 21/11/2018
copyright : (C) 2018 par LOKUGE, RAMSAHA, DEBORD
e-mail : sadsitha97@pediatrician.com
*************************************************************************/
// Réalisation de la classe <Trajet_Compose> (fichier Trajet_Compose.cpp)--
//---------------------------------------------------------------- INCLUDE
//-------------------------------------------------------- Include système
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
//------------------------------------------------------ Include personnel
#include "Trajet.h"
#include "Trajet_Compose.h"
//------------------------------------------------------------- Constantes
//----------------------------------------------------------------- PUBLIC
//----------------------------------------------------- Méthodes publiques
void Trajet_Compose::Renvoyer(int& nombre, Trajet** Contains) //
{
for(int i =0; i< number; i++)
{
Tab[i]->Renvoyer(nombre, Contains);
}
}
const char* Trajet_Compose::get_Trans() // retourne "NA" pour les trajets composés vue qu'il n'y a pas un seul genre de moyen de transport
{
const char* ret = "NA";
return ret;
}
void Trajet_Compose::SauvTrajet(ofstream& fic, int& ref, int memberOf, int TypeTraj, int SelecVille, string villes []) const
{
int condSatisfied = 0;
if (TypeTraj!=1)
{
//verifier les villes de départ/arrivée
if (SelecVille==1)
{
if (strcmp((villes[0]).c_str(),Ville_Depart)==0)
{
condSatisfied = 1;
}
} else if (SelecVille==2)
{
if (strcmp((villes[1]).c_str(),Ville_Arrivee)==0)
{
condSatisfied = 1;
}
} else if (SelecVille==3)
{
cout << "came here" << endl;
cout << villes[0] << endl;
cout << villes[1] << endl;
cout << Ville_Depart << endl;
cout << Ville_Arrivee << endl;
if ((strcmp((villes[0]).c_str(),Ville_Depart)==0) && (strcmp((villes[1]).c_str(),Ville_Arrivee)==0))
{
cout << "cond satisfied" << endl;
condSatisfied = 1;
}
} else //if SelecVille==0
{
condSatisfied = 1;
}
if (condSatisfied==1)
{
fic << ref << "," << Nom_Trajet << "," << Ville_Depart << "," << Ville_Arrivee << "," << "NA" << "," << number << "," << memberOf << "\n";
++ref;
for (int i=0; i < number; ++i)
{
Tab[i]->SauvTrajet(fic,ref,memberOf,0,0,villes);
}
}
}
}
//-------------------------------------------- Constructeurs - destructeur
Trajet_Compose::Trajet_Compose (const char* Nom, const char* Ville_Dep, const char* Ville_Arriv, Trajet** trajets, int nums) : Trajet(Nom, Ville_Dep, Ville_Arriv), Tab(trajets), number(nums)
{
#ifdef MAP
cout << "Appel au constructeur de <Trajet_Compose>" << endl;
#endif
} //----- Fin de Trajet_Compose
Trajet_Compose::~Trajet_Compose ( )
{
for (int i=0; i<number;i++) // destruction de tous les trajets inclus dans le trajet composé
{
delete Tab[i];
}
delete [] Nom_Trajet;
free(Tab);
#ifdef MAP
cout << "Appel au destructeur de <Trajet_Compose>" << endl;
#endif
} //----- Fin de ~Trajet_Compose
//------------------------------------------------------------------ PRIVE
//----------------------------------------------------- Méthodes protégées
|
SQL
|
UTF-8
| 1,876
| 3.390625
| 3
|
[] |
no_license
|
DROP DATABASE IF EXISTS my_authorization;
CREATE DATABASE my_authorization CHARACTER SET UTF8 ;
USE my_authorization ;
CREATE TABLE role(
rid varchar(50) ,
title varchar(200) ,
CONSTRAINT pk_rid PRIMARY KEY(rid)
) engine='innodb' ;
CREATE TABLE action(
actid varchar(50) ,
title varchar(200) ,
rid varchar(50) ,
CONSTRAINT pk_actid PRIMARY KEY(actid)
) engine='innodb' ;
CREATE TABLE member_role(
mid varchar(50) ,
rid varchar(50)
) engine='innodb' ;
-- 定义角色信息
INSERT INTO role(rid,title) VALUES ('member','用户管理') ;
INSERT INTO role(rid,title) VALUES ('dept','部门管理') ;
INSERT INTO role(rid,title) VALUES ('news','新闻管理') ;
-- 定义权限信息
INSERT INTO action(actid,title,rid) VALUES ('member:add','用户追加','member') ;
INSERT INTO action(actid,title,rid) VALUES ('member:list','用户列表','member') ;
INSERT INTO action(actid,title,rid) VALUES ('member:edit','用户编辑','member') ;
INSERT INTO action(actid,title,rid) VALUES ('member:remove','用户删除','member') ;
INSERT INTO action(actid,title,rid) VALUES ('dept:list','部门列表','dept') ;
INSERT INTO action(actid,title,rid) VALUES ('dept:edit','部门编辑','dept') ;
INSERT INTO action(actid,title,rid) VALUES ('news:add','新闻追加','news') ;
INSERT INTO action(actid,title,rid) VALUES ('news:edit','新闻修改','news') ;
INSERT INTO action(actid,title,rid) VALUES ('news:audit','新闻审核','news') ;
INSERT INTO action(actid,title,rid) VALUES ('news:list','新闻列表','news') ;
-- 定义用户与角色的关系
INSERT INTO member_role(mid,rid) VALUES ('admin','member') ;
INSERT INTO member_role(mid,rid) VALUES ('admin','dept') ;
INSERT INTO member_role(mid,rid) VALUES ('admin','news') ;
INSERT INTO member_role(mid,rid) VALUES ('origin','news') ;
INSERT INTO member_role(mid,rid) VALUES ('mermaid','dept') ;
|
Markdown
|
UTF-8
| 9,458
| 3.03125
| 3
|
[] |
no_license
|
<-------------------双伪元素清除浮动 (伪元素的本质是插入一个行内元素)----------------------------------->
.clearfix:before,.clearfix:after{
content:"";
display:table;
}
.clearfix:after{
clear:both;
}`
.clearfix{
*zoom:1;
<---------------解决图片底测缝隙的问题--------------------------------------->
给 img vertical-align:middle | top 让图片不要和基线对齐
vertical-align 属性设置一个元素的垂直对齐方式。
<----------------css3背景 ------------------------------------------------------->
(一)background-clip 设置背景图像区域
border-box 背景覆盖到到边框盒
padding-box 背景覆盖到内边距框
content-box 背景覆盖到内容框
(二)background-origin 设置背景图片的定位(原点)
background-origin 指定 background-position 的属性应该相对于谁进行定位,设置的是元素背景图片的原始起始位置。
background-clip 是规定背景图可以绘制并显示的区域,background-origin 决定了背景图在哪绘制。
如果 background-origin 的范围大于 background-clip 的范围,那超出的部分则不显示。
(三)background-size 设置背景图片的大小
1. 一个值
一个百分比背景图根据当前元素的宽度设置的,高度自动
2. 两个值
背景图的宽根据当前元素的宽,高根据当前元素的高设置。
3.cover !!!!
将背景图像等比缩放到完全覆盖容器,背景图像有可能超出容器。
4. contain
将背景图像等比缩放到宽度或高度与容器的宽度或高度相等,背景图像始终被包含在容器内。
(四)background-image 可以为元素设置多个背景图
多重背景图像 允许为元素设置多个背景图像
background-image: url(),url();/*前面的在上面*/ !!!!
(五)background-position 属性设置背景图像的起始位置。 (搭配精灵图!!!!!!!! )
第一个值是水平位置,第二个值是垂直位置。如果您仅规定了一个关键词,那么第二个值将是"center"。
<-----------------------css3文字效果 ------------------------------------------------->
text-shadow: 水平位置 垂直位置 模糊距离 阴影颜色
<--------------------css3边框------------------------------------------------------>
border-radius: 左上角 右上角 右下角 左下角
box-shadow: 水平位置 垂直位置 模糊距离 阴影颜色 // 盒子阴影
border-image: 路径 铺 (repeated)、铺满 (rounded) 或拉伸 (stretched)。
<--------------------------css3过渡属性 --------------------------------------------->
transition: 要过渡的属性 (all) 花费时间 运动曲线 何时开始
【1】transition-property:
规定应用过渡效果的 CSS 属性的名称(当指定的 CSS 属性改变时,过渡效果开始),其默认值为 all 。
【2】transition-duration:
规定完成过渡效果需要的时间(单位为 s 或 ms),其默认值为 0s ,意味着如果不指定这个属性,将不会呈现过渡效果。
【3】transition-timing-function:
规定过渡效果的时间曲线。
默认 ease :慢速开始,中间变快,慢速结束;相当于 cubic-bezier(0.25, 0.1, 0.25, 1)。
可选 liner:匀速运动;相当于 cubic-bezier(0, 0, 1, 1)。
可选 ease-in:慢速开始;相当于 cubic-bezier(0.42, 0, 1, 1)。
可选 ease-out:慢速结束;相当于 cubic-bezier(0, 0, 0.58, 1)
可选 ease-in-out:慢速开始,慢速结束;相当于 cubic-bezier(0.42, 0, 0.58, 1)
可选 cubic-bezier(n, n, n, n):在 bezier 函数中自定义 0 ~ 1 之间的数值。
贝塞尔时间曲线详解。
【4】transition-delay:
规定过渡效果的延迟时间,默认为 0s 。
如果在 hover 状态下也设置了 transition 属性,则 hover 状态下的为前进状态,非 hover 状态下的为反向状态。
<------------------------------css3 2D转换--------------------------------------->
translate(x,y) 移动 x 水平移动 y 垂直移动
transform: translate(x,y) 变形: 移动; 配合过渡和动画使用 这个属性给。active 点击触发 按钮动画不错
transform: translate(-50%,-50%) /* translate 移动距离如果是 % 不是以父级宽度为准,而是以自己的宽度 可以让定位的盒子居中对齐*/
scale(x,y) 缩小 放大
rotate(deg) 旋转 //deg 是度数 正值是顺时针 负值时逆时针
transform-origin: (xx)px,top 设置变形的中心点 // 如果时 4 个角 可以用 left top 如果想要精准的我为之 可以用 px 像素
skew(deg,deg) 倾斜 注意 X 轴是右往左 y 轴是下往上
<------------------------------css3 3D转换--------------------------------------->
transform: rotateX(deg) 类似翻转
transform: rotateY 类似开合页
transform: rotateZ 三种 3d 旋转 类似平面旋转
backface-visibility: hidden; // 只要不是正面对屏幕 就隐藏 作翻转两面的效果
perspective: 1000px // 视距 距离 眼睛到屏幕的距离 视距越小透视效果越明显
transform: translate3d(x,y,z); x 和 y 可是是 px 和 % z 只能是 px z 越大 物体越大 离我们越近
<------------------------------css3 动画--------------------------------------->
// 引用动画
animation: go 2s ease 0s 2 reverse;
animation: 动画名称 动画时间 运动曲线 何时开始 播放次数(默认一次,infinite- 无限循环) 是否反方向 (alternate- 先正后反 交替)
/* 定义动画 */
@keyframes 动画名称 {
from {
transform: translateX(0);
}
to {
transform: translateX(600px);
}
}
@keyframes 动画名称 {
0% {
transform: translate3d(0,0,0);
}
20% {
transform: translate3d(700px,0,0);
}
50% {
transform: translate3d(700px,300px,0); // 如果有多组变形 用空格隔开就好了
}
70% {
transform: translate3d(0,300px,0);
}
100% {
transform: translate3d(0,0,0);
}
}
CSS 选择器有哪些
*通用选择器:选择所有元素,不参与计算优先级,兼容性 IE6+
//# X id 选择器:选择 id 值为 X 的元素,兼容性:IE6+
.X 类选择器: 选择 class 包含 X 的元素,兼容性:IE6+
X Y 后代选择器: 选择满足 X 选择器的后代节点中满足 Y 选择器的元素,兼容性:IE6+
X 元素选择器: 选择标所有签为 X 的元素,兼容性:IE6+
:link,:visited,:focus,:hover,:active 链接状态: 选择特定状态的链接元素,顺序 LoVe HAte,兼容性:IE4+
X + Y 直接兄弟选择器:在 X 之后第一个兄弟节点中选择满足 Y 选择器的元素,兼容性: IE7+
X > Y 子选择器: 选择 X 的子元素中满足 Y 选择器的元素,兼容性: IE7+
X ~ Y 兄弟: 选择 X 之后所有兄弟节点中满足 Y 选择器的元素,兼容性: IE7+
[attr]:选择所有设置了 attr 属性的元素,兼容性 IE7+
[attr=value]:选择属性值刚好为 value 的元素
[attr~=value]:选择属性值为空白符分隔,其中一个的值刚好是 value 的元素
[attr|=value]:选择属性值刚好为 value 或者 value- 开头的元素
[attr^=value]:选择属性值以 value 开头的元素
[attr$=value]:选择属性值以 value 结尾的元素
[attr=value]*:选择属性值中包含 value 的元素
[:checked]:选择单选框,复选框,下拉框中选中状态下的元素,兼容性:IE9+
X:after, X::after:after 伪元素,选择元素虚拟子元素(元素的最后一个子元素),CSS3 中:: 表示伪元素。兼容性:after 为 IE8+,::after 为 IE9+
:hover:鼠标移入状态的元素,兼容性 a 标签 IE4+, 所有元素 IE7+
:not(selector):选择不符合 selector 的元素。不参与计算优先级,兼容性:IE9+
::first-letter:伪元素,选择块元素第一行的第一个字母,兼容性 IE5.5+
::first-line:伪元素,选择块元素的第一行,兼容性 IE5.5+
:nth-child(an + b):伪类,选择前面有 an + b - 1 个兄弟节点的元素,其中 n >= 0, 兼容性 IE9+
:nth-last-child(an + b):伪类,选择后面有 an + b - 1 个兄弟节点的元素 其中 n >= 0,兼容性 IE9+
X:nth-of-type(an+b):伪类,X 为选择器,解析得到元素标签,选择前面有 an + b - 1 个相同标签兄弟节点的元素。兼容性 IE9+
X:nth-last-of-type(an+b):伪类,X 为选择器,解析得到元素标签,选择后面有 an+b-1 个相同标签兄弟节点的元素。兼容性 IE9+
X:first-child:伪类,选择满足 X 选择器的元素,且这个元素是其父节点的第一个子元素。兼容性 IE7+
X:last-child:伪类,选择满足 X 选择器的元素,且这个元素是其父节点的最后一个子元素。兼容性 IE9+
X:only-child:伪类,选择满足 X 选择器的元素,且这个元素是其父元素的唯一子元素。兼容性 IE9+
X:only-of-type:伪类,选择 X 选择的元素,解析得到元素标签,如果该元素没有相同类型的兄弟节点时选中它。兼容性 IE9+
X:first-of-type:伪类,选择 X 选择的元素,解析得到元素标签,如果该元素 是此此类型元素的第一个兄弟。选中它。兼容性 IE9+
|
PHP
|
UTF-8
| 2,374
| 2.6875
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
<?php
/**
* 生成用户参加码
* User: 姜伟
* Date: 2020/3/30 0030
* Time: 8:26
*/
namespace SyLive\BaiJia\LiveLargeClass\Room;
use SyConstant\ErrorCode;
use SyConstant\ProjectBase;
use SyException\Live\BaiJiaException;
use SyLive\BaseBaiJia;
use SyLive\UtilBaiJia;
/**
* Class CodeGet
*
* @package SyLive\BaiJia\LiveLargeClass\Room
*/
class CodeGet extends BaseBaiJia
{
/**
* 房间id
*
* @var int
*/
private $room_id = 0;
/**
* 用户ID
*
* @var int
*/
private $user_number = 0;
/**
* 用户头像
*
* @var string
*/
private $user_avatar = '';
public function __construct(string $partnerId)
{
parent::__construct($partnerId);
$this->serviceUri = '/openapi/room/getcode';
}
private function __clone()
{
}
/**
* @throws \SyException\Live\BaiJiaException
*/
public function setRoomId(int $roomId)
{
if ($roomId > 0) {
$this->reqData['room_id'] = $roomId;
} else {
throw new BaiJiaException('房间ID不合法', ErrorCode::LIVE_BAIJIA_PARAM_ERROR);
}
}
/**
* @throws \SyException\Live\BaiJiaException
*/
public function setUserNumber(int $userNumber)
{
if ($userNumber > 0) {
$this->reqData['user_number'] = $userNumber;
} else {
throw new BaiJiaException('用户ID不合法', ErrorCode::LIVE_BAIJIA_PARAM_ERROR);
}
}
/**
* @throws \SyException\Live\BaiJiaException
*/
public function setUserAvatar(string $userAvatar)
{
if (preg_match(ProjectBase::REGEX_URL_HTTP, $userAvatar) > 0) {
$this->reqData['user_avatar'] = $userAvatar;
} else {
throw new BaiJiaException('用户头像不合法', ErrorCode::LIVE_BAIJIA_PARAM_ERROR);
}
}
public function getDetail(): array
{
if (!isset($this->reqData['room_id'])) {
throw new BaiJiaException('房间ID不能为空', ErrorCode::LIVE_BAIJIA_PARAM_ERROR);
}
if (!isset($this->reqData['user_number'])) {
throw new BaiJiaException('用户ID不能为空', ErrorCode::LIVE_BAIJIA_PARAM_ERROR);
}
UtilBaiJia::createSign($this->partnerId, $this->reqData);
return $this->getContent();
}
}
|
Python
|
UTF-8
| 1,115
| 3.15625
| 3
|
[] |
no_license
|
# To run this, download the BeautifulSoup zip file
# http://www.py4e.com/code3/bs4.zip
# and unzip it in the same directory as this file
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = input('Enter - ')
count = int(input('Enter count - '))
position = int(input('Enter position - '))
new_list = []
out_list = []
for i in range(count):
print('Retrieving: ', url)
html = urllib.request.urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, 'html.parser')
#print(i)
# Retrieve all of the anchor tags
tags = soup('a')
#for tag in tags:
#new_list.append(tag) #append all anchors into new_list
url = tags[position-1].get('href', None) #list use index position that is -1 away from user input
#print(tag.get('href', None))
print('Retriving: ', url)
#for i in count:
#print(new_list[position])
#print(type(new_list))
#print('type of tag is : ',type(tag))
#print('type of tag is : ',type(tags))
|
Java
|
UTF-8
| 7,537
| 1.984375
| 2
|
[] |
no_license
|
package com.jiazy.areaview.util;
import android.content.Context;
import android.graphics.Bitmap;
import com.jiazy.areaview.R;
public class ChinaUtil extends CityUtil{
/*110000=北京市
120000=天津市
130000=河北省
140000=山西
150000=内蒙古自治区
210000=辽宁省
220000=吉林省
230000=黑龙江省
310000=上海市
320000=江苏省
330000=浙江省
340000=安徽省
350000=福建省
360000=江西省
370000=山东省
410000=河南省
420000=湖北省
430000=湖南省
440000=广东省
450000=广西壮族自治区
460000=海南省
500000=重庆市
510000=四川省
520000=贵州省
530000=云南省
540000=西藏自治区
610000=陕西省
620000=甘肃省
630000=青海省
640000=宁夏回族自治区
650000=新疆维吾尔自治区
710000=台湾省
810000=香港特别行政区
820000=澳门特别行政区*/
private String anhui = "ffc3c7ca";
private String beijing = "ffd5dee3";
private String chongqing = "ffb9c3c9";
private String fujian = "ffafbdb5";
private String gansu = "ffdcdddd";
private String guangdong = "ffb2beb5";
private String guangxi = "ffb6c0b5";
private String guizhou = "ffb6c0bb";
private String hainan = "ffabbbae";
private String hebei = "ffe4e9eb";
private String heilongjiang = "ffefefef";
private String henan = "ffcbcfd1";
private String hubei = "ffbcc4c9";
private String hunan = "ffb6c1be";
private String jiangsu = "ffc7cbcd";
private String jiangxi = "ffb6c1c1";
private String jilin = "ffebecec";
private String liaoning = "ffe8e8e8";
private String neimenggu = "ffe4e4e5";
private String ningxia = "ffd6dadd";
private String qinghai = "ffd2d8dc";
private String shandong = "ffced9df";
private String shanghai = "ffc0c6c9";
private String shanxi = "ffd2d6d9"; //山西
private String shanxisheng = "ffced3d5";//陕西
private String sichuan = "ffb5c1c8";
private String taiwan = "ffafbdb2";
private String tianjin = "ffdde3e7";
private String xinjiang = "ffe0e1e1";
private String xizang = "ffced7dc";
private String yunnan = "ffb6c0b8";
private String zhejiang = "ffb5c1c3";
@Override
public void setAreaViewValue(Context context, AreaView itemView, String colorStr){
Bitmap bitmap = null;
if (anhui.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_anhui);
itemView.setTag("340000=安徽省");
} else if (beijing.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_beijing);
itemView.setTag("110000=北京市");
} else if (chongqing.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_chongqing);
itemView.setTag("500000=重庆市");
} else if (fujian.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_fujian);
itemView.setTag("350000=福建省");
} else if (gansu.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_gansu);
itemView.setTag("620000=甘肃省");
} else if (guangdong.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_guangdong);
itemView.setTag("440000=广东省");
} else if (guangxi.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_guangxi);
itemView.setTag("450000=广西壮族自治区");
} else if (guizhou.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_guizhou);
itemView.setTag("520000=贵州省");
} else if (hainan.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_hainan);
itemView.setTag("460000=海南省");
} else if (hebei.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_hebei);
itemView.setTag("130000=河北省");
} else if (heilongjiang.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_heilongjiang);
itemView.setTag("230000=黑龙江省");
} else if (henan.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_henan);
itemView.setTag("410000=河南省");
} else if (hubei.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_hubei);
itemView.setTag("420000=湖北省");
} else if (hunan.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_hunan);
itemView.setTag("430000=湖南省");
} else if (jiangsu.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_jiangsu);
itemView.setTag("320000=江苏省");
} else if (jiangxi.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_jiangxi);
itemView.setTag("360000=江西省");
} else if (jilin.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_jilin);
itemView.setTag("220000=吉林省");
} else if (liaoning.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_liaoning);
itemView.setTag("210000=辽宁省");
} else if (neimenggu.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_neimenggu);
itemView.setTag("150000=内蒙古自治区");
} else if (ningxia.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_ningxia);
itemView.setTag("640000=宁夏回族自治区");
} else if (qinghai.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_qinghai);
itemView.setTag("630000=青海省");
} else if (shandong.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_shandong);
itemView.setTag("370000=山东省");
} else if (shanghai.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_shanghai);
itemView.setTag("310000=上海市");
} else if (shanxi.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_shanxi);
itemView.setTag("140000=山西");
} else if (shanxisheng.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_shanxisheng);
itemView.setTag("610000=陕西省");
} else if (sichuan.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_sichuan);
itemView.setTag("510000=四川省");
} else if (taiwan.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_taiwan);
itemView.setTag("710000=台湾省");
} else if (tianjin.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_tianjin);
itemView.setTag("120000=天津市");
} else if (xinjiang.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_xinjiang);
itemView.setTag("650000=新疆维吾尔自治区");
} else if (xizang.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_xizang);
itemView.setTag("540000=西藏自治区");
} else if (yunnan.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_yunnan);
itemView.setTag("530000=云南省");
} else if (zhejiang.equals(colorStr)) {
bitmap = itemView.readBitMap(context, R.drawable.city_china_zhejiang);
itemView.setTag("330000=浙江省");
} else {
itemView.setTag("");
}
itemView.setImageBitmap(bitmap);
}
}
|
Java
|
UTF-8
| 297
| 2.421875
| 2
|
[] |
no_license
|
/*
* file: DolphinFactory.java
* author: garret patten
* date: 03/12/18
*/
package hw5;
public class DolphinFactory extends FishFactory{
public DolphinFactory(){}
public Fish create(){
Fish f = new Fish(new DolphinBehavior());
f.setType(new Dolphin());
return f;
}
}
|
JavaScript
|
UTF-8
| 1,945
| 2.859375
| 3
|
[] |
no_license
|
$( document ).ready(function() {
var Trackster = {};
/*
Given an array of track data, create the HTML for a Bootstrap row for each.
Append each "row" to the container in the body to display all tracks.
*/
Trackster.renderTracks = function(tracks) {
for(var i = 0; i < tracks.length; i++){
var mediumAlbumArt = tracks[i].image[1]["#text"];
var totalListeners = numeral(tracks[i].listeners).format('0,0');
var artistResults = '<div class="song-row">\
<ul class="song-item">\
<li class="col-xs-offset-1 col-xs-1"><a href="' + tracks[i].url + '"><i class="fa fa-play-circle-o fa-2x" aria-hidden="true"></i></a></li>\
<li class="col-xs-3">' + tracks[i].name + '</li>\
<li class="col-xs-2">' + tracks[i].artist + '</li>\
<li class="col-xs-2"><img src=' + mediumAlbumArt + '/></li>\
<li class="col-xs-1">' + totalListeners + '</li>\
<li class="col-xs-1"></li>\
</ul>\
</div>'
$('#song-list').append(artistResults);
}
};
/*
Given a search term as a string, query the LastFM API.
Render the tracks given in the API query response.
*/
Trackster.searchTracksByTitle = function(title) {
$.ajax({
url: "https://ws.audioscrobbler.com/2.0/?method=track.search&track=" + title + "&api_key="+ API_KEY + "&format=json",
datatype: 'jsonp',
success: function(data){
Trackster.renderTracks(data.results.trackmatches.track);
}
});
};
/*
Adding some interativity to the button
*/
$('#search-button').click(function(){
var $item = $('.music-search').val();
//This deletes the previous search results
$('#song-list').empty();
Trackster.searchTracksByTitle($item);
})
/*
To detect if the user presses the enter key
*/
$('.music-search').keypress(function(event){
if(event.which == 13){
var $item = $('.music-search').val();
//This deletes the previous search results
$('#song-list').empty();
Trackster.searchTracksByTitle($item);
}
})
const API_KEY = 'c5c83bce364f8f016a2400e48b06f348';
});
|
Ruby
|
UTF-8
| 2,588
| 4.40625
| 4
|
[] |
no_license
|
=begin
ask for the first name and last name. Split into two variables called first and last and downcase
split the two name variables into a data structure (array) that has each letter (as a string)
set a variable with vowels, set a variable with consonants
loop through each data structure of first and last name to determine if each letter is in the variable or consonants array
if a vowel move to the next vowel
if it is the letter u let it equal a
if a consonant move to the next consonant
if it is the letter z let is equal b
save over the other letter and replace it in the array
combine back into a string
have first name appear after last name and saved as a new variable for alias name
=end
def alias
puts "What is you full name (first and last)"
full_name = gets.chomp.downcase
name_array = full_name.split(' ')
#p full_name
first_name = name_array[0]
last_name = name_array[1]
#p first_name
#p last_name
first_array = first_name.split('')
last_array = last_name.split('')
#p first_array
#p last_array
vowels = "aeiou".split('')
consonants = "bcdfghjklmnpqrstvwxyz".split('')
#p vowels
#p consonants
first_array.map! do
end
end
######_____________________#####
def alias_name
puts "what is your full name?"
name = gets.chomp.downcase.split(' ')
first_name = name[0].split('')
last_name = name[1].split('')
p first_name
p last_name
#new method?
index = 0
while index < first_name.length
vowels_array = ["a", "e", "i", "o", "u"]
c_array = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'x', 'y', 'z']
#p vowels_array
p first_name[index]
if vowels_array.include?(first_name[index])
first_name.map! do |letter|
if letter == "u"
letter = "a"
else letter != "u"
vowel_i = vowels_array.index(letter)
p vowel_i
next_vowel_i = vowel_i.next
p next_vowel_i
vowels_array[next_vowel_i]
end
end
p first_name
elsif c_array.include?(first_name[index])
first_name.map! do |c_letter|
if c_letter == "z"
c_letter = "b"
else c_letter != "z"
consonant_i = c_array.index(c_letter)
puts "this is the consonant_i"
p consonant_i
next_consonant_i = consonant_i +1
p next_consonant_i
c_array[next_consonant_i]
end
end
end
index += 1
end
end
p alias_name
|
Python
|
UTF-8
| 4,231
| 4.0625
| 4
|
[] |
no_license
|
https://leetcode.com/problems/h-index/?tab=Description
Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."
For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, his h-index is 3.
Note: If there are several possible values for h, the maximum one is taken as the h-index.
Really smart method!!! Here is my interpretation of the method and hope it helps those in need:
We first create a new vector counts of size L+1 where L is the length of the citations vector. The counts vector stores the number of papers having a citation equal to its index for i=0 to L-1. For i=L, it stores the number of papers having a citation equal to or greater than L. A simple fact is that the h-index can be at most L, this happens when all of his papers have citations no less than L. Therefore, for the purpose of computing h-index, if a person has L papers, it would end up with the same h-index no matter one of his paper has a citation of 10L or L.
After finalizing the counts vector, we can then easily locate his h-index by scanning from right (L) to left (0). By definition, index k is his h-index if the summation of all elements from counts[k] to counts[L] is no less than k.
The following is simply a copy of the original code with some new naming corresponding to the above interpretation:
public int hIndex(int[] citations) {
int L = citations.length;
if(L<1) return 0;
int[] counts = new int[L+1];
for(int i : citations) {
if(i>L) counts[L]++;
else counts[i]++;
}
int res = 0;
for(int k=L; k>=0; k--) {
res += counts[k];
if(res>=k) return k;
}
return 0;
}
he idea behind it is some bucket sort mechanisms. First, you may ask why bucket sort. Well, the h-index is defined as the number of papers with reference greater than the number. So assume n is the total number of papers, if we have n+1 buckets, number from 0 to n, then for any paper with reference corresponding to the index of the bucket, we increment the count for that bucket. The only exception is that for any paper with larger number of reference than n, we put in the n-th bucket.
Then we iterate from the back to the front of the buckets, whenever the total count exceeds the index of the bucket, meaning that we have the index number of papers that have reference greater than or equal to the index. Which will be our h-index result. The reason to scan from the end of the array is that we are looking for the greatest h-index. For example, given array [3,0,6,5,1], we have 6 buckets to contain how many papers have the corresponding index. Hope to image and explanation help.
I give you 99 points, one less point means that you might get proud of 100 points.lass Solution(object):
def hIndex(self, citations):
n = len(citations)
buckets = [0 for _ in range(n + 1)]
for num in citations:
if num >= n:
buckets[n] += 1
else:
buckets[num] += 1
count = 0
for i in reversed(range(len(buckets))):
count += buckets[i]
if count >= i:
return i
return 0
def hIndex(self, citations):
citations.sort()
n = len(citations)
for i in xrange(n):
if citations[i] >= (n-i):
return n-i
return 0
O(n) space, O(n) time
def hIndex(self, citations):
n = len(citations)
citeCount = [0] * (n+1)
for c in citations:
if c >= n:
citeCount[n] += 1
else:
citeCount[c] += 1
i = n-1
while i >= 0:
citeCount[i] += citeCount[i+1]
if citeCount[i+1] >= i+1:
return i+1
i -= 1
return 0
|
Java
|
UTF-8
| 5,023
| 2.0625
| 2
|
[] |
no_license
|
package sample.view;
import com.google.gson.Gson;
import com.jfoenix.controls.JFXButton;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.HPos;
import javafx.geometry.Pos;
import javafx.geometry.VPos;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import sample.util.InfoExchangeUtil;
import sample.util.Movie;
import sample.util.MultiLangMovie;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
public class MovieRecomController implements Initializable {
private ResourceBundle rb;
@FXML
private BorderPane bp;
@FXML
private GridPane topgp;
@FXML
private ImageView airlineLogoIV;
@FXML
private Button langBtn;
@FXML
private HBox mainhb;
@FXML
private ImageView movieim1;
@FXML
private Label movielb1;
@FXML
private ImageView movieim2;
@FXML
private Label movielb2;
@FXML
private ImageView movieim3;
@FXML
private Label movielb3;
@FXML
private JFXButton downBtn;
@FXML
private GridPane imagegp;
//private List<String> movielist;
@Override
public void initialize(URL location, ResourceBundle resources) {
GridPane.setHalignment(imagegp,HPos.CENTER);
langBtn.setText("");
langBtn.setGraphic(new ImageView(new Image("/sample/resources/language.png")));
GridPane.setHalignment(topgp, HPos.CENTER);
GridPane.setValignment(topgp,VPos.CENTER);
// Image image = new Image(getClass().getResource("/sample/resources/airline/logo.png").toString());
// InfoExchangeUtil.initAirlineLogo(getClass().getResource("/sample/resources/airline/logo.png").toString());
// System.out.println(getClass().getResource("/sample/resources/airline/logo.png").toString());
// InfoExchangeUtil.initProperties();
// System.out.println(InfoExchangeUtil.properties.getProperty("airlineResourcePath"));
airlineLogoIV.setImage(InfoExchangeUtil.getAirlineLogo());
rb = ResourceBundle.getBundle("language"); // load success
System.out.println(java.util.Locale.getDefault());
System.out.println(rb.getString("welcome"));
// langBtn.setText(rb.getString("welcome"));
// InfoExchangeUtil.TempinitAllMovie();
// InfoExchangeUtil.generateRecomMovie();
ArrayList<PosterAndTitle> posterAndTitles = new ArrayList<>(3);
posterAndTitles.add(new PosterAndTitle(movieim1, movielb1, null));
posterAndTitles.add(new PosterAndTitle(movieim2, movielb2, null));
posterAndTitles.add(new PosterAndTitle(movieim3, movielb3, null));
for(int i=0;i<3;i++){
PosterAndTitle posterAndTitle = posterAndTitles.get(i);
MultiLangMovie multiLangMovie = InfoExchangeUtil.getRecomMovieList().get(i);
posterAndTitle.mu = multiLangMovie;
posterAndTitle.iv.requestFocus();
posterAndTitle.iv.setImage(InfoExchangeUtil.loadPosterFromMultiLangMovie(multiLangMovie));
posterAndTitle.lb.setText(multiLangMovie.getALangMovie(Locale.getDefault().toString()).getName());
posterAndTitle.iv.setOnMouseClicked((e) -> {
InfoExchangeUtil.setRecomMovieSelected(posterAndTitle.mu);
try {
downBtnClicked();
} catch (IOException e2){
e2.printStackTrace();
}
});
}
Gson gson = InfoExchangeUtil.gsonFactory();
System.out.println(gson.toJson(InfoExchangeUtil.getAllMovieList().get(0)));
System.out.println(Locale.getDefault());
}
public void downBtnClicked() throws IOException {
ResourceBundle bundle = ResourceBundle.getBundle("language");
Parent root = FXMLLoader.load(getClass().getResource("/sample/view/list.fxml"),bundle);
bp.getChildren().setAll(root);
}
public void langSelected() throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("/sample/view/lang_select.fxml"));
bp.getChildren().setAll(root);
}
public void filterBtnClicked() throws IOException {
ResourceBundle bundle = ResourceBundle.getBundle("language");
Parent root = FXMLLoader.load(getClass().getResource("/sample/view/filter.fxml"),bundle);
bp.getChildren().setAll(root);
}
}
class PosterAndTitle{
public ImageView iv;
public Label lb;
public MultiLangMovie mu;
public PosterAndTitle(ImageView iv, Label lb, MultiLangMovie mu){
this.iv = iv;
this.lb = lb;
this.mu = mu;
}
}
|
C#
|
UTF-8
| 1,625
| 2.890625
| 3
|
[] |
no_license
|
using System;
using FluentValidation;
namespace FluentValidator.Models.FluentValidators
{
public class DeveloperValidator : AbstractValidator<Developer>
{
public DeveloperValidator()
{
RuleFor(p => p.FirstName)
.Cascade(CascadeMode.StopOnFirstFailure) // scenarios where you actually need not run multiple validation rules for a property even if it fails at the first rule.
// means that when the validator hits it’s first error for the corresponding property, it stops
.NotEmpty().WithMessage("{PropertyName} should be not empty. NEVER!")
.Length(2, 25)
.Must(CustomValidation.IsValidName).WithMessage("{PropertyName} should be all letters.");
RuleFor(p => p.LastName)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty().WithMessage("{PropertyName} should be not empty. NEVER!")
.Length(2, 25)
.Must(CustomValidation.IsValidName).WithMessage("{PropertyName} should be all letters.");
// JUST FOR CONTROL
RuleFor(p => p.LastName).NotEqual(p=>p.FirstName, StringComparer.Ordinal);
RuleFor(p => p.Email)
.EmailAddress();
RuleFor(x => x.DateOfBirth).NotEmpty().WithMessage("{PropertyName} should be not empty. NEVER!");
RuleFor(x => x.DateOfBirth)
.Must(CustomValidation.AgeValidate)
.WithMessage("Invalid {PropertyName}. Age must be 21 or greater than 21");
}
}
}
|
Java
|
UTF-8
| 2,194
| 1.835938
| 2
|
[] |
no_license
|
package com.canteen.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import java.util.List;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author 毕业设计
* @since 2021-05-04
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class Userorder implements Serializable {
private static final long serialVersionUID = 1L;
@TableId("userorderId")
private String userorderId;
/**
* 所属用户ID
*/
@TableField("openId")
private String openId;
/**
* 总价
*/
@TableField("userorderSmoney")
private float userorderSmoney;
/**
* 应支付订金的金额
*/
@TableField("userorderFmoney")
private float userorderFmoney;
/**
* 订金状态,
0为未支付订金,1为已支付订金,2为退订金,3退款
*/
@TableField("userorderFStatus")
private Integer userorderFStatus;
/**
* 应支付的尾款金额
*/
@TableField("userorderMmoney")
private float userorderMmoney;
/**
* 尾款状态,
0为未支付尾款,1为已支付尾款
*/
@TableField("userorderMStatus")
private Integer userorderMStatus;
@TableField("userorderCreatime")
private LocalDateTime userorderCreatime;
@TableField("useraddressId")
private Integer useraddressId;
@TableField("useraddressTel")
private String useraddressTel;
@TableField("useraddressName")
private String useraddressName;
private String useraddress;
private String gender;
@TableField("departmentId")
private Integer departmentId;
@TableField("departmentName")
private String departmentName;
@TableField("departmentfloorId")
private Integer departmentfloorId;
@TableField("departmentfloorName")
private String departmentfloorName;
@TableField("dailymenuTime")
private Integer dailymenuTime;
@TableField("dailymenuCreatime")
private LocalDateTime dailymenuCreatime;
}
|
C#
|
UTF-8
| 1,948
| 2.671875
| 3
|
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//状态转换条偶见
public enum Transition
{
NullTransition = 0,
SawPlayer, //看到主角
LostPlayer, //跟丢主角
}
//状态ID,是每一个状态的唯一标识,一个状态有一个stateid,而且其他的状态不可重复
public enum StateID
{
NullStateID = 0,
Patrol, //巡逻转台
Chase, //追主角状态
}
public abstract class FSMState
{
protected StateID stateID;
public StateID ID
{
get
{
return stateID;
}
}
protected Dictionary<Transition, StateID> map = new Dictionary<Transition, StateID>();
public FSMSystem fsm;
public void AddTransition(Transition trans, StateID id)
{
if (trans == Transition.NullTransition || id == StateID.NullStateID)
{
Debug.LogError("Transition or stateid is null");
return;
}
if (map.ContainsKey(trans))
{
Debug.Log("State " + stateID + " is already transition " + trans);
}
map.Add(trans, id);
}
public void DeleteTransition(Transition trans)
{
if (!map.ContainsKey(trans))
{
Debug.LogWarning("The transition " + trans + "you want to delete is not exit in map!");
}
map.Remove(trans);
}
//根据传递过来的转换条件,判断一下是否可以发生转换
public StateID GetOutputState(Transition trans)
{
if (map.ContainsKey(trans))
{
return map[trans];
}
return StateID.NullStateID;
}
public virtual void DoBeforeEntering() {}
public virtual void DoBefoteLeaving() {}
//当状态机处于当前状态中,会一直被条用
public abstract void DoUpdate();
}
|
Java
|
UTF-8
| 191
| 2.828125
| 3
|
[] |
no_license
|
package week1.dayy1;
public class EvenNos
{
public static void main(String[] args)
{
for (int i=80;i>=60;i--)
{
if (i%2==0)
{
System.out.println(i);
}
}
}
}
|
Python
|
UTF-8
| 2,893
| 3.125
| 3
|
[] |
no_license
|
#
# Students : Philip Bouman , Alex Khawalid
# Studentnr : 10668667 , 10634207
# Assignment B: step 1 NTMI
# Date : 06-02-2015
#
# Command-line:
# (1): python bstep1.py -i [non-binarized] -o [binarized]
from optparse import OptionParser
# parse options
parser = OptionParser()
parser.add_option("-i", "--input", dest="input")
parser.add_option("-o", "--output", dest="output")
(options,args) = parser.parse_args()
# if input assigned
if options.input:
inputfile = options.input
else:
inputfile = "data/test20.txt"
# if output assigned
if options.output:
outputfile = options.output
else:
outputfile = "test.txt"
inputfile = open(inputfile, 'r')
inputlines = inputfile.readlines()
inputfile.close()
outputfile = open(outputfile, 'w')
# get substrings
# line is of the form TAG followed by children
# line = TAG (..) (..) (..)
# elements returns these elements in a list
def getSubStrings(line):
openCount = 0
closeCount = 0
lastStart = 0
elements = []
i = 0
char = line[i]
if "(" not in line:
return False
while char != "(":
i+= 1
if i > len(line)-1:
return False
char = line[i]
lastStart = i
elements.append(line[:lastStart-1])
while i < len(line):
if line[i] == " ":
i += 1
continue
elif line[i] == "(":
openCount += 1
elif line[i] == ")":
closeCount += 1
if openCount-closeCount == 0 and openCount > 0:
elements.append(line[lastStart:i+1].strip())
lastStart = i + 1
i += 1
return elements
def getTerminalTag(element):
elements = element.split()
return elements[0][1:]
def updateSibilings(siblings, newsib):
if len(siblings) < 2:
siblings.append(newsib)
else:
siblings.append(newsib)
siblings = siblings[1:]
return siblings
def binarizeLeft(line, parent):
# init variables
left = " ("
right = ")"
output = ""
root = ""
# get tree elements
elements = getSubStrings(line[1:-1])
if elements != False:
# if only 1 child
if len(elements) == 2:
output += elements[0] + " "
temp = binarizeLeft(elements[1],elements[0])
output += temp[0]
root = elements[0]
# if 2 children or more
elif len(elements) > 2:
# get root element of this level
root = elements[0]
output += root + " "
# binarize first element and get tag
temp = binarizeLeft(elements[1],root)
output += temp[0]
lastsib = temp[1]
siblings = [lastsib]
# add siblings to other elements
for el in elements[2:]:
output += " (@" + root + "->_" + "_".join(siblings) + " "
temp = binarizeLeft(el,root)
output += temp[0]
lastsib = temp[1]
siblings = updateSibilings(siblings,lastsib)
right += ")"
# terminal node
else:
return [line,getTerminalTag(line)]
#print output
return [left + output + right,root]
############## main code ###############
for line in inputlines:
if line == "\n":
outputfile.write('\n')
continue
outputfile.write(binarizeLeft(line,"")[0].strip() + "\n")
|
C++
|
UTF-8
| 1,742
| 3.859375
| 4
|
[] |
no_license
|
/**************************************************************************************************
* Hau Tao
* select.cpp
* 01/26/2016
* This program implement the selection sort
*The algorithm divides the input list into two parts: the sublist of items already sorted,
*which is built up from left to right at the front (left) of the list, and the sublist of
*items remaining to be sorted that occupy the rest of the list. Initially, the sorted
*sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds
* by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist,
* exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order)
*and moving the sublist boundaries one element to the right.
**************************************************************************************************/
#include <iostream>
#include <stack>
#include <vector>
#include <cstdlib>
using namespace std;
void print_out(vector<int>&v);
void selection_sort(vector<int>&v,int n );
void random_vector( vector<int>& v, int n);
main()
{
int n;
cout << "Enter your size (n): \n";
cin >> n;
vector<int> v(n);
srand(time(0));
random_vector(v,n);
selection_sort(v, n);
print_out(v);
}
// selection sort algorithm
void selection_sort(vector<int>&v, int n )
{
for ( int i = 0; i< n-1; i++){
for( int j =i+1; j< n; ++j){
if(v.at(i)>v.at(j))
swap(v.at(i), v.at(j));
}
}
}
// print out the sorted vector
void print_out(vector<int>&v)
{
for( int i =0; i< v.size(); i++)
cout << v.at(i)<<endl;
}
// create the random number vector
void random_vector( vector<int> &v, int n)
{
for( int i =0; i< n; i++)
v.at(i) = rand()/1000000;
}
|
Python
|
UTF-8
| 1,346
| 3.265625
| 3
|
[] |
no_license
|
def reverse_complement(read):
read = read[::-1]
read = read.replace("A", "t").replace("C", "g")
read = read.replace("T", "a").replace("G", "c")
return read.upper()
def parse_fasta(filepath):
with open(filepath) as fasta_file:
reads = [
line.strip()
for i, line in enumerate(fasta_file.readlines())
if ((i % 4) == 1)
]
return reads
def parse_sam(filepath):
def _record_check(line):
return (len(line.split()) > 9) and (len(line.split()[9]) > 100)
with open(filepath) as sam_file:
reads = [
line.split()[9].strip()
for line in sam_file.readlines()
if _record_check(line)
]
return reads
def load_reads(filepaths):
reads = []
for filepath in filepaths:
extension = filepath.split(".")[-1]
if extension == "sam":
reads.extend(parse_sam(filepath))
elif extension == "fas" or extension == "fq":
reads.extend(parse_fasta(filepath))
else:
raise ValueError(
f"filepath: expected extension to one of '.sam', '.fas', found {extension}"
)
reads = [read for read in reads if 'N' not in read]
rev_comp_reads = [reverse_complement(read) for read in reads]
return reads + rev_comp_reads
|
C++
|
UTF-8
| 5,377
| 3.359375
| 3
|
[] |
no_license
|
#ifndef CAMERA_HPP
#define CAMERA_HPP
#include <glm/glm.hpp>
/**
* @brief Manage the Camera.
*
* We consider a camera to be defined by two 4x4 matrices:
* - the view matrix
* - the projection matrix.
*
* The view matrix defines the position and the orientation of the camera in the
* world coordinates. It is represented as follow:
* | Column 0 | Column 1 | Column 2 | Column 3 |
* |----------|----------|----------|----------|
* | X0 | X1 | X2 | P0 |
* | Y0 | Y1 | Y2 | P1 |
* | Z0 | Z1 | Z2 | P2 |
* | 0 | 0 | 0 | 1 |
* X=(X0,X1,X2), Y=(Y0,Y1,Y2) and Z=(Z0,Z1,Z2) represent the right, up, and
* backward direction of the camera in the world coordinates. The point
* P=(P0,P1,P2) is the position of the world origin in the camera frame
* (X,Y,Z). Thus, the point (-dot(P,X), -dot(P,Y), -dot(P,Z)) is the position
* of the camera in the world coordinates.
*
* The projection matrix defines the way the scene viewed by the camera is
* transformed (projected) to a 2D image that will be displayed on screen. To
* compute this matrix, we need ratio of the 2D image, the field of view and
* the far and near cutting plane distances.
*/
class Camera
{
public:
Camera();
~Camera();
/** @brief Animate the camera
*
* This function is currently empty, but you can define an animation
* behavior here. This function is automatically called by the Viewer
* @param time Current simulation time.
*/
void animate( float time );
/**
* @name Camera View Matrix
* Set of methods which interact with the camera view matrix. This matrix
* which determines the camera frame in the world coordinates, i.e. the way
* the camera is positioned and oriented.
* @{
*/
/**
* Returns the current view matrix: where the camera looks.
*/
const glm::mat4& viewMatrix() const;
/**
* Returns the camera position in world coordinates.
*/
glm::vec3 getPosition() const;
/**
* Returns the camera right direction (+X) in world coordinates.
*/
glm::vec3 getRight() const;
/**
* Returns the camera up direction (+Y) in world coordinates.
*/
glm::vec3 getUp() const;
/**
* Returns the camera forward direction (-Z / looking direction) in world coordinates.
*/
glm::vec3 getForward() const;
/**
* Sets the camera position in world coordinates.
* @param pos New camera world position.
*/
void setPosition( const glm::vec3& pos );
/**
* Sets the camera right direction in world coordinates.
* @param right New camera right axis.
*/
void setRight( const glm::vec3& right );
/** Set the camera up direction in world coordinates.
* @param up New camera up axis.
*/
void setUp( const glm::vec3& up );
/** Set the camera forward (-Z) direction in world coordinates.
* @param forward New camera forward direction.
*/
void setForward( const glm::vec3& forward );
///@}
/**
* @name Camera Projection Matrix
* Set of methods which interact with the projection matrix. This matrix
* determine how a scene is projected on a 2D image that will be displayed
* on screen.
* @{
*/
/**
* Returns the projection matrix.
*/
const glm::mat4& projectionMatrix() const;
/**
* Returns the field of view.
*/
float fov() const;
/**
* Returns the length ratio of the image taken by this camera:
*/
float ratio() const;
/**
* Returns the near clipping plane: anything closer to the camera than this plane
* will be removed from the view.
*/
float znear() const;
/**
* Returns the far clipping plane: anything farther from the camera than this plane
* will be removed from the view.
*/
float zfar() const;
/**
* Sets the field of view. 1.04 is a good start.
*/
void setFov( const float& v );
/**
* Sets the ratio of the camera (generally, this is done at each window resize).
*/
void setRatio( const float& v );
/**
* Sets the far clipping plane.
*/
void setZfar( const float& v );
/**
* Sets the near clipping plane.
*/
void setZnear( const float& v );
///@}
/**
* How the camera react to a mouse displacement.
*/
enum CAMERA_MOUSE_BEHAVIOR {
/** The view matrix is modified to turn the camera around the world origin.*/
ARCBALL_BEHAVIOR,
/** The view matrix is modified to point its 'nose' in the direction pointed by the mouse. */
SPACESHIP_BEHAVIOR
};
/** @name Mouse Control
* Control the camera with the mouse.
* @{
*/
/**
* Returns the mouse behavior.
*/
CAMERA_MOUSE_BEHAVIOR getMouseBehavior() const;
/**
* Sets the mouse behavior.
*/
void setMouseBehavior( const CAMERA_MOUSE_BEHAVIOR& v );
/**
* Update the camera view matrix according to the current mouse behavior.
*/
void update( float dx, float dy );
///@}
private:
/** @name Private members */
CAMERA_MOUSE_BEHAVIOR m_mouseBehavior;
float m_fov;
float m_ratio;
float m_znear;
float m_zfar;
glm::mat4 m_view;
glm::mat4 m_projection;
};
#endif
|
Java
|
UTF-8
| 7,225
| 3.1875
| 3
|
[] |
no_license
|
package bgs.geophys.library.Swing.Wizard;
import java.awt.*;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.*;
/**
* A descriptor class used to reference a Component panel for the Wizard, as
* well as provide general rules as to how the panel should behave.
*/
public class WizardPanelDescriptor
{
static class FinishIdentifier {
public static final String ID = "FINISH";
}
/**
* Identifier returned by getNextPanelDescriptor() to indicate that this is the
* last panel and the text of the 'Next' button should change to 'Finish'.
*/
public static final FinishIdentifier FINISH = new FinishIdentifier();
private Wizard wizard;
private Component targetPanel;
private Object backIdentifier;
private Object panelIdentifier;
private Object nextIdentifier;
private Vector<WizardListeners.WizardPanelChangeListener> panelChangeListeners;
/**
* Constructor to create a panel descriptor which knows its own
* id and panel, as well as the ids for previous and next panels
* @param previous_id ID for the previous panel
* @param id Object-based identifier
* @param next_id ID for the previous panel
* @param panel A class which extends java.awt.Component that will be inserted as a
* panel into the wizard dialog.
*/
public WizardPanelDescriptor(Object previous_id, Object id, Object next_id, Component panel) {
backIdentifier = previous_id;
panelIdentifier = id;
nextIdentifier = next_id;
targetPanel = panel;
panelChangeListeners = new Vector<WizardListeners.WizardPanelChangeListener> ();
}
public void addPanelChangeListener (WizardListeners.WizardPanelChangeListener listener) {
panelChangeListeners.add (listener);
}
public void removePanelChangeListener (WizardListeners.WizardPanelChangeListener listener) {
panelChangeListeners.remove(listener);
}
/**
* Returns to java.awt.Component that serves as the actual panel.
* @return A reference to the java.awt.Component that serves as the panel
*/
public final Component getPanelComponent() {
return targetPanel;
}
/**
* Sets the panel's component as a class that extends java.awt.Component
* @param panel java.awt.Component which serves as the wizard panel
*/
public final void setPanelComponent(Component panel) {
targetPanel = panel;
}
/**
* Returns the unique Object-based identifier for this panel descriptor.
* @return The Object-based identifier
*/
public final Object getPanelDescriptorIdentifier() {
return panelIdentifier;
}
/**
* Sets the Object-based identifier for this panel. The identifier must be unique
* from all the other identifiers in the panel.
* @param id Object-based identifier for this panel.
*/
public final void setPanelDescriptorIdentifier(Object id) {
panelIdentifier = id;
}
final void setWizard(Wizard w) {
wizard = w;
}
/**
* Returns a reference to the Wizard component.
* @return The Wizard class hosting this descriptor.
*/
public final Wizard getWizard() {
return wizard;
}
/**
* Returns a reference to the current WizardModel for this Wizard component.
* @return The current WizardModel for this Wizard component.
*/
public WizardModel getWizardModel() {
return wizard.getModel();
}
/**
* Get the Object-based identifier of the panel that the
* user should traverse to when the Next button is pressed. Note that this method
* is only called when the button is actually pressed, so that the panel can change
* the next panel's identifier dynamically at runtime if necessary. Return null if
* the button should be disabled. Return FinishIdentfier if the button text
* should change to 'Finish' and the dialog should end.
* @return Object-based identifier.
*/
public Object getNextPanelDescriptor() {
return nextIdentifier;
}
/** set the identifier of the panel that will be displayed when the
* Next button is pressed. Note that this can be called at any time before
* next is pressed
* @param id the new identifier
*/
public void setNextPanelDescriptor (Object id) {
nextIdentifier = id;
}
/**
* Get the Object-based identifier of the panel that the
* user should traverse to when the Back button is pressed. Note that this method
* is only called when the button is actually pressed, so that the panel can change
* the previous panel's identifier dynamically at runtime if necessary. Return null if
* the button should be disabled.
* @return Object-based identifier
*/
public Object getBackPanelDescriptor() {
return backIdentifier;
}
/** set the identifier of the panel that will be displayed when the
* Back button is pressed. Note that this can be called at any time before
* back is pressed
* @param id the new identifier
*/
public void setBackPanelDescriptor (Object id) {
backIdentifier = id;
}
/**
* Call listeners just before the panel is to be displayed.
*/
public void aboutToDisplayPanel(WizardEvents.WizardButtonEvent btn_evt) {
Iterator<WizardListeners.WizardPanelChangeListener> i;
WizardEvents events;
WizardEvents.WizardPanelChangeEvent evt;
events = new WizardEvents ();
evt = events.makeWizardPanelChangeEvent(panelIdentifier);
for (i=panelChangeListeners.iterator(); i.hasNext(); )
i.next().aboutToDisplayPanel(evt, btn_evt);
}
/**
* Call listeners when the panel itself is displayed.
*/
public void displayingPanel(WizardEvents.WizardButtonEvent btn_evt) {
Iterator<WizardListeners.WizardPanelChangeListener> i;
WizardEvents events;
WizardEvents.WizardPanelChangeEvent evt;
events = new WizardEvents ();
evt = events.makeWizardPanelChangeEvent(panelIdentifier);
for (i=panelChangeListeners.iterator(); i.hasNext(); )
i.next().displayingPanel(evt, btn_evt);
}
/**
* Call listeners just before the panel is to be hidden.
* @return true if the panel can be hidden (and the next panel displayed)
* false to halt the panel change operations
*/
public boolean aboutToHidePanel(WizardEvents.WizardButtonEvent btn_evt) {
Iterator<WizardListeners.WizardPanelChangeListener> i;
WizardEvents events;
WizardEvents.WizardPanelChangeEvent evt;
boolean ret_val;
events = new WizardEvents ();
evt = events.makeWizardPanelChangeEvent(panelIdentifier);
ret_val = true;
for (i=panelChangeListeners.iterator(); i.hasNext(); )
{
if (! i.next().aboutToHidePanel(evt, btn_evt)) ret_val = false;
}
return ret_val;
}
}
|
PHP
|
UTF-8
| 1,945
| 2.9375
| 3
|
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* User: allflame
* Date: 4/4/16
* Time: 9:08 PM
*/
namespace Logger;
use Vain\Expression\Evaluator\EvaluatorInterface;
use Vain\Expression\ExpressionInterface;
use Vain\Expression\Logger\LoggerInterface;
use Vain\Expression\Parser\ParserInterface;
class Logger implements LoggerInterface
{
private $logger;
/**
* Logger constructor.
* @param \Vain\Logger\LoggerInterface $logger
*/
public function __construct(\Vain\Logger\LoggerInterface $logger)
{
$this->logger = $logger;
}
/**
* @inheritDoc
*/
public function beforeEvaluation(ExpressionInterface $expression, EvaluatorInterface $evaluator)
{
$this->logger->debug(sprintf('Starting evaluating expression %s with evaluator %s', get_class($expression), get_class($evaluator)));
}
/**
* @inheritDoc
*/
public function afterEvaluation(ExpressionInterface $expression, EvaluatorInterface $evaluator, $result)
{
if (false === $result) {
$this->logger->debug(sprintf('Finished evaluating expression %s with evaluator %s: FALSE', get_class($expression), get_class($evaluator)));
} else {
$this->logger->debug(sprintf('Finished evaluating expression %s with evaluator %s: TRUE', get_class($expression), get_class($evaluator)));
}
}
/**
* @inheritDoc
*/
public function beforeParsing(ExpressionInterface $expression, ParserInterface $parser)
{
$this->logger->debug(sprintf('Starting evaluating expression %s with evaluator %s', get_class($expression), get_class($parser)));
}
/**
* @inheritDoc
*/
public function afterParsing(ExpressionInterface $expression, ParserInterface $parser, $result)
{
$this->logger->debug(sprintf('Finished parsing expression %s with parser %s: %s', get_class($expression), get_class($parser), $result));
}
}
|
C++
|
UTF-8
| 2,003
| 2.53125
| 3
|
[
"CC0-1.0"
] |
permissive
|
#pragma once
#include "ofMain.h"
#include "ofxMidi.h"
#include "ofxAnimationPrimitives.h"
#define MIDI_SENDER MidiSenderController::getInstance()
class MidiSenderController
{
class Note : public ofxAnimationPrimitives::Instance
{
ofxMidiOut * mMidi;
const int mCh;
const int mPich;
public:
Note(ofxMidiOut * midi, int pich, int velo, int channel):
mMidi(midi), mCh(channel), mPich(pich)
{
mMidi->sendNoteOn(channel, pich, velo);
}
void willDelete()
{
mMidi->sendNoteOff(mCh, mPich);
}
};
// singleton
MidiSenderController(){ init(); };
// midi controll instances
ofxAnimationPrimitives::InstanceManager mMidi;
private:
ofxMidiOut mMidiOut;
int mChannel;
unsigned int mCurrentPgm;
public:
static MidiSenderController * getInstance()
{
static MidiSenderController * instance = new MidiSenderController();
return instance;
}
void init()
{
mChannel = 1;
mCurrentPgm = 0;
ofAddListener(ofEvents().update, this, &MidiSenderController::update);
}
void update(ofEventArgs& e)
{
mMidi.update();
}
void openPort(const string& deviceName)
{
mMidiOut.openPort(deviceName);
}
void setCurrentChannel(int ch)
{
mChannel = ch;
}
void setCurrentProgram(unsigned int pgm)
{
mCurrentPgm = pgm;
}
void makeNote(int note, int velo, int channel, float duration)
{
if (channel != 0) mChannel = channel;
mMidi.createInstance<Note>(&mMidiOut, note, velo, mChannel)->play(duration);
}
void ctlOut(int cc, int value, int channel = 0)
{
if (channel != 0) mChannel = channel;
mMidiOut.sendControlChange(mChannel, cc, value);
}
void listPorts()
{
mMidiOut.listPorts();
}
};
|
Markdown
|
UTF-8
| 1,150
| 2.953125
| 3
|
[] |
no_license
|
# CookItYourself
<p align="center">
<img src="page.png" width="400"/>
</p>
CookItYourself is a neat web app which transforms pictures of food (or single ingredients) into recipes.
It uses image recognition—powered by Google Cloud Platform—to fetch matching recipes from [Chefkoch](http://chefkoch.de).
The app was created by an amazing team at a hackathon in Karlsruhe, Germany (sponsored by [real.digital](http://real.digital/)), winning the first prize.
[Read the full story here!](https://pioniergarage.de/2017/hck-e-food-hackathon/) (German)
## How to run
Prerequisites: You need node.js installed.
Additionally, you must have a valid private key file (JSON format) for Google Cloud Platform.
Please see [this guide](https://cloud.google.com/docs/authentication/getting-started) for instructions on how to get this.
1. Clone this repo
2. `cd server`
3. `npm install`
4. `GOOGLE_APPLICATION_CREDENTIALS=<path to your private key file> node bin/www`
5. Open `index_.html` (in `client` directory) in Browser (yes, the one with the dash, sorry!)
(Warning: This code should be treated as a hacky PoC and is not suitable for production.)
|
Markdown
|
UTF-8
| 1,142
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
# Billing Package
Umbrella package for billing, charging, invoicing and payment functionality
## 1. Installation
### 1.1 Setup your project's composer.json
Add repository containing this package
```json
"repositories": [{"type": "composer", "url": "http://your.resource.url"}],
```
(Note: you need to have access to this repository as well as to resources it points to)
Set minimum stability to 'dev':
```json
"minimum-stability": "dev"
```
### 1.2 Add dependency to this package under "require" key of your project's composer.json
```json
"subscribo/billing": "@dev"
```
and update composer
```sh
composer update
```
### 1.3 To register BillingServiceProvider with Laravel (5.0)
add following under 'providers' key in config/app.php file:
```php
'\\Subscribo\\Billing\\Integration\\Laravel\\BillingServiceProvider',
```
or (for conditional registration) you can add following to bootstrap/app.php:
```php
if (class_exists('\\Subscribo\\Billing\\Integration\\Laravel\\BillingServiceProvider')) {
$app->register('\\Subscribo\\Billing\\Integration\\Laravel\\BillingServiceProvider');
}
```
|
C++
|
WINDOWS-1252
| 2,510
| 2.75
| 3
|
[] |
no_license
|
#include"Queue.cpp"
#include"time.h"
#define Qn 5
#define maxit 5
#define maxdt 30
typedef LinkList EventList;
EventList ev;
Event en,et;
LinkQueue q[5];
QElemType customer;
int TotalTime,CustomerNum;
int CloseTime=100;
int n=1;
int cmp(Event a,Event b){
if(a.Occurtime>b.Occurtime)
return 1;
else if(a.Occurtime<b.Occurtime)
return -1;
else
return 0;
}//cmp
int Minimum(LinkQueue *q){
int i,j=1;
for(i=2;i<Qn;i++){
if(QueueLength(q[j])>QueueLength(q[i]))
j=i;
}//printf("ŵ %d \n",j);
return j;
}//Minimum
void Random(int &a,int &b)
{
//srand((unsigned int)__TIME__);//seed of time
a=rand()%maxdt+1;//duritime
b=rand()%maxit+1;//intertime
}//Random
Event GetCurElem(Link p){
return p->data;
}
void OpenForDay(){
//Init operation
int i;
TotalTime=0;
CustomerNum=0;
InitList(ev);
en.Occurtime=0; en.Ntype=0;
OrderInsert(ev,en,cmp);
for(i=1;i<=Qn;++i) InitQueue(q[i]);
} //OpenForDay
void CustomerArried(){
//en.NType=0;
int i,durtime,intertime;
CustomerNum++;
Random(durtime,intertime);
//printf("d :%d,i :%d\n",durtime,intertime);
et.Occurtime=en.Occurtime+intertime;
customer.ArrivalTime=en.Occurtime;
customer.Duration=durtime;
customer.num=++n;
//printf("TIME :%d ",et.Occurtime);
//printf("c %d arrived;\n",customer.num);
et.Ntype=0;
if(et.Occurtime<CloseTime)
OrderInsert(ev,et,cmp);
i=Minimum(q); //The minimum length of queue;
EnQueue(q[i],customer);
//printf("%d",i);
if(QueueLength(q[i])==1)
{
et.Occurtime=en.Occurtime+durtime;
et.Ntype=i;
OrderInsert(ev,et,cmp);
//deparure event of i queue;
}
}//CustomerArried
void CustomerDeparture(){
//en.Ntype>0;
int i;
i=en.Ntype; DeleQueue(q[i],customer);
TotalTime+=en.Occurtime-customer.ArrivalTime;
//accumulate customer's sojourn/stay time
if(!QueueEmpty(q[i])){//printf("\nTIME :%d \n",en.Occurtime);
GetHead_Q(q[i],customer);
et.Occurtime=en.Occurtime+customer.Duration;
et.Ntype=i;
OrderInsert(ev,et,cmp);
//printf("c %d departure;\n",customer.num);
}
} //CustomerDeparture
void Bank_Simulation(int Closetime)
{
Link p;
OpenForDay();
while(!ListEmpty(ev)){
DelFirst(GetHead(ev),p);
//printf("%d %d\n",p->data.Occurtime,p->data.Ntype);
en=GetCurElem(p);
if(en.Ntype==0)
CustomerArried();
else
CustomerDeparture();
}
printf("The average time is %f\n",(float)TotalTime/CustomerNum);
}//Bank_Simulation
int main(){
Bank_Simulation(CloseTime);
return 0;
}
|
Shell
|
UTF-8
| 441
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env bash
#{{{ MARK:Header
#**************************************************************
##### Author: JACOBMENKE
##### Date: Sat Apr 21 17:07:54 EDT 2018
##### Purpose: bash script to
##### Notes:
#}}}***********************************************************
for file in "$@"; do
newfile=${file%.*}
vim -c 'hardcopy > '"$newfile.ps" -c quitall "$file"
done
cat *.ps | open -fa Preview
rm -f *.ps
|
C
|
UTF-8
| 2,745
| 2.890625
| 3
|
[] |
no_license
|
#include "ros/ros.h"
#include "svg_ros/OverSrv.h"
#include <cstdlib>
int over_light()
{
static int flg = 1;
static ros::NodeHandle n;
static ros::ServiceClient client;
svg_ros::OverSrv srv;
//printf("over light\n");
if(flg == 1){
client = n.serviceClient<svg_ros::OverSrv> ("over_light"); // connecting to service OverSrv:over_light
flg = 0;
}
srv.request.over_flg = 1;
if (client.call(srv))
{
//ROS_INFO("LIGHT Program is over");
}
else
{
ROS_ERROR("Failed to call LIGHT service over_light");
return 1;
}
return 0;
}
int over_sensor()
{
static int flg = 1;
static ros::NodeHandle n;
static ros::ServiceClient client;
svg_ros::OverSrv srv;
//printf("over sensor\n");
if(flg == 1){
client = n.serviceClient<svg_ros::OverSrv> ("over_sensor"); // connecting to service OverSrv:send_destination
flg = 0;
}
srv.request.over_flg = 1;
if (client.call(srv))
{
//ROS_INFO("SENSOR Program is over");
}
else
{
ROS_ERROR("Failed to call SENSOR service over_sensor");
return 1;
}
return 0;
}
int over_base()
{
static int flg = 1;
static ros::NodeHandle n;
static ros::ServiceClient client;
svg_ros::OverSrv srv;
//printf("over base\n");
if(flg == 1){
client = n.serviceClient<svg_ros::OverSrv> ("over_base"); // connecting to service OverSrv:over_base
flg = 0;
}
srv.request.over_flg = 1;
if (client.call(srv))
{
//ROS_INFO("Base Program is over");
}
else
{
ROS_ERROR("Failed to call BASE service over_base");
return 1;
}
return 0;
}
int over_inputs()
{
ros::NodeHandle n;
ros::ServiceClient client = n.serviceClient<svg_ros::OverSrv> ("over_inputs");
svg_ros::OverSrv srv;
srv.request.over_flg = 0;
if (client.call(srv))
{
//ROS_INFO("Inputs Program's over");
}
else
{
ROS_ERROR("Failed to call inputs service over_inputs");
return 1;
}
return 0;
}
int over_gui()
{
ros::NodeHandle n;
ros::ServiceClient client = n.serviceClient<svg_ros::OverSrv> ("over_gui");
svg_ros::OverSrv srv;
srv.request.over_flg = 0;
//printf("over gui\n");
if (client.call(srv))
{
//ROS_INFO("GUI Program's over");
}
else
{
ROS_ERROR("Failed to call gui service over_gui");
return 1;
}
return 0;
}
int over(){
int s1 = over_light();
int s2 = over_sensor();
int s3 = over_inputs();
int s4 = over_gui();
int s5 = over_base();
return s1|s2|s3|s4|s5;
}
|
Python
|
UTF-8
| 386
| 3.25
| 3
|
[] |
no_license
|
a=[
{"name":"nikhil","roll":12,"feedback":None},
{"name":"anil","roll":23,"feedback":None},
{"name":"raol","roll":1,"feedback":"Behaves like johnny"}
]
for i in range(3):
print(a[i]["name"]);
# ab=a[0]["last_name"]; This returns an error...so
ab=a[0].get("last_name","last_name not found");
print("The value of ab is ",ab," So this is the value");
|
Swift
|
UTF-8
| 1,511
| 2.921875
| 3
|
[] |
no_license
|
//
// ExampleViewController.swift
// LovelyActivityIndicatorView
//
// Created by Evan Bacon on 09/14/2016.
// Copyright (c) 2016 bacon brix. All rights reserved.
//
import UIKit
class ExampleViewController: UIViewController {
var loop: UIButton!
}
extension ExampleViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupLoopingButton()
startAnimation(loop)
}
private func setupLoopingButton() {
loop = UIButton(frame: CGRect(origin: view.center, size: CGSize(width: self.view.frame.size.width,height: 100)))
loop.frame.origin.y += 100
loop.frame.origin.x = 0
loop.setTitle("Loop", forState: .Normal)
loop.setTitleColor(UIColor.blackColor(), forState: .Normal)
loop.setTitleColor(UIColor.lightGrayColor(), forState: .Disabled)
loop.titleLabel?.font = UIFont(name: "Avenir-Book", size: 20.0)
loop.titleLabel?.textAlignment = .Center
loop.addTarget(self, action: #selector(ExampleViewController.startAnimation(_:)), forControlEvents: .TouchUpInside)
view.addSubview(loop)
}
func startAnimation(sender:UIButton) {
sender.enabled = false
view.startLoading()
NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: #selector(ExampleViewController.stopAnimation), userInfo: nil, repeats: false)
}
func stopAnimation() {
loop.enabled = true
view.stopLoading()
}
}
|
C
|
UTF-8
| 1,689
| 4.40625
| 4
|
[] |
no_license
|
//Write a program to pass a character array in a function and function should commute the
//total numbers of occurrences of a particular character in the character array.
#include <stdio.h>
/******declaring function******/
void occurrences();
//globally declare variable char array[]
char array[100];
int main()
{
printf("Enter the string (will be stored in an array):-->");
//takes user input in the argument and occurrences function called
occurrences(gets(array));
return 0;
}
/*****function defination*****/
void occurrences(char array[100])
{
int i;
int count=0;
char value;
// User interface
printf("Enter the character to be searched:--> \n");
scanf("%c",&value); //char to be searched is stored
/************ Logic *************/
//loop runs until '\0' which is null that comes as the user finshes input and presses enter
for(i=0 ; array[i]!='\0' ;i++ )
{
if(array[i]==value) //comparing value with elements of array
{
//increamenting count when array encounters the searched variable
count++;/
}
}
/*******Output computation******/
if(count>0)
{
printf("%s \n above string has %d occurrence/s of %c character\n",array,count,value);
}
if(count==0)
{
printf("%c character not found in given string\n",value);
}
} //occurrence() function ends
|
Markdown
|
UTF-8
| 6,826
| 3.359375
| 3
|
[] |
no_license
|
# **Kickstarting with Excel**
## **Overview of Project**
### **Purpose**
The purpose of this analysis is to provide a comprehensive review of the performance of other “Play” projects on Kickstarter, specifically with regards to the success of these projects relative to their launch dates. Louise contacted us after her Kickstarter-funded play Fever almost met its fundraising goal over a short period of time, with the intent of analyzing other similar campaign funding goal outcomes relative to their launch dates
To assist Louise, we created the following visualizations with data obtained from Kickstarter’s APIs:
- A Line Chart visualizing the number of successful, failed, and cancelled Kickstarter Projects within the “Theater” category based on the launch months of the projects (data was obtained from 2009 through 2017). See "Analysis of Outcomes Based on Launch Date" below for additional information.
- A line chart plotting the percentage of successful, failed and cancelled projects based on the initial funding goals of each project (utilizing data obtained from 2009 through 2017). See "Analysis of Outcomes Based on Goals" below for additional information.
## **Analysis and Challenges**
### *Analysis of Outcomes Based on Launch Date*

Per review of the above-referenced visualization, we noted that Kickstarter Projects under the “Theater” category were most successful when launched in the months May and June. Conversely, failed projects were more linear in their success rates, but with a notable spike in failed projects that launched in October. As such, our analysis yields that the best time to launch a theater funding project is within Q2.
### *Analysis of Outcomes Based on Goals*

Generally, our analysis of the “plays” subcategory yielded that the higher the funding goal, the lower the percentage of successful outcomes (with the exception of funding goals within the range of $35,000 to $44,999). As such, our recommendation is to create a funding goal anywhere from $1,000 to $10,000 (depending on the needs of the project, as goals that exceed the $10,000 have a higher likelihood of failure.
### *Challenges and Difficulties Encountered*
The primary challenge of this project was “cleaning” the data obtained from Kickstarter’s APIs. Specifically:
- Information like dates were presented in Unix Time, which had to be converted to a standard time format in order to facilitate the visual analysis. This was performed via an Excel function;
- The data obtained from Kickstart was voluminous and included superfluous information that would not be relevant to the goals of this project, as stated within the Overview section above. To standardize this data, we relied on pivot tables and conditional functions to primary focus our analysis on the Theater and Plays category and sub-category, respectively.
## **Results**
- What are two conclusions you can draw about the Outcomes based on Launch Date?
With regards to Outcomes Based on Launch Date, our above analysis yielded that most successful projects within the Theater category tend to be launched in Q2. Additionally, the analysis indicates that project failures are not as related to launch date, as failures are more linear within the above-referenced visualization. October, however, did experience a sharp spike in failures, thereby indicating that October may not be the best month to launch a new project.
- What can you conclude about the Outcomes based on Goals?
With regards to Outomes Based on Goals, our analysis generally indicates that the higher the goal, the lesser the rate of success (with the exception of certain outliers, see limitations below for additional information). As such, it is recommended that projects with the "Plays" category include goals o $1,000 to $10,000. Please note, however, that the likelihood of success diminishes as the project goal increases.
- What are some limitations of this dataset?
- **Theater Outcomes Based on Launch Date**: As noted within the visualization and above analysis of the results, there tend to generally be more successful projects than failed projects during any given month. As a result, the spike in successful projects in the month of June may be the result of more projects simply being launched in that month than any other factors (as such, the results may present a false positive). Notably, our analysis indicated that projects launched in May and June accounted for approximately 23% of all projects launched during a 12-month period. In other words, our analysis yielded that May and June did indeed have the greatest number of projects launched. An alternative suggestion for future reference would be to create a graph uses weighting techniques to normalize the data for the number of launched projects in order to create a better and more meaningful visualization.
- **Outcomes Based on Goals**: While our analysis yielded a definitive conclusion, it is worth nothing that there are outliers within the data. Specifically, those projects that launched within the aforementioned $35,000 to $44,999 range did “buck the trend” and experience a higher success rate. Per our analysis, however, only 9 successful projects out of a total of 1,047 overall projects were launched within that range, and only 3 failed projects were launched in that range (for a total of 11 projects out of 1,047, or 0.10%). As such, it is not advisable to try to glean any information from this, as these successful projects may simply be outliers.
Additionally, it is also crucial to consider currency and exchange rates within this analysis. As the analysis simply plots goals (in currency terms) against success rates, it is important to note that currencies with an unfavorable exchange rate relative to the US dollar may skew the results. For example, within the the aforementioned range, one of the Plays that was listed with a goal of 38,000 (specifically, ID#: 2857) was denominated in Mexican Pesos, which results in a lesser amount in USD.
- What are some other possible tables and/or graphs that we could create?
Perhaps a more meaningful alternative to the "Outcomes Based on Goals" visualization would be one that is limited to projects with a specific region, in order to standardize the currency. Additionally, with regards to it would also be advisable to plot Outcomes Based on the Percentage Funded of each project in lieu of goals,
|
Go
|
UTF-8
| 4,449
| 2.546875
| 3
|
[
"Apache-2.0"
] |
permissive
|
// Copyright (c) 2021 Terminus, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package statusutil
import (
"github.com/pkg/errors"
"github.com/erda-project/erda/apistructs"
"github.com/erda-project/erda/modules/pipeline/spec"
)
func CalculatePipelineTaskStatus(pt *spec.PipelineTask) (apistructs.PipelineStatus, error) {
if pt.Status == apistructs.PipelineEmptyStatus {
return apistructs.PipelineEmptyStatus, errors.New("status is empty")
}
if pt.Status.IsEndStatus() && pt.Extra.AllowFailure {
return apistructs.PipelineStatusSuccess, nil // 相当于 success,并不改变数据库里原始状态
}
return pt.Status, nil
}
func CalculatePipelineStageStatus(ps *spec.PipelineStageWithTask) (apistructs.PipelineStatus, error) {
tasks := ps.PipelineTasks
totalNum := len(tasks)
if totalNum == 0 {
return apistructs.PipelineStatusSuccess, nil
}
summary := make(map[apistructs.PipelineStatus]int)
var bornNum int
var successNum int
var endNum int
var pauseNum int
var disableNum int
for _, task := range tasks {
taskStatus, err := CalculatePipelineTaskStatus(task)
if err != nil {
return apistructs.PipelineEmptyStatus, err
}
summary[taskStatus]++
if taskStatus == apistructs.PipelineStatusBorn {
bornNum++
}
if taskStatus.IsSuccessStatus() {
successNum++
}
if taskStatus == apistructs.PipelineStatusPaused {
pauseNum++
}
if taskStatus == apistructs.PipelineStatusDisabled {
disableNum++
}
if taskStatus.IsEndStatus() {
endNum++
}
}
// 重试失败节点时,可能会有 success 和 born
// thruster 推进时需要 stage 状态为 born
if bornNum > 0 && bornNum+successNum+disableNum == totalNum {
return apistructs.PipelineStatusBorn, nil
}
// 如果全部是 终态 + 暂停
if endNum+pauseNum+disableNum == totalNum {
// 如果有暂停,则为暂停
if pauseNum > 0 {
return apistructs.PipelineStatusPaused, nil
}
// 禁用视为成功
if disableNum+successNum == totalNum {
return apistructs.PipelineStatusSuccess, nil
}
// 否则为失败
return apistructs.PipelineStatusFailed, nil
}
// 其余状态显示为运行中
return apistructs.PipelineStatusRunning, nil
}
// stage 递归调用 stage.CalculateStatus
func CalculateStatus(p spec.PipelineWithStage) (apistructs.PipelineStatus, error) {
stages := p.PipelineStages
totalNum := len(stages)
if totalNum == 0 {
return apistructs.PipelineStatusSuccess, nil
}
var stageStatusList []apistructs.PipelineStatus
for _, stage := range stages {
stageStatus, err := CalculatePipelineStageStatus(stage)
if err != nil {
return apistructs.PipelineEmptyStatus, err
}
stageStatusList = append(stageStatusList, stageStatus)
}
// 按照 stage 顺序遍历:
// 如果有暂停,则返回暂停;
// 如果 stage 为禁用,则查看下一个 stage;
// 如果 stage 为终态,如果成功,则查看下一个 stage;如果失败,则快速失败
// 返回运行中
for si, stageStatus := range stageStatusList {
// 如果有暂停,则为暂停
if stageStatus == apistructs.PipelineStatusPaused {
return apistructs.PipelineStatusPaused, nil
}
if stageStatus == apistructs.PipelineStatusDisabled {
// 如果是最后一个 stage,则返回成功
if (si + 1) == totalNum {
return apistructs.PipelineStatusSuccess, nil
}
// 否则继续查看下一个 stage
continue
}
if stageStatus.IsEndStatus() {
if stageStatus.IsSuccessStatus() {
// 如果是最后一个 stage,则返回成功
if (si + 1) == totalNum {
return apistructs.PipelineStatusSuccess, nil
}
// 否则继续查看下一个 stage
continue
}
return stageStatus, nil
}
return apistructs.PipelineStatusRunning, nil
}
// 算不出来,则返回 Error
return apistructs.PipelineStatusError, errors.Errorf("failed to calculate status of strange pipeline [%d], summary: %+v", p.ID, stageStatusList)
}
|
PHP
|
UTF-8
| 7,693
| 2.828125
| 3
|
[] |
no_license
|
<?php
// Check we have the appropriate variable data
$vote = $_POST['vote'];
if (empty($vote)) {
echo '<p>You have not voted for a politician.</p>';
exit;
}
/*******************************************
Database query to get poll info
*******************************************/
// Log in to database
$db = new mysqli('localhost', 'poll', 'poll', 'poll');
// $db = new mysqli('tester.cynw5brug1nx.us-east-1.rds.amazonaws.com', 'tester_admin', 'pekoemini!!!!!', 'poll');
if (mysqli_connect_errno()) {
echo '<p>Error: Could not connect to database.<br/>
Please try again later.</p>';
exit;
}
// Add the user's vote
$v_query = "UPDATE poll_results
SET num_votes = num_votes + 1
WHERE candidate = ?";
$v_stmt = $db->prepare($v_query);
$v_stmt->bind_param('s', $vote);
$v_stmt->execute();
$v_stmt->free_result();
// Get current results of poll
$r_query = "SELECT candidate, num_votes FROM poll_results";
$r_stmt = $db->prepare($r_query);
$r_stmt->execute();
$r_stmt->store_result();
$r_stmt->bind_result($candidate, $num_votes);
$num_candidates = $r_stmt->num_rows;
// Calculate total number of votes so far
$total_votes = 0;
while ($r_stmt->fetch()) {
$total_votes += $num_votes;
}
$r_stmt->data_seek(0);
/*******************************************
Initial calculations for graph
*******************************************/
// Set up constants
// putenv('GDFONTPATH=/usr/share/fonts/truetype/dejavu');
// putenv('GDFONTPATH=C:\WINDOWS\Fonts');
$width = 500; // width of image in pixels. Is the total width of the canvas you will use.
$left_margin = 50; // space to leave on left of graph
$right_margin = 50; // space to leave on right of graph
$bar_height = 40;
$bar_spacing = $bar_height / 2;
$font_name = 'C:\WINDOWS\Fonts\Arial.ttf';
$title_size = 16; // in points
$main_size = 12; // in points
$small_size = 12; // in points
$text_indent = 10; // position for text labels from edge of image
// Given these base values, you can then make a few calculations. You want to draw a baseline that all the bars stretch out from. You can work out the position for this baseline by using the left margin plus an allowance for the text labels for the x coordinate and again an estimate from the sketch for the y coordinate. You could get the exact width of the longest name instead if flexibility is important.
// Set up initial point to draw from
$x = $left_margin + 60; // place to draw baseline of the graph
$y = 50; // ditto
// the distance on the graph that represents one unit
$bar_unit = ($width - ($x + $right_margin)) / 100; // one "point" on the graph
// This is the maximum length of the bars—from the baseline to the right margin—divided by 100 because the graph is going to show percentage values.
// Calculate height of graph - bars plus gaps plus some margin
$height = $num_candidates * ($bar_height + $bar_spacing) + 50; // the total height that you need for the canvas
/*******************************************
Set up base image
*******************************************/
// Create a blank canvas
$im = imagecreatetruecolor($width, $height);
// Allocate colors
$white = imagecolorallocate($im, 255, 255, 255);
$blue = imagecolorallocate($im, 0, 64, 128);
$black = imagecolorallocate($im, 0, 0, 0);
$pink = imagecolorallocate($im, 255, 78, 243);
$text_color = $black;
$percent_color = $black;
$bg_color = $white;
$line_color = $black;
$bar_color = $blue;
$number_color = $pink;
// Create "canvas" to draw on
imagefilledrectangle($im, 0, 0, $width, $height, $bg_color); // fill in the background for the graph
// The imagefilledrectangle() function, as you might imagine, draws a filled-in rectangle. The first parameter is, as usual, the image identifier. Then you must pass it the x and y coordinates of the start point and the end point of the rectangle. These points correspond to the upper-left corner and lower-right corner, respectively. In this case, you fill the entire canvas with the background color, which is the last parameter, and it’s white.
// Draw outline around canvas
imagerectangle($im, 0, 0, $width - 1, $height - 1, $line_color); // draw a black outline around the edge of the canvas. This function draws an outlined rectangle instead of a filled one. The parameters are the same. Notice that the rectangle is drawn to $width-1 and $height-1—a canvas of width by height goes from (0, 0) to these values. If you drew it to $width and $height, the rectangle would be outside the canvas area.
// Add title
$title = 'Poll Results';
$title_dimensions = imagettfbbox($title_size, 0, $font_name, $title);
$title_length = $title_dimensions[2] - $title_dimensions[0];
$title_height = abs($title_dimensions[7] - $title_dimensions[1]);
$title_above_line = abs($title_dimensions[7]);
$title_x = ($width - $title_length) / 2; // center it in x
$title_y = ($y - $title_height) / 2 + $title_above_line; // center in y gap
imagettftext(
$im,
$title_size,
0,
$title_x,
$title_y,
$text_color,
$font_name,
$title
);
// Draw a base line from a little above first bar location
// to a little below last
imageline($im, $x, $y - 5, $x, $height - 15, $line_color); // The imageline() function draws a line on the image you specify ($im) from one set of coordinates ($x, $y-5) to another ($x, $height-15), in the color specified by $line_color.
// In this case, you draw the baseline from a little above where you want to draw the first bar, to a little above the bottom of the canvas.
/*******************************************
Draw data into graph
*******************************************/
// Get each line of DB data and draw corresponding bars
while ($r_stmt->fetch()) {
if ($total_votes > 0) {
$percent = intval(($num_votes / $total_votes) * 100);
} else {
$percent = 0;
}
// Display percent for this value
$percent_dimensions = imagettfbbox($main_size, 0, $font_name, $percent . '%');
$percent_length = $percent_dimensions[2] - $percent_dimensions[0];
imagettftext($im, $main_size, 0, $width - $percent_length - $text_indent, $y + ($bar_height / 2), $percent_color, $font_name, $percent . '%'); // add labels
// Length of bar for this value
$bar_length = $x + ($percent * $bar_unit);
// Draw bar for this value
imagefilledrectangle($im, $x, $y - 2, $bar_length, $y + $bar_height, $bar_color); // draw the bars as filled rectangles
// Draw title for this value
imagettftext($im, $main_size, 0, $text_indent, $y + ($bar_height / 2), $text_color, $font_name, $candidate);
// Draw outline showing 100%
imagerectangle($im, $bar_length + 1, $y - 2, ($x + (100 * $bar_unit)), $y + $bar_height, $line_color); // add outlines for the 100% mark
// Display numbers
imagettftext($im, $small_size, 0, $x + (100 * $bar_unit) - 50, $y + ($bar_height / 2), $number_color, $font_name, $num_votes . '/' . $total_votes);
// Move down to next bar
$y = $y + ($bar_height + $bar_spacing);
}
/*******************************************
Display image
*******************************************/
header('Content-type: image/png');
imagepng($im); // output the image using imagepng()
/*******************************************
Clean up
*******************************************/
$r_stmt->free_result();
$db->close();
imagedestroy($im); // clean up using imagedestroy()
/**
* this script is missing is any sort of anticheating mechanism. Users would quickly discover that they can vote repeatedly and make the result meaningless.
*/
|
C
|
UTF-8
| 1,139
| 3.859375
| 4
|
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
struct node
{
int value;
struct node *l;
struct node *r;
};
typedef struct node node;
node *ptr, *root = NULL;
void createbinary()
{
root = getNode(50);
root->l = getNode(20);
root->r = getNode(30);
root->l->l = getNode(70);
root->l->r = getNode(80);
root->l->l->l = getNode(10);
root->l->l->r = getNode(40);
root->l->r->r = getNode(60);
}
node* getNode(int val)
{
ptr = (node*)malloc(sizeof(node));
if (ptr == NULL)
{
printf("Memory was not allocated");
return;
}
ptr->value = val;
ptr->l = NULL;
ptr->r = NULL;
return ptr;
}
int count(node *n)
{
int c = 1;
if (n == NULL)
return 0;
else
{
c += count(n->l);
c += count(n->r);
return c;
}
}
void preorder(node *t)
{
if (t != NULL)
{
printf("%d->", t->value);
preorder(t->l);
preorder(t->r);
}
}
int main()
{
int c;
createbinary();
preorder(root);
c = count(root);
printf("\nNumber of nodes in binary tree are:%d\n", c);
}
|
C
|
UTF-8
| 1,655
| 3.375
| 3
|
[] |
no_license
|
/*
** EPITECH PROJECT, 2020
** PSU_2019_malloc
** File description:
** list
*/
#include "malloc.h"
#include <unistd.h>
data_t *init_list(size_t size)
{
data_t *ret = sbrk(sizeof(data_t) + size);
ret->struct_size = sizeof(data_t);
ret->size = size;
ret->adress = sbrk(0) + ret->struct_size;
ret->isfree = 0;
ret->next = NULL;
ret->prev = NULL;
return (ret);
}
data_t *init_node(data_t *data, size_t size)
{
data_t *tmp = data;
tmp->next = sbrk(sizeof(data_t) + size);
tmp = tmp->next;
tmp->struct_size = sizeof(data_t);
tmp->size = size;
tmp->adress = sbrk(0) + tmp->struct_size;
tmp->isfree = 0;
tmp->next = NULL;
tmp->prev = data;
return (tmp);
}
data_t *re_node(data_t *data, size_t size)
{
data_t *tmp = data;
tmp->struct_size = sizeof(data_t);
tmp->size = size;
tmp->isfree = 0;
return (tmp);
}
data_t *put_back(data_t *data, size_t size)
{
data_t *tmp = data;
short isfree = 0;
if (tmp->next == NULL) {
tmp->next = init_node(tmp, size);
} else {
while (tmp->next != NULL) {
if (tmp->isfree == 1 && tmp->size > size) {
isfree = 1;
break;
}
tmp = tmp->next;
}
if (isfree == 1)
tmp = re_node(tmp, size);
else
tmp->next = init_node(tmp, size);
}
return (data);
}
data_t *pop_back(data_t *struc)
{
data_t *tmp = struc;
if (tmp->next == NULL) {
tmp = NULL;
} else {
while (tmp->next != NULL)
tmp = tmp->next;
tmp = NULL;
}
return (struc);
}
|
Java
|
UTF-8
| 1,351
| 3.234375
| 3
|
[] |
no_license
|
import java.util.*;
public class ColorfulStrings
{
private int[] digits;
private int n;
private int k;
private int count;
private int[] prods;
private boolean[] used;
public String getKth(int n, int k)
{
this.n = n;
this.k = k;
if (n == 1) {
if (k <= 10) {
return "" + (k - 1);
}
return "";
}
if (n > 8) {
return "";
}
digits = new int[n];
prods = new int[n];
used = new boolean[10];
count = 0;
gen(0);
String result = "";
if (count == k) {
for (int digit : digits) {
result += digit;
}
}
return result;
}
private void gen(int idx) {
if (count == k) {
return;
}
if (idx == n) {
if (check()) {
count++;
}
return;
}
for (int i = 2; i < 10; i++) {
if (count >= k) {
return;
}
if (!used[i]) {
used[i] = true;
digits[idx] = i;
gen(idx + 1);
used[i] = false;
}
}
}
private boolean check() {
Map <Integer, Boolean> map = new HashMap <Integer, Boolean>();
prods[0] = digits[0];
for (int i = 1; i < n; i++) {
prods[i] = prods[i - 1] * digits[i];
}
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int p = prods[j];
if (i > 0) {
p /= prods[i - 1];
}
if (map.containsKey(p)) {
return false;
} else {
map.put(p, true);
}
}
}
return true;
}
}
|
C
|
UTF-8
| 2,829
| 2.59375
| 3
|
[] |
no_license
|
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_event_loop.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "mdns.h"
// Event group
static EventGroupHandle_t wifi_event_group;
const int CONNECTED_BIT = BIT0;
// Wifi event handler
static esp_err_t event_handler(void *ctx, system_event_t *event)
{
switch(event->event_id) {
case SYSTEM_EVENT_STA_START:
esp_wifi_connect();
break;
case SYSTEM_EVENT_STA_GOT_IP:
xEventGroupSetBits(wifi_event_group, CONNECTED_BIT);
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
xEventGroupClearBits(wifi_event_group, CONNECTED_BIT);
break;
default:
break;
}
return ESP_OK;
}
// Main task
void main_task(void *pvParameter)
{
// mDNS server instance
mdns_server_t* mDNS = NULL;
// wait for connection
printf("Main task: waiting for connection to the wifi network... ");
xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT, false, true, portMAX_DELAY);
printf("connected!\n");
// print the local IP address
tcpip_adapter_ip_info_t ip_info;
ESP_ERROR_CHECK(tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_STA, &ip_info));
printf("IP Address: %s\n", ip4addr_ntoa(&ip_info.ip));
printf("Subnet mask: %s\n", ip4addr_ntoa(&ip_info.netmask));
printf("Gateway: %s\n", ip4addr_ntoa(&ip_info.gw));
// create and configure the mDNS server
ESP_ERROR_CHECK(mdns_init(TCPIP_ADAPTER_IF_STA, &mDNS));
ESP_ERROR_CHECK(mdns_set_hostname(mDNS, CONFIG_MDNS_HOSTNAME));
ESP_ERROR_CHECK(mdns_set_instance(mDNS, CONFIG_MDNS_INSTANCE));
while(1) {
vTaskDelay(1000 / portTICK_RATE_MS);
}
}
// Main application
void app_main()
{
// initialize NVS
ESP_ERROR_CHECK(nvs_flash_init());
// create the event group to handle wifi events
wifi_event_group = xEventGroupCreate();
// initialize the tcp stack
tcpip_adapter_init();
// initialize the wifi event handler
ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL));
// initialize the wifi stack in STAtion mode with config in RAM
wifi_init_config_t wifi_init_config = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&wifi_init_config));
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
// configure the wifi connection and start the interface
wifi_config_t wifi_config = {
.sta = {
.ssid = CONFIG_WIFI_SSID,
.password = CONFIG_WIFI_PASSWORD,
},
};
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));
ESP_ERROR_CHECK(esp_wifi_start());
printf("Connecting to %s\n", CONFIG_WIFI_SSID);
// start the main task
xTaskCreate(&main_task, "main_task", 2048, NULL, 5, NULL);
}
|
TypeScript
|
UTF-8
| 4,514
| 3.03125
| 3
|
[] |
no_license
|
/**
* validation.ts
* Provide functions for validating data
*/
// Node Modules
// NPM Modules
import { isUndefined } from 'lodash'
// Local Modules
import { IValidationFields } from '@osm/server'
// Constants and global variables
export class Validation {
private providedFields: any
/**
* Accept the provided input and what the required fields are
*/
constructor(providedFields: any) {
this.providedFields = providedFields
}
/**
* Check that all fields in an array are present and not null
* @param requiredFields Array of field names
* @param switchOn If this, validate on more fields
* @param extraRequiredFields Any more fields based on the switch
*/
public required(
requiredFields: string[],
switchOn?: string,
extraRequiredFields?
): IValidationFields[] {
if (!requiredFields) {
return [
{
isInvalid: true,
fieldName: 'all',
fieldValue: null
}
]
}
let fieldsToValidate: string[] = []
if (this.providedFields && this.providedFields[switchOn]) {
fieldsToValidate = requiredFields.concat(extraRequiredFields)
} else {
fieldsToValidate = requiredFields
}
const invalidFields: IValidationFields[] = []
for (const field of fieldsToValidate) {
if (
this.providedFields[field] !== undefined &&
this.providedFields[field] !== null &&
this.providedFields[field] !== ''
) {
continue
} else {
invalidFields.push({
isInvalid: true,
fieldName: field,
fieldValue: this.providedFields[field]
})
}
}
return invalidFields
}
/**
* Set default fields from provided object
* @param defaultFields Object containing defult field values to set
*/
public defaults(defaultFields): any {
if (!defaultFields) {
return this.providedFields
} else {
const defaultedFields = this.providedFields
for (const field of Object.keys(defaultFields)) {
if (!defaultedFields[field] || defaultedFields[field] === '') {
// Only set the default if the field does not exist
defaultedFields[field] = defaultFields[field]
} else {
continue
}
}
return defaultedFields
}
}
public truncate(fields: { field: string; length: number }[]): any {
for (const field of fields) {
const fieldInQuestion = this.providedFields[field.field]
if (field.field && fieldInQuestion) {
this.providedFields[field.field] = fieldInQuestion.slice(
0,
field.length
)
}
}
return this
}
public updateFields(allowableFields): any {
if (!allowableFields) {
return this.providedFields
} else {
const sanitizedObject: any = {}
for (const key of allowableFields) {
if (
this.providedFields[key] !== '' &&
this.providedFields[key] !== null &&
this.providedFields[key] !== undefined
) {
sanitizedObject[key] = this.providedFields[key]
}
}
return sanitizedObject
}
}
public exists() {
return this.providedFields !== null && this.providedFields !== undefined
}
public matches(test) {
return this.providedFields === test
}
public isEmail() {
const emailRegex = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/
return emailRegex.test(this.providedFields)
}
public notEmpty(fields: any, minLen?: number) {
const min = minLen || 0
if (Array.isArray(fields)) {
const validFields = {}
fields.map((field) => {
if (
!isUndefined(this.providedFields[field]) &&
this.providedFields[field].length > min
) {
validFields[field] = this.providedFields[field]
}
})
return validFields
} else if (typeof fields === 'object') {
const keys = Object.keys(fields)
const validFields: any = {}
keys.map((key) => {
if (typeof fields[key] === 'string' && fields[key].length > min) {
validFields[key] = fields[key]
}
})
return validFields
} else if (typeof fields === 'string') {
if (fields.length > min) {
return fields
} else {
return null
}
} else {
return null
}
}
}
export function isBoolean(val) {
return (
val === 'false' ||
typeof val === 'boolean' ||
val === 'true' ||
val === 1 ||
val === 0
)
}
|
Python
|
UTF-8
| 3,604
| 3.078125
| 3
|
[] |
no_license
|
#! /bin/python3
# vim: set expandtab:
'''
[begin_markdown get_started]
# Getting Started Using CurveFit
## Data Mean
The model for the mean of the data for this example is:
\[
f(t; \alpha, \beta, p) = \frac{p}{1 + \exp [ -\alpha(t - \beta) ]}
\]
where \( \alpha \), \( \beta \), and \( p \) are unknown parameters.
## Problem Settings
The following settings are used to simulate the data and check
that the solution is correct:
```python '''
n_data = 21 # number simulated measurements to generate
alpha_true = 2.0 # values of alpha, beta, p, used to simulate data
beta_true = 3.0
p_true = 4.0
rel_tol = 1e-6 # relative tolerance used to check optimal solution
'''```
## Simulated data
### Time Grid
A grid of *n_data* points in time, \( t_i \), where
\[
t_i = \mbox{beta_true} / ( \mbox{n_data} - 1 )
\]
The minimum value is zero for this grid is zero and its maximum is \( \beta \).
### Measurement values
We simulate data, \( y_i \), with no noise at each of the time points.
To be specific, for \( i = 0 , \ldots , \mbox{n_data} \)
\[
y_i = f( t_i , \mbox{alpha_true}, \mbox{beta_true}, \mbox{p_true} )
\]
Note that when we do the fitting, we model each data point as having
noise.
## Source Code
```python '''
# -------------------------------------------------------------------------
import sys
import pandas
import numpy
import sandbox
sandbox.path()
import curvefit
from curvefit.core.model import CurveModel
#
# number of parameters in this model
num_params = 3
#
# model for the mean of the data
def generalized_logistic(t, params) :
alpha = params[0]
beta = params[1]
p = params[2]
return p / ( 1.0 + numpy.exp( - alpha * ( t - beta ) ) )
#
# link function used for beta
def identity_fun(x) :
return x
#
# link function used for alpha, p
def exp_fun(x) :
return numpy.exp(x)
#
# inverse of function used for alpha, p
def log_fun(x) :
return numpy.log(x)
#
# params_true
params_true = numpy.array( [ alpha_true, beta_true, p_true ] )
#
# data_frame
independent_var = numpy.array(range(n_data)) * beta_true / (n_data-1)
measurement_value = generalized_logistic(independent_var, params_true)
measurement_std = n_data * [ 0.1 ]
constant_one = n_data * [ 1.0 ]
data_group = n_data * [ 'world' ]
data_dict = {
'independent_var' : independent_var ,
'measurement_value' : measurement_value ,
'measurement_std' : measurement_std ,
'constant_one' : constant_one ,
'data_group' : data_group ,
}
data_frame = pandas.DataFrame(data_dict)
#
# curve_model
col_t = 'independent_var'
col_obs = 'measurement_value'
col_covs = num_params *[ [ 'constant_one' ] ]
col_group = 'data_group'
param_names = [ 'alpha', 'beta', 'p' ]
link_fun = [ exp_fun, identity_fun, exp_fun ]
var_link_fun = link_fun
fun = generalized_logistic
col_obs_se = 'measurement_std'
#
curve_model = CurveModel(
data_frame,
col_t,
col_obs,
col_covs,
col_group,
param_names,
link_fun,
var_link_fun,
fun,
col_obs_se
)
#
# fit_params
inv_link_fun = [ log_fun, identity_fun, log_fun ]
fe_init = numpy.zeros( num_params )
for i in range(num_params) :
fe_init[i] = inv_link_fun[i](params_true[i] / 3.0)
curve_model.fit_params(fe_init)
params_estimate = curve_model.params
#
for i in range(num_params) :
rel_error = params_estimate[i] / params_true[i] - 1.0
assert abs(rel_error) < rel_tol
#
print('get_started.py: OK')
sys.exit(0)
''' ```
[end_markdown get_started]
'''
|
PHP
|
UTF-8
| 438
| 2.640625
| 3
|
[] |
no_license
|
<?php
ini_set('display_errors', 0);
function getTwitterStatus($userid, $x){
$url = "https://api.twitter.com/1/statuses/user_timeline/$userid.xml?count=$x&include_rts=1callback=?";
$xml = simplexml_load_file($url) or die("Unable to load news stream. Sorry!");
foreach($xml->status as $status){
$text = $status->text;
echo "<li>" . $text . "</li>";
}
}
// USAGE
getTwitterStatus("OnThePathYoga", $count);
?>
|
C++
|
UTF-8
| 1,590
| 2.796875
| 3
|
[] |
no_license
|
/*
https://leetcode.com/problems/count-the-repetitions/
Time: O(rep1 + M*N*(M+N)) ~ 10^6
Space: O(M*N) ~ 10^4
*/
class Solution {
public:
int getMaxRepetitions(string s1, int rep1, string s2, int rep2) {
int n = s1.size();
int m = s2.size();
vector<vector<int>> nxt_ptr_txt(m, vector<int>(n)), nxt_ptr_pat(m, vector<int>(n));
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int cur_pat = i, cur_txt = j;
while (cur_pat < m && cur_txt < n) {
if (s2[cur_pat] == s1[cur_txt]) cur_pat++;
cur_txt++;
}
nxt_ptr_txt[i][j] = cur_txt;
nxt_ptr_pat[i][j] = cur_pat;
}
}
int found_pat = 0;
int used_txt = 0;
int cur_txt = 0, cur_pat = 0;
while (used_txt < rep1) {
int nxt_on_txt = nxt_ptr_txt[cur_pat][cur_txt];
int nxt_on_pat = nxt_ptr_pat[cur_pat][cur_txt];
cur_txt = nxt_on_txt;
cur_pat = nxt_on_pat;
if (cur_txt == n) {
used_txt++;
cur_txt = 0;
}
if (cur_pat == m) {
found_pat++;
cur_pat = 0;
}
}
int max_reps = found_pat / rep2;
return max_reps;
}
};
|
SQL
|
UTF-8
| 1,394
| 2.90625
| 3
|
[] |
no_license
|
-- phpMyAdmin SQL Dump
-- version 4.8.3
-- https://www.phpmyadmin.net/
--
-- Host: localhost:8889
-- Generation Time: 2019 年 2 月 08 日 07:54
-- サーバのバージョン: 5.7.23
-- PHP Version: 7.2.10
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `localdb`
--
-- --------------------------------------------------------
--
-- テーブルの構造 `bbs_table`
--
CREATE TABLE `bbs_table` (
`id` int(12) NOT NULL,
`name` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
`comment` text COLLATE utf8_unicode_ci NOT NULL,
`date` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `bbs_table`
--
ALTER TABLE `bbs_table`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `bbs_table`
--
ALTER TABLE `bbs_table`
MODIFY `id` int(12) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Markdown
|
UTF-8
| 3,370
| 2.953125
| 3
|
[] |
no_license
|
# devjek example
Hello we are devjek! This is a repo to give you an example of what we can do for you. We chose to recreate a [web design](https://dribbble.com/shots/2144293-Redesign-Dropbox-Dashboard/attachments/392373) we found on Dribbble by [Muhammad Asad](https://dribbble.com/mrasad40). We took the .PSD file and created the webpage built with React components. We have it hosted as a [Storybook](https://devjekteam.github.io/devjek-example/) so you can check it out the components individually as well as play around with the full page.
The purpose of this repo is to allow you to audit the code and see what you can expect to receive in return when you deliver design assets to us.
### How devjek works
- Visit our [homepage](http://devjek.com) to upload your assets and select your timeframe.
- We work asynchronously to convert your code or design assets to React components.
- Once we are done we will share with you the Storybook showing our work in action.
- If you are satisfied with the work we will transfer the ownership of a repo just like this one to you with all the React components and storybook assets.
### See it all put together
[Click Here](https://devjekteam.github.io/devjek-example/) to check out all the components in action.
Alternatively to host the storybook on your machine:
- Install [yarn](https://yarnpkg.com/lang/en/docs/install/) or [npm](https://www.npmjs.com/get-npm). We use yarn as our package manager but npm v3.0.0 + should work as well. If you use npm simply substitute `npm` for all the `yarn` commands.
- Install dependencies
```
yarn install
```
- Run storybook
```
yarn run storybook
```
The storybook should be hosted at http://localhost:6006/
### Code layout
- In the root directory you will find **design.psd**. This is what we based our work off of and is an example of something that you can send to us to receive React components. A good .psd will include all of the assets we need to create an exact replica in code, such as images and fonts.
- **/stories** contains the default props and storybook examples that you see on our hosted page. This is a good place to look to see a working example of how you would integrate the components with your codebase.
- **/src** contains all of the source code and is what you will integrate into your own codebase.
- **/src/components** contains all of the barebones components that are the building blocks for the webpage.
- **/src/containers** contains groups of components put together to create a larger piece of the webpage. Examples include the Top Navigation bar and the File Grid.
- **/src/public** contains the assets needed to render the webpage. These include the "Files", images and icons that we took from the design.psd.
### Tech Stack
We create our React components using [ES6](https://github.com/lukehoban/es6features) syntax. In this example we did the styling with regular old CSS but on request can do styling with SASS, LESS or some other CSS extension language. We write tests for every component using Jest + Enzyme.
To run tests:
```
yarn run test
```
Every component has it's own styling and test located in the same directory as the source file.
We create our components to be as extensible as possible. We don't want to assume functionality and allow you to pass whatever javascript handlers you will need to the components.
|
JavaScript
|
UTF-8
| 449
| 2.5625
| 3
|
[] |
no_license
|
function Command(commandString='') {
this.childArguments = [];
this.value = commandString;
this.defaultAction = function() {
// map to service
}
this.help = function() {
console.log(`
${ `Command: `.gray } ${ `${this.value}`.blue }
${ `Arguments:`.gray } ${ this.childArguments }
`);
}
}
Command.prototype = Object.create(Command.prototype);
Command.prototype.constructor = Command;
module.exports = Command;
|
Java
|
UTF-8
| 822
| 2.0625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package dharma.github.io.mvvmsample.data.database;
import android.arch.lifecycle.LiveData;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.OnConflictStrategy;
import android.arch.persistence.room.Query;
import java.util.List;
import dharma.github.io.mvvmsample.constants.Constants;
import dharma.github.io.mvvmsample.data.model.GalleryModel;
@Dao
public interface GalleryModelDao {
@Query("SELECT * FROM " + Constants.DatabaseTables.GALLERY_MODEL)
LiveData<List<GalleryModel>> getGalleryModels();
@Query("SELECT * FROM " + Constants.DatabaseTables.GALLERY_MODEL)
List<GalleryModel> getAllGalleryModels();
@Insert(onConflict = OnConflictStrategy.IGNORE)
List<Long> insertGallery(List<GalleryModel> galleryModels);
}
|
JavaScript
|
UTF-8
| 6,172
| 2.890625
| 3
|
[] |
no_license
|
var center, weight;
function setup(){
createCanvas(700,500);
background('blue');
m = 50;//mass of block in kg
g = 1.5;//gravity
muSlider = createSlider(0.1,0.9,0.5,0.1);
muSlider.position(100,580);
mu_s = muSlider.value();//coefficient of static friction
mu_k = muSlider.value()/2;//kinetic
weight = new createVector(0,m*g);
mu = mu_s; //set as static friciton to start
//slider used to add/subtract y-value to apex of triangle, thus changing the angle of ramp
rampSlider = createSlider(-150,200,0);
rampSlider.position(100,550);
//calculate angle of ramp
theta = atan((400-(250-rampSlider.value))/(500));
//setup ramp triangular coordinates using vectors
rightCorner = new createVector(600,400);
apex = new createVector(100,250-rampSlider.value());
//calculate middle of incline as vector so that those coordinates can be used to draw the box
center = new createVector((apex.x+rightCorner.x)/2,(apex.y+rightCorner.y)/2);
friction = m*mu*g*cos(theta);
rampGrav = m*g*sin(theta);
//where x-dir is parallel to ramp and y-dir is normal to ramp
boxAccl = new createVector((rampGrav-friction)/m,0);
boxVel = 0;
boxPos = 0;
gravEnd = p5.Vector.add(center,weight);
gravVec = new Arrow(center,gravEnd);
gravVec.color= color('red');
gravVec.grab = false;
gravVec.draggable = false;
gravVec.showComponents = false;
reset = createButton('reset');
reset.position(200,200);
reset.mousePressed(reset2);
//frameRate(15);
}
//resets the box to middle of ramp and gives it 0 velocity and acceleration
reset2 = function(){
boxPos=0;
boxVel=0;
boxAccl = new createVector(0,0);
}
function draw(){
angleMode(DEGREES);
background('blue');
strokeWeight(1);
rectMode(CORNER);
fill('green');
rect(0,400,700,100); //just some scenic grass
mu_s = muSlider.value();//coefficient of static friction
mu_k = muSlider.value()/2;//kinetic
//coordinates again of triangle ramp and box location
rightCorner = new createVector(600,400);
apex = new createVector(100,250-rampSlider.value());
center = new createVector((apex.x+rightCorner.x)/2,(apex.y+rightCorner.y)/2);
//recalculate angle in case ramp geometry has changed
theta = atan((rightCorner.y-apex.y)/(rightCorner.x-apex.x));
if (boxVel == 0){
mu = mu_s;
} else{
mu = mu_k;
};
normalForce_= m*g*cos(theta);
friction = mu*normalForce_;
rampGrav = m*g*sin(theta);
//keeps box in equilibrium untill gravity overcomes friction
if (friction > rampGrav){
friction = rampGrav;
};
//where x-dir is parallel to ramp and y-dir is normal to ramp
//takes care of stopping sliding if ramp is lowered
if (friction < rampGrav){
boxVel = boxVel + boxAccl.x;
} else{
boxVel = 0;
};
netForce_ = rampGrav - friction;
//set position vector to be origin of all arrow objects
gravCenter = new createVector(center.x+(cos(theta)*(boxPos))+(sin(theta)*40), center.y-40+(sin(theta)*(boxPos+10)));
gravEnd = p5.Vector.add(gravVec.origin,weight);
gravVec = new Arrow(gravCenter,gravEnd);
normalForce = new createVector(normalForce_*sin(theta),-normalForce_*cos(theta));
normEnd = p5.Vector.add(gravCenter,normalForce);
normVec = new Arrow(gravCenter,normEnd);
if (friction == rampGrav){
frictionForce = new createVector(-rampGrav*cos(theta),-rampGrav*sin(theta));
} else if (boxPos > 200) {
frictionForce = new createVector(-rampGrav*cos(theta),-rampGrav*sin(theta));
} else {
frictionForce = new createVector(-friction*cos(theta),-friction*sin(theta));
};
frictionEnd = p5.Vector.add(gravCenter,frictionForce);
frictionVec = new Arrow(gravCenter,frictionEnd);
netForce = new createVector(cos(theta)*netForce_,sin(theta)*netForce_);
netForceEnd = p5.Vector.add(gravCenter,netForce);
netForceVec = new Arrow(gravCenter,netForceEnd);
if (boxPos > 200){
frictionVec.color = ('purple'); //turn into normal force from stopper
} else if(mu == mu_k){
frictionVec.color = color('green');
} else {
frictionVec.color = color('orange');
};
frictionVec.grab = false;
frictionVec.draggable = false;
frictionVec.showComponents = false;
gravVec.color= color('red');
gravVec.grab = false;
gravVec.draggable = false
gravVec.showComponents = false;
normVec.color = color('purple');
normVec.grab = false;
normVec.draggable = false;
normVec.showComponents = false;
netForceVec.color= color('orange');
netForceVec.grab = false;
netForceVec.draggable = false
netForceVec.showComponents = false;
netForceVec.width = 10;
//stops the box from moving when it reaches the stop
if(boxPos > 200){
boxPos=205;
boxVel = 0;
boxAccl = new createVector(0,0);
netForce_ = 0;
friction = rampGrav;
};
boxAccl = new createVector((rampGrav-friction)/m,0);
//vector was not used for velocity here because the box only moves uni-directionly along ramp
//this however should be changed and vectors should be used.....
boxPos = boxPos + boxVel;
//draw the ramp
fill('tan');
triangle(100,400,apex.x,apex.y,rightCorner.x,rightCorner.y);
//angle text output
fill('white');
text("Angle of Ramp = "+theta.toFixed(2)+" degrees",300,450);
text("Net Force = "+netForce_.toFixed(2)+" Newtons",500,475);
if (mu == mu_s){
text("Mu = "+mu+" Static",300,475);
} else{
text("Mu = "+mu+" Kinetic",300,475);
};
push();
rectMode(CENTER);
fill('brown');
translate(center.x,center.y);//translates coordinate to center so box rotates correctly
rotate(theta);//rotate box to be flush with ramp according to angle theta
rect(boxPos,-40,80,80);//(0,0) is new position of center
stroke('black');
strokeWeight(15);
//draw a stop for the box to prevent any weird transitions of box moving from ramp to ground
line(250,0,250,-40);
pop();
push();
gravVec.update();
gravVec.display();
normVec.update();
normVec.display();
frictionVec.update();
frictionVec.display();
netForceVec.update();
if (netForce_ > 0.001){
netForceVec.display();
};
pop();
// console.log(friction)
// console.log(rampGrav)
// console.log(mu)
// console.log(netForce_)
// console.log(boxVel)
// console.log(boxVel)
}
|
JavaScript
|
UTF-8
| 711
| 3.234375
| 3
|
[
"MIT"
] |
permissive
|
//business logic
// function player A(randomA) {
// this.randomA = randomA;
// }
// function player B(randomB) {
// this.randomB= randomB
// }
// playerA.prototype.scoreA =function() {
// return scoreA.randomA;
// }
// playerB.prototype.scoreB = function() {
// return scoreB.randomB;
// }
$(document).ready(function() {
var newplayerA=(player one);
var playerone =0;
$("form#"new playerA).submit(function(event) {
event.preventDefault();
var randomNumber A =Math.floor(Math.random() * 6) + 1;
if(randomNumber A===1){
alert("win!!");
}
else{
playerone += randomNumber A;
}
console.log(playerone);
};
)};
|
PHP
|
UTF-8
| 20,313
| 2.71875
| 3
|
[] |
no_license
|
<?php
class ParseQueries
{
protected $db;
protected $total_rows = 0;
protected $indexes = array();
protected $setting = array();
private function open_connection($host, $dbname)
{
try
{
$dsn = sprintf('mysql:host=%s;dbname=%s;', $host, $dbname);
$this->db = new PDO($dsn, 'dba', 'gorillamaster789');
}
catch(PDOException $ex)
{
echo sprintf("Couldn't open db connection by %s: %s \n", $ex->getCode(), $ex->getMessage());
}
}
public function __construct($settings)
{
$this->setting = $settings;
$this->open_connection($settings['host'], $settings['dbname']);
if (!isset($this->db))
die("Couldn't open connection with database server \n");
}
public function get_update_explain($query)
{
$regexp = "/^(update)(.+)(set)\s+(.+)\s*/i";
$result = "";
$matches = array();
$matches2 = array();
preg_match($regexp, $query, $matches);
if(!empty($matches[2]))
{
if(strpos($matches[4], "where") > 0)
{
$regexp = "/(.*)where?(.*)/i";
preg_match($regexp, $matches[4], $matches2);
$result = sprintf("select %s from %s where %s ", trim($matches2[1]), trim($matches[2]), trim($matches2[2]));
}
else if(strpos($matches[4], "order by") !== false)
{
$regexp = "/(.*)order by?(.*)/i";
preg_match($regexp, $matches[4], $matches2);
$result = sprintf("select %s from %s order by %s ", trim($matches2[1]), trim($matches[2]), trim($matches2[2]));
}
else if(strpos($matches[4], "limit") !== false)
{
$regexp = "/(.*)limit?(.*)/i";
preg_match($regexp, $matches[4], $matches2);
$result = sprintf("select %s from %s limit %s ", trim($matches2[1]), trim($matches[2]), trim($matches2[2]));
}
else
$result = sprintf("select %s from %s ", trim($matches[4]), trim($matches[2]));
}
return $result;
}
private function get_index_statistics($dbname, $tablename, $indexname)
{
$sql = sprintf("SELECT GROUP_CONCAT(CARDINALITY ORDER BY SEQ_IN_INDEX SEPARATOR ', ') AS Cardinality,
GROUP_CONCAT(COLUMN_NAME ORDER BY SEQ_IN_INDEX SEPARATOR ', ') AS Columns
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_NAME = '%s' AND TABLE_SCHEMA = '%s' AND
INDEX_NAME = '%s';",
$tablename, $dbname, $indexname);
$stmt2 = $this->db->prepare($sql);
$result = array("Usage" => 0, "Cardinality" => "", "Columns" => "");
try
{
if ($stmt2->execute())
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC))
$result = array("Usage" => 0,
"Cardinality" => $row["Cardinality"],
"Columns" => $row["Columns"]);
else
echo sprintf("Statement %s\n\terror code %s => %s \n", $sql, $stmt2->errorCode(), implode(' ', $stmt2->errorInfo()));
$stmt2->closeCursor();
}
catch(PDOException $ex)
{
echo sprintf("Couldn't read index statistics from table %s\n\t%s: %s\n", $tablename, $ex->getCode(), $ex->getMessage());
}
$sql = sprintf("SELECT TABLE_ROWS FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '%s' AND TABLE_SCHEMA = '%s'",
$tablename, $dbname);
$stmt2 = $this->db->prepare($sql);
$stmt2->execute();
$row = $stmt2->fetch(PDO::FETCH_ASSOC);
$this->total_rows = $row["TABLE_ROWS"];
$stmt2->closeCursor();
return $result;
}
public function get_indexes_from_table()
{
$sql = sprintf("SELECT INDEX_NAME
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_NAME = '%s' AND TABLE_SCHEMA = '%s'
GROUP BY INDEX_NAME",
$this->setting['tablename'], $this->setting['dbname']);
$stmt = $this->db->prepare($sql);
$result_set = array("FullScan" => array("Usage" => 0, "Cardinality" => 0, "Columns" => ""));
try
{
if ($stmt->execute())
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$usage = $this->get_index_statistics($this->setting['dbname'],
$this->setting['tablename'],
$row['INDEX_NAME']);
$result_set = array_merge($result_set,
array($row['INDEX_NAME'] => $usage));
}
else
echo sprintf("Statement %s\n\terror code %s => %s \n", $sql, $stmt->errorCode(), implode(' ', $stmt->errorInfo()));
$stmt->closeCursor();
}
catch(PDOException $ex)
{
echo sprintf("Couldn't read indexes from table %s\n\t%s: %s\n", $table_name, $ex->getCode(), $ex->getMessage());
}
$this->indexes = $result_set;
return true;
}
public function parse_file()
{
$files = explode(",", $this->setting['filename']);
$result_set = array();
foreach($files as $file)
{
echo sprintf("\t\tParsing file %s ... \n", $file);
$shell_command = sprintf("grep -v '#' %s | grep -iv 'show create table'", $file);
$data = explode('\G', shell_exec($shell_command));
echo sprintf("\t\t\t%0d queries extracted from file %s \n", count($data), $file);
foreach ($data as $row)
if (strpos($row, 'EXPLAIN') == false &&
strpos($row, 'checksums') === false &&
strpos($row, 'chunk boundary') === false)
$result_set[] = trim(str_replace('`', '', $row));
}
return preg_grep("/^(select)/i", $result_set);
}
private function get_table_alias($data, $tablename)
{
$matches = array();
$regexp = sprintf('~(from|join)\s(%s)\s(as)?\s*([a-z]+)\s~', $tablename);
$result = array();
$result[] = $tablename;
foreach($data as $query)
{
$query = strtolower($query);
preg_match($regexp, $query, $matches);
if (count($matches))
if (trim($matches[(count($matches) -1 )]) !== "where")
{
$alias = trim($matches[(count($matches) -1 )]);
if (array_search($alias, $result) === false && isset($alias))
$result[] = $alias;
}
}
return $result;
}
private function check_disk_usage($row)
{
$result = array("Temporary" => false, "Filesort" => false);
if (!empty($row["Extra"]))
{
if (strpos($row["Extra"], "temporary") !== false)
$result["Temporary"] = true;
if (strpos($row["Extra"], "filesort") !== false)
$result["Filesort"] = true;
}
return $result;
}
private function check_join_buffer($row)
{
$result = array("BufferJoin" => false);
if (!empty($row["Extra"]) && strpos($row["Extra"], "Using join buffer") !== false)
$result["BufferJoin"] = true;
return $result;
}
private function compare_column($array1, $array2)
{
if ($array1["Usage"] == $array2["Usage"])
return 0;
return ($array1["Usage"] < $array2["Usage"]) ? -1 : 1;
}
private function get_remove_indexes_sql()
{
$result = array();
foreach($this->indexes as $index => $stats)
{
if($stats["Usage"] === 0 && $index !== "FullScan")
$result[] = sprintf(" DROP INDEX %s", $index);
}
$return_value = "";
if (!empty($result))
$return_value = sprintf("ALTER TABLE %s.%s \n%s;", $this->setting["dbname"],
$this->setting["tablename"], implode(",\n", $result));
return $return_value;
}
public function check_indexes($data)
{
$tablename = $this->setting["tablename"];
$output_file = "";
$filename = '';
if (isset($this->setting["index"]))
$filename = sprintf("%s_%s_index_usage.sql", $tablename, $this->setting["index"]);
else
$filename = sprintf("%s_index_usage.sql", $tablename);
if (isset($this->setting["output"]))
$output_file = sprintf("%s/%s", $this->setting["output"], $filename);
else
$output_file = $filename;
if (file_exists($output_file))
unlink($output_file);
$tablename = strtolower($tablename);
$table_alias = $this->get_table_alias($data, $tablename);
$handler = fopen($output_file, "w");
$buffer_line = sprintf("Query summary for %s table \n\n", $tablename);
fwrite($handler, $buffer_line);
$result = array();
$query_no = 1;
$queries = count($data);
$counter = 0;
foreach($data as $query)
{
$query = strtolower($query);
$sql = sprintf("EXPLAIN %s \n", $query);
$stmt = $this->db->prepare($sql);
$counter++;
echo sprintf("\t\tProcessing query %0d of %0d ... \n", $counter, $queries);
if ($stmt->execute())
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
if (array_search(strtolower($row['table']), $table_alias) !== false)
{
$diskUsage = $this->check_disk_usage($row);
$joinbufferUsage = $this->check_join_buffer($row);
$result_set = array("query_no" => $query_no,
"query" => $query,
"index_used" => $row['key'],
"rows" => $row['rows']);
$query_no++;
if (isset($row['key']))
{
$keys = explode(",", $row['key']);
foreach($keys as $key)
if (isset($this->indexes[$key]))
$this->indexes[$key]["Usage"] += 1;
}
else
$this->indexes["FullScan"]["Usage"] += 1;
$buffer_line = sprintf("\n\n# Query # %0d: \n# EXPLAIN PARTITIONS \n%s;\n\n# Index used => %s ( %s rows / %s%% used) \n",
$result_set['query_no'], $result_set['query'],
empty($result_set['index_used'])? "Full Table Scan" : $result_set['index_used'],
number_format($result_set['rows'], 0), number_format(($result_set['rows'] / $this->total_rows) * 100, 2));
if (isset($this->setting["index"]))
if ($this->setting["index"] == $result_set['index_used'])
{
fwrite($handler, $buffer_line);
if ($diskUsage["Temporary"] || $diskUsage["Filesort"])
{
$buffer_line = sprintf("\n# WARNING!!!! This query has activity disk and potencialy is giving more cpu activity\n");
fwrite($handler, $buffer_line);
}
}
else
continue;
elseif (isset($this->setting["exclude"]))
if ($this->setting["exclude"] == $result_set['index_used'])
continue;
else
{
fwrite($handler, $buffer_line);
if ($diskUsage["Temporary"] || $diskUsage["Filesort"])
{
$buffer_line = sprintf("\n# WARNING!!!! This query has activity disk and potencialy is giving more cpu activity\n");
fwrite($handler, $buffer_line);
}
}
elseif (isset($this->setting["join_buffer"]))
if ($joinbufferUsage["BufferJoin"])
{
fwrite($handler, $buffer_line);
if ($diskUsage["Temporary"] || $diskUsage["Filesort"])
{
$buffer_line = sprintf("\n# WARNING!!!! This query has activity disk and potencialy is giving more cpu activity\n");
fwrite($handler, $buffer_line);
}
}
else
continue;
else
{
fwrite($handler, $buffer_line);
if ($diskUsage["Temporary"] || $diskUsage["Filesort"])
{
$buffer_line = sprintf("\n# WARNING!!!! This query has activity disk and potencialy is giving more cpu activity\n");
fwrite($handler, $buffer_line);
}
}
}
}
}
$stmt->closeCursor();
}
$line_length = 230;
$buffer_line = sprintf("\n\n\n\n# %s\n", str_repeat("-", $line_length));
fwrite($handler, $buffer_line);
$buffer_line = sprintf("# |%s Index %s|%s Usage %s|%s Cardinality %s|%s Columns %s|\n", str_repeat(" ",25), str_repeat(" ",25),
str_repeat(" ",8), str_repeat(" ",8), str_repeat(" ",25), str_repeat(" ",25), str_repeat(" ",37),
str_repeat(" ",37));
fwrite($handler, $buffer_line);
$buffer_line = sprintf("# %s\n", str_repeat("-", $line_length));
fwrite($handler, $buffer_line);
// usort($this->indexes, array($this, "compare_column"));
foreach($this->indexes as $index => $stats)
{
$buffer_line = sprintf("# | %s %s|%s %s |%s %s | %s %s|\n", $index, str_repeat(" ", (55 - strlen($index))),
str_repeat(" ", (21 - strlen($stats["Usage"]))), $stats["Usage"],
str_repeat(" ", (61 - strlen($stats["Cardinality"]))), $stats["Cardinality"],
$stats["Columns"], str_repeat(" ", (81 - strlen($stats["Columns"]))));
fwrite($handler, $buffer_line);
}
$buffer_line = sprintf("# %s\n\n", str_repeat("-", $line_length));
fwrite($handler, $buffer_line);
$buffer_line = $this->get_remove_indexes_sql();
fwrite($handler, $buffer_line);
fclose($handler);
}
}
class OptionsManager
{
protected $shortOpts = "h:d:t:f:?::o:i:e:j::";
protected $longOpts = array("host:", "dbname:", "tablename:", "filename:", "help::", "output:", "index:", "exclude:", "join_buffer::");
private function print_Usage()
{
$usageLine = "
Welcome to Vaquita Index Usage, this tool provides you an idea how each query runs on your schema,
and provides which index is used by each query and a summary for all the indexes.
This script requires an output file from pt-query-digest which extract all the queries used on specific table.
-h, --host Database Host to run explain queries
-d, --dbname Database Name which contains table to evaluate
-t, --tablename Table Name to check index usage
-f, --filename File name which contains pt-query-digest result, should include full path
-o, --output Path for output file
-i, --index Specific Index to get evaluate
-e, --exclude Index Name you want to exclude be written in the output file
-j, --join_buffer This flag, would get only the queries using join buffer instead of index
-?, --help Show this screen
Output: returns a file named <tablename>_index_usage.sql located in the same path from this script
";
echo sprintf("\n%s\n", $usageLine);
}
private function validate_options($options)
{
$result = array();
foreach($options as $key => $option)
{
switch($key)
{
case "f":
case "filename":
if (gettype($option) == "string")
$result = array_merge($result, array("filename" => $option));
break;
case "h":
case "host":
if (gettype($option) == "string")
$result = array_merge($result, array("host" => $option));
break;
case "d":
case "dbname":
if (gettype($option) == "string")
$result = array_merge($result, array("dbname" => $option));
break;
case "t":
case "tablename":
if (gettype($option) == "string")
$result = array_merge($result, array("tablename" => $option));
break;
case "o":
case "output":
if (gettype($option) == "string")
$result = array_merge($result, array("output" => $option));
break;
case "i":
case "index":
if (gettype($option) == "string")
$result = array_merge($result, array("index" => $option));
break;
case "e":
case "exclude":
if (gettype($option) == "string")
$result = array_merge($result, array("exclude" => $option));
break;
case "j":
case "join_buffer":
$result = array_merge($result, array("join_buffer" => true));
break;
case "?":
case "help":
$this->print_Usage();
die();
}
}
return $result;
}
public function get_options()
{
$options = getopt($this->shortOpts, $this->longOpts);
$result = $this->validate_options($options);
if (!isset($result["host"]) || !isset($result["tablename"]) ||
!isset($result["dbname"]) || !isset($result["filename"]))
{
$this->print_Usage();
var_dump($options);
die();
}
return $result;
}
}
$options = new OptionsManager();
$setting = $options->get_options();
echo sprintf("Initializing class to parse queries... \n");
$parse = new ParseQueries($setting);
echo sprintf("\tGetting indexes from table %s... \n", $setting["tablename"]);
$parse->get_indexes_from_table();
echo sprintf("\tInitializing process to check each index... \n");
$parse->check_indexes($parse->parse_file());
?>
|
Python
|
UTF-8
| 582
| 3.1875
| 3
|
[] |
no_license
|
class Movie():
"""A class movie which have some movie attributes
Attributes:
title (str): the title of the movie
post_image_url (str): The link to the image of the movie
trailer_youtube_url (str): The link to the trailer
story (str): the story of the movie
"""
def __init__(self, movie_title, movie_poster_image, movie_youtube_url,
movie_story):
self.title = movie_title
self.poster_image_url = movie_poster_image
self.trailer_youtube_url = movie_youtube_url
self.story = movie_story
|
Java
|
UTF-8
| 802
| 1.78125
| 2
|
[] |
no_license
|
package com.liyuan.ecommerce.domain.po.memberlevel;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
@Data
public class MemberLevelPo implements Serializable {
/**
* 主键
*/
private Integer id;
/**
* 等级值
*/
private String levelValue;
/**
* 登记名称
*/
private String levelName;
/**
* 最小经验值
*/
private Integer minExperienceValue;
/**
* 最大经验值
*/
private Integer maxExperienceValue;
/**
* 添加时间
*/
private Date addTime;
/**
* 添加人
*/
private String addUserId;
/**
* 修改操作时间
*/
private Date optTime;
/**
* 修改操作人
*/
private String optUserId;
/**
* 状态,1启用,0禁用
*/
private Integer state;
/**
* 是否删除,1是0否
*/
private Integer isDelete;
}
|
Markdown
|
UTF-8
| 9,136
| 2.5625
| 3
|
[
"Apache-2.0"
] |
permissive
|
# HyperflexWitnessConfigurationAllOf
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**ClassId** | **string** | The fully-qualified name of the instantiated, concrete type. This property is used as a discriminator to identify the type of the payload when marshaling and unmarshaling data. | [default to "hyperflex.WitnessConfiguration"]
**ObjectType** | **string** | The fully-qualified name of the instantiated, concrete type. The value should be the same as the 'ClassId' property. | [default to "hyperflex.WitnessConfiguration"]
**ConnectionError** | Pointer to **string** | The detailed connection error to the external witness. Empty if status is connected. | [optional] [readonly]
**CustomWitnessEnabled** | Pointer to **bool** | Custom witness has been configured by user. | [optional] [readonly]
**Fingerprint** | Pointer to **string** | The fingerprint of the witness server, identifies the revision of the witness servers database. Only applicable if custom witness has been enabled in the cluster, otherwise value is always empty. | [optional] [readonly]
**Status** | Pointer to **string** | Status of the devices connection to the witness. Device will report status as either 'Connected' or 'NotConnected'. | [optional] [readonly]
**Version** | Pointer to **string** | The version of the custom witness server. Only applicable if custom witness has been enabled in the cluster, otherwise value is always empty. | [optional] [readonly]
**WitnessUrl** | Pointer to **string** | URL of the witness endpoint, including IP/host and path. Only applicable if custom witness has been enabled in the cluster, otherwise value is always empty. | [optional] [readonly]
**Cluster** | Pointer to [**HyperflexClusterRelationship**](HyperflexClusterRelationship.md) | | [optional]
## Methods
### NewHyperflexWitnessConfigurationAllOf
`func NewHyperflexWitnessConfigurationAllOf(classId string, objectType string, ) *HyperflexWitnessConfigurationAllOf`
NewHyperflexWitnessConfigurationAllOf instantiates a new HyperflexWitnessConfigurationAllOf object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewHyperflexWitnessConfigurationAllOfWithDefaults
`func NewHyperflexWitnessConfigurationAllOfWithDefaults() *HyperflexWitnessConfigurationAllOf`
NewHyperflexWitnessConfigurationAllOfWithDefaults instantiates a new HyperflexWitnessConfigurationAllOf object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetClassId
`func (o *HyperflexWitnessConfigurationAllOf) GetClassId() string`
GetClassId returns the ClassId field if non-nil, zero value otherwise.
### GetClassIdOk
`func (o *HyperflexWitnessConfigurationAllOf) GetClassIdOk() (*string, bool)`
GetClassIdOk returns a tuple with the ClassId field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetClassId
`func (o *HyperflexWitnessConfigurationAllOf) SetClassId(v string)`
SetClassId sets ClassId field to given value.
### GetObjectType
`func (o *HyperflexWitnessConfigurationAllOf) GetObjectType() string`
GetObjectType returns the ObjectType field if non-nil, zero value otherwise.
### GetObjectTypeOk
`func (o *HyperflexWitnessConfigurationAllOf) GetObjectTypeOk() (*string, bool)`
GetObjectTypeOk returns a tuple with the ObjectType field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetObjectType
`func (o *HyperflexWitnessConfigurationAllOf) SetObjectType(v string)`
SetObjectType sets ObjectType field to given value.
### GetConnectionError
`func (o *HyperflexWitnessConfigurationAllOf) GetConnectionError() string`
GetConnectionError returns the ConnectionError field if non-nil, zero value otherwise.
### GetConnectionErrorOk
`func (o *HyperflexWitnessConfigurationAllOf) GetConnectionErrorOk() (*string, bool)`
GetConnectionErrorOk returns a tuple with the ConnectionError field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetConnectionError
`func (o *HyperflexWitnessConfigurationAllOf) SetConnectionError(v string)`
SetConnectionError sets ConnectionError field to given value.
### HasConnectionError
`func (o *HyperflexWitnessConfigurationAllOf) HasConnectionError() bool`
HasConnectionError returns a boolean if a field has been set.
### GetCustomWitnessEnabled
`func (o *HyperflexWitnessConfigurationAllOf) GetCustomWitnessEnabled() bool`
GetCustomWitnessEnabled returns the CustomWitnessEnabled field if non-nil, zero value otherwise.
### GetCustomWitnessEnabledOk
`func (o *HyperflexWitnessConfigurationAllOf) GetCustomWitnessEnabledOk() (*bool, bool)`
GetCustomWitnessEnabledOk returns a tuple with the CustomWitnessEnabled field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetCustomWitnessEnabled
`func (o *HyperflexWitnessConfigurationAllOf) SetCustomWitnessEnabled(v bool)`
SetCustomWitnessEnabled sets CustomWitnessEnabled field to given value.
### HasCustomWitnessEnabled
`func (o *HyperflexWitnessConfigurationAllOf) HasCustomWitnessEnabled() bool`
HasCustomWitnessEnabled returns a boolean if a field has been set.
### GetFingerprint
`func (o *HyperflexWitnessConfigurationAllOf) GetFingerprint() string`
GetFingerprint returns the Fingerprint field if non-nil, zero value otherwise.
### GetFingerprintOk
`func (o *HyperflexWitnessConfigurationAllOf) GetFingerprintOk() (*string, bool)`
GetFingerprintOk returns a tuple with the Fingerprint field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetFingerprint
`func (o *HyperflexWitnessConfigurationAllOf) SetFingerprint(v string)`
SetFingerprint sets Fingerprint field to given value.
### HasFingerprint
`func (o *HyperflexWitnessConfigurationAllOf) HasFingerprint() bool`
HasFingerprint returns a boolean if a field has been set.
### GetStatus
`func (o *HyperflexWitnessConfigurationAllOf) GetStatus() string`
GetStatus returns the Status field if non-nil, zero value otherwise.
### GetStatusOk
`func (o *HyperflexWitnessConfigurationAllOf) GetStatusOk() (*string, bool)`
GetStatusOk returns a tuple with the Status field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetStatus
`func (o *HyperflexWitnessConfigurationAllOf) SetStatus(v string)`
SetStatus sets Status field to given value.
### HasStatus
`func (o *HyperflexWitnessConfigurationAllOf) HasStatus() bool`
HasStatus returns a boolean if a field has been set.
### GetVersion
`func (o *HyperflexWitnessConfigurationAllOf) GetVersion() string`
GetVersion returns the Version field if non-nil, zero value otherwise.
### GetVersionOk
`func (o *HyperflexWitnessConfigurationAllOf) GetVersionOk() (*string, bool)`
GetVersionOk returns a tuple with the Version field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetVersion
`func (o *HyperflexWitnessConfigurationAllOf) SetVersion(v string)`
SetVersion sets Version field to given value.
### HasVersion
`func (o *HyperflexWitnessConfigurationAllOf) HasVersion() bool`
HasVersion returns a boolean if a field has been set.
### GetWitnessUrl
`func (o *HyperflexWitnessConfigurationAllOf) GetWitnessUrl() string`
GetWitnessUrl returns the WitnessUrl field if non-nil, zero value otherwise.
### GetWitnessUrlOk
`func (o *HyperflexWitnessConfigurationAllOf) GetWitnessUrlOk() (*string, bool)`
GetWitnessUrlOk returns a tuple with the WitnessUrl field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetWitnessUrl
`func (o *HyperflexWitnessConfigurationAllOf) SetWitnessUrl(v string)`
SetWitnessUrl sets WitnessUrl field to given value.
### HasWitnessUrl
`func (o *HyperflexWitnessConfigurationAllOf) HasWitnessUrl() bool`
HasWitnessUrl returns a boolean if a field has been set.
### GetCluster
`func (o *HyperflexWitnessConfigurationAllOf) GetCluster() HyperflexClusterRelationship`
GetCluster returns the Cluster field if non-nil, zero value otherwise.
### GetClusterOk
`func (o *HyperflexWitnessConfigurationAllOf) GetClusterOk() (*HyperflexClusterRelationship, bool)`
GetClusterOk returns a tuple with the Cluster field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetCluster
`func (o *HyperflexWitnessConfigurationAllOf) SetCluster(v HyperflexClusterRelationship)`
SetCluster sets Cluster field to given value.
### HasCluster
`func (o *HyperflexWitnessConfigurationAllOf) HasCluster() bool`
HasCluster returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
|
Python
|
UTF-8
| 1,204
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
from django.db import models
from random import randrange
from datetime import timedelta
from django.utils import timezone
# http://www.crockford.com/wrmg/base32.html
# Should reduce confusion on characters when typing in from a phone. No I/1 l/I l/1 confusion.
CHARSET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'
LENGTH = 10
# This model is based largely on the model available at:
# https://github.com/workmajj/django-unique-random/
class TextMessageShortCode(models.Model):
code = models.CharField(max_length=LENGTH)
token = models.CharField(max_length=256)
created = models.DateTimeField(auto_now_add=True)
def save(self, *args, **kwargs):
# Delete old tokens first.
TextMessageShortCode.objects.filter(created__lte=timezone.now()-timedelta(days=7)).delete()
unique = False
while not unique:
new_code = ''
for _ in range(LENGTH):
new_code += CHARSET[randrange(0, len(CHARSET))]
if not TextMessageShortCode.objects.filter(code=new_code):
self.code = new_code
unique = True
super(TextMessageShortCode, self).save(*args, **kwargs)
|
Shell
|
UTF-8
| 924
| 3.546875
| 4
|
[
"MIT"
] |
permissive
|
#!/bin/bash
source ${0%/*}/utils/common.sh
function usage() {
cat <<EOF
Usage: $0 [options]
-h| --help Display help text.
-n| --no-questions No interactive mode (default behavior by default: raspbian image cache is not re-downloaded).
EOF
}
while [[ $# -gt 0 ]]; do
KEY="$1"
case $KEY in
-h|--help)
DISPLAY_HELP=true
;;
-n|--no-questions)
NO_QUESTIONS=true
;;
*)
;;
esac
shift
done
if [[ $DISPLAY_HELP ]]; then
usage
exit 0
fi
RASPBIAN_ARG=''
if [[ $NO_QUESTIONS ]]; then
RASPBIAN_ARG='--no-download'
fi
check_env_vars
cd utils
./init-common.sh
./synchronize-toolchain.sh
./download-raspbian.sh $RASPBIAN_ARG
./prepare-sysroot-full.sh
./prepare-sysroot-minimal.sh
./switch-sysroot.sh full
./synchronize-qt-modules.sh
./compile-qt-modules.sh --clean-output --clean-modules-repo
|
JavaScript
|
UTF-8
| 7,775
| 2.609375
| 3
|
[] |
no_license
|
var createStatement = "CREATE TABLE IF NOT EXISTS TaskNotification (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, duedate TEXT, tasktype TEXT, created_by TEXT, assigned_to TEXT, deal_id INTEGER, is_complete INTEGER, is_notified INTEGER)";
var createLoginStatement = "CREATE TABLE IF NOT EXISTS is_login (id INTEGER PRIMARY KEY AUTOINCREMENT, is_login INTEGER, is_record_insert INTEGER)";
var selectAllStatement = "SELECT * FROM TaskNotification where is_notified = 0";
var selectLoginStatement = "SELECT * FROM is_login";
var insertStatement = "INSERT INTO TaskNotification (title, duedate, tasktype, created_by, assigned_to, deal_id, is_complete, is_notified ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
var insertloginStatement = "INSERT INTO is_login (is_login, is_record_insert ) VALUES (?,?)";
var updateStatement = "UPDATE TaskNotification SET is_notified = ? WHERE id=?";
var deleteStatement = "DELETE FROM TaskNotification WHERE id=?";
var dropStatement = "DROP TABLE TaskNotification";
var dropLoginStatement = "DROP TABLE is_login";
var truncateStatement = "TRUNCATE TABLE TaskNotification";
var db = openDatabase("TaskReminder", "1.0", "Task Notification Reminder", 200000); // Open SQLite Database
var dataset;
var DataType;
function initDatabase() // Function Call When Page is ready.
{
try {
if (!window.openDatabase) // Check browser is supported SQLite or not.
{
alert('Databases are not supported in this browser.');
}
else {
createTable(); // If supported then call Function for create table in SQLite
}
}
catch (e) {
if (e == 2) {
// Version number mismatch.
console.log("Invalid database version.");
} else {
console.log("Unknown error " + e + ".");
}
return;
}
}
function createTable() // Function for Create Table in SQLite.
{
db.transaction(function (tx) { tx.executeSql(createStatement, []); });
db.transaction(function (tx) { tx.executeSql(createLoginStatement, []); });
}
function insertLoginRecord(){
var logv= "1"
db.transaction(function (tx) { tx.executeSql(insertloginStatement, [logv,logv]); });
}
function insertRecord() // Get value from Input and insert record . Function Call when Save/Submit Button Click..
{
//var title = "5th deal/5th task";
//var duedate = "2014-04-04 18:24:00"; //yy-dd-mm
//var tasktype = "Followup";
//var created_by = "Srikant";
//var assigned_to = "Deepak";
//var is_complete = "0";
//var is_notified = "0";
$.ajax({ type: "get", url: "/get_sqllite_task", dataType: 'json', async: false,
beforeSend: function(){
},
success: function(data){
},
error: function(data) {
},
complete: function(datares) {
//alert(JSON.stringify(datares.responseJSON, null, 4));
if(datares.responseJSON.length>0){
$.each(datares.responseJSON, function(i, obj) {
//alert(obj.title);
db.transaction(function (tx) { tx.executeSql(insertStatement, [obj.title, obj.duedate, obj.tasktype, obj.created_by, obj.assigned_to, obj.deal_id, obj.is_complete, obj.is_notified]); });
});
check_notification();
}
}
});
//tx.executeSql(SQL Query Statement,[ Parameters ] , Sucess Result Handler Function, Error Result Handler Function );
}
function deleteRecord(id) // Get id of record . Function Call when Delete Button Click..
{
var iddelete = id.toString();
db.transaction(function (tx) { tx.executeSql(deleteStatement, [id]); alert("Delete Sucessfully"); });
}
function updateRecord(noti,id) // Get id of record . Function Call when Delete Button Click..
{
db.transaction(function (tx) { tx.executeSql(updateStatement, [noti, id]); });
}
function dropTable() // Function Call when Drop Button Click.. Talbe will be dropped from database.
{
db.transaction(function (tx) { tx.executeSql(dropStatement, []); });
db.transaction(function (tx) { tx.executeSql(dropLoginStatement, []); });
//initDatabase();
}
function onError(tx, error) // Function for Hendeling Error...
{
//alert(error.message);
}
function get_login_info(){
db.transaction(function (tx) {
tx.executeSql(selectLoginStatement, [], function (tx, result) {
$('#hdn_sqllite').val("1");
},
function(tx, error) {
dropTable();
initDatabase();
insertRecord();
insertLoginRecord(1,1);
});
});
}
function showRecords() // Function For Retrive data from Database Display records as list
{
db.transaction(function (tx) {
tx.executeSql(selectAllStatement, [], function (tx, result) {
//alert('fire');
dataset = result.rows;
k=0;
for (var i = 0, item = null; i < dataset.length; i++) {
item = dataset.item(i);
var dateObj = new Date(item['duedate']);
var curdateobj = new Date();
var dtobj = new Date();
curdateobj.setMinutes(curdateobj.getMinutes() + 10);
if(curdateobj > dateObj )
{
//curdateobj.setMinutes(dateObj.getMinutes() - 10);
if(dateObj > dtobj ){
if ( $('#hdn_sqllite').val() == "1")
{
notify(item['title'], (item['tasktype'] + " @ " + dateObj.getHours() + ":" + dateObj.getMinutes() ), item['deal_id'] );
}
}
updateRecord(1,item['id']);
k++;
}
}
if($('#hdn_sqllite').val() == "0" && (k>0))
{
notify( k + " overdue task(s) fo the day." , "www.wakeupsales.com" , "" );
$('#hdn_sqllite').val("1")
}
});
});
}
//chrome desktop notification function
function notify(title, desc, dealid) {
if( window.webkitNotifications) {
var havePermission = window.webkitNotifications.checkPermission();
if (havePermission == 0) {
// 0 is PERMISSION_ALLOWED
//var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var url = window.location.origin;
if( $('#hdn_sqllite').val() == 0)
{
linkurl = url +'/tasks?type=today'
}
else
{
linkurl = url +'/leads/'+dealid
}
var notification = window.webkitNotifications.createNotification(
url + '/assets/task-icon-larger.png',
title,
desc
);
notification.onclick = function () {
try{
window.focus();
window.location =linkurl;
notification.cancel();
} catch(e){}
};
//setTimeout(function(){
// try{
// notification.cancel();
// } catch(e){}
//}, 10000);
notification.show();
} else {
window.webkitNotifications.requestPermission();
}
}
}
function allowChromeDskNotify(){
if (window.webkitNotifications && window.webkitNotifications.checkPermission()!=0) {
window.webkitNotifications.requestPermission();
}
}
//end chrome desktop notification function
function check_notification()
{
showRecords();
}
$(document).ready(function () // Call function when page is ready for load..
{
$('body').click(function(){ allowChromeDskNotify()});
if($('#is_login').val() == 1)
{
get_login_info();
}
else
{
dropTable();
}
setInterval(function(){check_notification();}, 30000);
//$("body").fadeIn(2000); // Fede In Effect when Page Load..
//dropTable();
//initDatabase();
//insertRecord();
//check_notification();
//$("#submitButton").click(insertRecord); // Register Event Listener when button click.
//$("#btnUpdate").click(updateRecord);
//$("#btnReset").click(resetForm);
//$("#btnDrop").click(dropTable);
});
|
PHP
|
UTF-8
| 1,426
| 3.015625
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace ClassConfig;
use ClassConfig\Exceptions\MissingConfigException;
/**
* Class Config
* @package ClassConfig
*/
abstract class AbstractConfig
{
/**
* @var object
*/
protected $___owner;
/**
* @var null|AbstractConfig
*/
protected $___parent;
/**
* @var null|string
*/
protected $___key;
/**
* AbstractConfig constructor.
*
* @param object $owner
* @param AbstractConfig|null $parent
* @param string|null $key
*/
public function __construct($owner, AbstractConfig $parent = null, string $key = null)
{
$this->___owner = $owner;
$this->___parent = $parent;
$this->___key = $key;
}
/**
* @param string $key
* @return bool
*/
public function exists(string $key): bool
{
return property_exists($this, '__' . $key . '__');
}
/**
* @param string $key
* @return AbstractConfig
* @throws MissingConfigException
*/
public function depend(string $key): AbstractConfig
{
if (!isset($this->$key)) {
$trail = [$key];
$config = $this;
while ($config->___parent) {
$trail[] = $config->___key;
$config = $config->___parent;
}
throw new MissingConfigException(array_reverse($trail));
}
return $this;
}
}
|
Java
|
UTF-8
| 581
| 3.53125
| 4
|
[] |
no_license
|
package interviewPrograms;
public class ReverseOnlyAlphacharactersInString {
public static void main(String[] args) {
String str = "M@he,sh";
char [] values = str.toCharArray();
int l=0;
int r = str.length()-1;
while (l < r) {
if(!Character.isAlphabetic(values[l])) {
l++;
}else if(!Character.isAlphabetic(values[r])){
r--;
}else
{
char temp = values[l];
values[l] = values[r];
values[r] = temp;
l++;
r--;
}
}
String reverse = new String(values);
System.out.println(reverse);
}
}
|
Python
|
UTF-8
| 1,949
| 2.703125
| 3
|
[] |
no_license
|
import cv2
import sys
import os
import glob
class FaceCropper(object):
CASCADE_PATH = "./haarcascade_frontalface_default.xml"
def __init__(self):
self.face_cascade = cv2.CascadeClassifier(self.CASCADE_PATH)
def generate(self, image_path, show_result):
cap = cv2.VideoCapture(image_path)
pos_frame = cap.get(cv2.CAP_PROP_POS_FRAMES)
path = "./results/"+image_path.split('/')[-1].split('.')[0]
if not os.path.exists(path):
os.makedirs(path)
idx=0
seconds = 1
fps = cap.get(cv2.CAP_PROP_FPS)
multiplier = fps * seconds
print ("Processing ...")
while True:
frameId = int(round(cap.get(1)))
flag, img = cap.read()
idx+=1
if frameId % multiplier == 0:
faces = self.face_cascade.detectMultiScale(img, 1.3, 5, minSize=(100, 100))
if (faces is None):
print('Failed to detect face')
return 0
facecnt = len(faces)
i = 0
height, width = img.shape[:2]
for (x, y, w, h) in faces:
r = max(w, h) / 2
centerx = x + w / 2
centery = y + h / 2
nx = int(centerx - r)
ny = int(centery - r)
nr = int(r * 2)
faceimg = img[ny:ny+nr, nx:nx+nr]
i += 1
cv2.imwrite(path+"/"+image_path.split('/')[-1].split('.')[0]+"_original_%d_%d.jpg" % (idx/10,i), img)
cv2.imwrite(path+"/"+image_path.split('/')[-1].split('.')[0]+"_cropped_%d_%d.jpg" % (idx/10,i), faceimg)
if cap.get(cv2.CAP_PROP_POS_FRAMES) == cap.get(cv2.CAP_PROP_FRAME_COUNT):
break
if __name__ == '__main__':
detecter = FaceCropper()
imgList = glob.glob('./data/*')
for img in imgList:
print (img)
detecter.generate(img, True)
|
TypeScript
|
UTF-8
| 3,035
| 2.765625
| 3
|
[] |
no_license
|
import { FormValidationService } from './form-validation.service';
import { FormValidationRule } from './form-validation-rule';
describe('FormValidationService', () => {
let service: FormValidationService;
beforeEach(() => {
service = new FormValidationService();
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should call each validator', () => {
const passingValidatorA = jasmine.createSpy('validatorA').and.returnValue(true);
const passingValidatorB = jasmine.createSpy('validatorB').and.returnValue(true);
const rules: FormValidationRule[] = [{
prop: 'testA',
error: 'testA',
validator: passingValidatorA
}, {
prop: 'testB',
error: 'testB',
validator: passingValidatorB
}];
const values: any = {
testA: true,
testB: ''
};
const errors: any = {};
service.validator(rules, values, errors);
expect(passingValidatorA).toHaveBeenCalledWith(true);
expect(passingValidatorB).toHaveBeenCalledWith('');
});
it('should set an error message for each validator that fails', () => {
const failingValidatorA = jasmine.createSpy('validatorA').and.returnValue(false);
const failingValidatorB = jasmine.createSpy('validatorB').and.returnValue(false);
const rules: FormValidationRule[] = [{
prop: 'testA',
error: 'testA',
validator: failingValidatorA
}, {
prop: 'testB',
error: 'testB',
validator: failingValidatorB
}];
const values: any = {
testA: true,
testB: ''
};
const errors: any = {};
service.validator(rules, values, errors);
expect(errors.testA).toEqual('testA');
expect(errors.testB).toEqual('testB');
});
it('should return false if any validator fails', () => {
const failingValidator = jasmine.createSpy('validatorA').and.returnValue(false);
const passingValidator = jasmine.createSpy('validatorA').and.returnValue(true);
const rules: FormValidationRule[] = [{
prop: 'testA',
error: 'testA',
validator: failingValidator
}, {
prop: 'testB',
error: 'testB',
validator: passingValidator
}];
const values: any = {
testA: true,
testB: ''
};
const errors: any = {};
const pass = service.validator(rules, values, errors);
expect(pass).toBeFalsy();
});
it('should return true if all validators pass', () => {
const passingValidatorA = jasmine.createSpy('validatorA').and.returnValue(true);
const passingValidatorB = jasmine.createSpy('validatorB').and.returnValue(true);
const rules: FormValidationRule[] = [{
prop: 'testA',
error: 'testA',
validator: passingValidatorA
}, {
prop: 'testB',
error: 'testB',
validator: passingValidatorB
}];
const values: any = {
testA: true,
testB: ''
};
const errors: any = {};
const pass = service.validator(rules, values, errors);
expect(pass).toBeTruthy();
});
});
|
Python
|
UTF-8
| 452
| 3.359375
| 3
|
[] |
no_license
|
import math
def match(n):
s = str(n)
return s[0]=='1' and s[2]=='2' and s[4]=='3' and s[6]=='4' and s[8]=='5' and s[10]=='6' and s[12]=='7' and s[14]=='8' and s[16]=='9' and s[18]=='0'
#print(math.sqrt(1020304050607080900), match(1020304050607080900))
magic = 10203040506070809
# Add a zero on the end of the printed result
for n in range(int(math.sqrt(magic)), int(math.sqrt(magic)*2)):
if match(n**2*100):
print(n)
break
|
Python
|
UTF-8
| 250
| 3.984375
| 4
|
[] |
no_license
|
# Allison Gross
# factorial.py
# computes factorial
# 01-07-13
def main():
fact = 1
n = eval(input( "What number should we compute the factorial of? "))
for i in range(1, n+1):
fact = fact*i
print(n, "factorial is", fact)
main()
|
JavaScript
|
UTF-8
| 16,339
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
//取得当前选中的升或降一的音符
function getNewNote(note, flag) {
if (note == "") {
return note;
}
// 判断音符出现的次数,如果出现次数大于1,则于无做升降调
var count = 0;
for (var i = 1; i < note.length; i++) {
if (notestr.indexOf(note.substr(i - 1, i)) > -1) {
count++;
}
}
if (count > 1) {
return note;
}
var suffix = "";
var start = note.lastIndexOf(",");
if (start == -1) {
start = note.lastIndexOf("'");
}
if (start == -1) {
start = 0
}
var all = [];
for (var i = 0; i < sd.KeyBoardStand.length; i++) {
all = all.concat(sd.KeyBoardStand[i].val);
}
for (var i = 0; i < all.length; i++) {
if (all[i] == note.substr(0, start + 1)) {
if (flag == "UP") {
if (i + 1 < all.length) {
playNote(all[i + 1]);
return all[i + 1] + note.substr(start + 1, note.length);
}
}
if (flag == "DOWN") {
if (i - 1 > 0) {
playNote(all[i - 1]);
return all[i - 1] + note.substr(start + 1, note.length);
}
}
return all[i];
}
}
return note;
}
// 取键盘对应的音符
function getNoteByKey(group, index) {
// 所有键盘数据
var keys = sd.KeyBoard;
// 取键盘对应的音符
for (var i = 0; i < keys.length; i++) {
if (keys[i].group == group) {
return keys[i].val[index];
}
}
return "";
}
//取键盘对应的音符
function getNoteByKey2(group, index, riseOrDown, sourceid, lower,key) {
// 所有键盘数据
var keys;
if(riseOrDown == "undefined" || riseOrDown == undefined || riseOrDown == ""){
keys = sd.KeyBoardStand;
} else if (riseOrDown == "rise") {
keys = sd.KeyBoard;
} else if (riseOrDown == "down") {
keys = sd.KeyBoard_D;
}
// 取键盘对应的音符
for (var i = 0; i < keys.length; i++) {
if (keys[i].group == group) {
var note = keys[i].val[index];
// 上面返回的是C大调的对应的音符,要转成当前相对应的调子的音符
var val = getNoteByKeyWithC(sourceid, lower,key);
if (val == "") {
return keys[i].val[index];
} else {
return val;
}
}
}
return "";
}
function findCNote(jpVal) {
var arr = sd.Simple2Staff.SimpleValue;
var index = -1;
for (var i = 0; i < arr.length; i++) {
var n = arr[i];
if (jpVal.replaceAll("'", "").replaceAll(",", "").replaceAll("\\^", "#").replaceAll("\\_", "b") == n.replace(",", "")) {
index = i;
}
}
if (index != -1) {
var tmpNote = sd.Simple2Staff.StaffValue[0].STAFF[index];
var suffix = jpVal.substr(tmpNote.length);
return tmpNote + suffix;
}
return "";
}
// 根据C大调的音符值,取得其它大调的音符值
function getNoteByKeyWithC(sourceid, lower,K) {
var cNote = findCNote(currJpVal);
if (cNote == "") {
return "";
}
var content = $("#" + sourceid).val();
if (content == "undefined" || content == undefined) {
return;
}
//K的值改为传入
// var kPattern = /K:\s{0,}.[^\s]*/;
// var kResult = content.match(kPattern);
// var K = "";
// if (kResult != null) {
// K = kResult[0].replace("K:", "");
// K = $.trim(K);
// }
var carr = sd.Simple2Staff.StaffValue[0].STAFF;
var tmpNote = cNote.replaceAll(",", "").replaceAll("'", "");
var index = -1;
var note = "";
var resultNote = "";
// 1.先找到与C大调对应的
for (var i = 0; i < carr.length; i++) {
if (tmpNote.toLowerCase() == carr[i].replaceAll(",", "").replaceAll("'", "").toLowerCase()) {
index = i;
note = carr[i];
}
}
for (var i = 0; i < sd.Simple2Staff.StaffValue.length; i++) {
if (sd.Simple2Staff.StaffValue[i].K == K) {
if (lower == "lower") {
resultNote = sd.Simple2Staff.StaffValue[i].STAFF_LOWER[index];
} else if (lower == "higher") {
resultNote = sd.Simple2Staff.StaffValue[i].STAFF[index];
} else {
// 这里主要处理前期没有这个标识时,降b调使用的是小字组
if (K == "Bb") {
resultNote = sd.Simple2Staff.StaffValue[i].STAFF_LOWER[index];
} else {
resultNote = sd.Simple2Staff.StaffValue[i].STAFF[index];
}
}
}
}
var suffix = cNote.substr(note.length);
var result = resultNote + suffix;
if (result.indexOf(",'") > -1) {
result = result.replace(",'", "");
}
var pattern = /[A-G]'/g;
result = result.replace(pattern, function(m, p1, p2, p3) {
return m.replace("'", "").toLowerCase();
});
var pattern2 = /[a-g],/g;
result = result.replace(pattern2, function(m, p1, p2, p3) {
return m.replace(",", "").toUpperCase();
});
return result;
}
// 取键盘对应的音符
function getNoteNameByKey(group, index) {
// 所有键盘数据
var keys = sd.KeyBoard;
// 取键盘对应的音符
for (var i = 0; i < keys.length; i++) {
if (keys[i].group == group) {
return keys[i].name[index];
}
}
return "";
}
// 取键盘对应的简谱
function getNumStaffByKey(group, index) {
// 所有键盘数据
var keys = sd.KeyBoard;
// 取键盘对应的音符
for (var i = 0; i < keys.length; i++) {
if (keys[i].group == group) {
return keys[i].numstaff[index];
}
}
return "";
}
// 根据不同的声调取不同的音符,如G大调时,弹奏F,应该显示在谱子上为“=F”,如果弹奏"^F"显示F
function getNoteByKeySign(key, note) {
// 与当前音符在同一小节内的的有有升降符、还原符的音符
var barlineNotes = getNotesByBarLine();
// 本节内最后一个升降号,如果本节内最后一个升降号与当前的一至,则当前的就不需要加升降号和还原号
// var lastUpOrDown = getNodePreUpOrDownSymbol();
var lastUpOrDown = getLastFlag(barlineNotes, note);
// 所有声调数据
var sigs = sd.KeySignature;
if (sigs != null && currJpVal == "") {
for (var i = 0; i < sigs.length; i++) {
if (key == sigs[i].key) {
var val = sigs[i].val;
var type = sigs[i].type;
if (type == "down") {
// var noteIndex = findIndexByNote(note);
// note = findNoteByIndex_D(noteIndex);
// console.log("note:=================="+note)
}
if (val != "") {
var notes = val.split(",");
for (var j = 0; j < notes.length; j++) {
// 符号相应的调子的音符,则去掉前面的升降号,如^F->F
if (note.toUpperCase().indexOf(notes[j]) > -1) {
// 输入的音符是需要处理的音符
if (note.startWith("\\^\\^")) {
if (lastUpOrDown == "" || lastUpOrDown == "^^") {
return note.replace("^^", "");
} else {
return note;
}
} else if (note.startWith("\\^")) {
// 如果该音符前没有升降符号,或者该音符前已经有升号,则该音符不需要加升号
if (lastUpOrDown == "" || lastUpOrDown == "^") {
return note.replace("^", "");
} else {
return note;
}
} else if (note.startWith("\\_\\_")) {
if (lastUpOrDown == "" || lastUpOrDown == "__") {
return note.replace("__", "");
} else {
return note;
}
} else if (note.startWith("\\_")) {
// 如果该音符前没有升降符号,或者该音符前已经有升号,则该音符不需要加升号
if (lastUpOrDown == "" || lastUpOrDown == "_") {
return note.replace("_", "");
} else {
return note;
}
} else {
// 如果该音符前没有升降符号,或者该音符前已经有升号,则该音符不需要加升号
if (lastUpOrDown == "=") {
return note;
} else {
if (note.indexOf("=") > -1) {
return note;
}
// return "=" + note;
return restoreNote(key, note);
}
}
} else {
if (type == "down") {
var tmpnote = "_" + note;
if (tmpnote.toUpperCase().indexOf(notes[j]) > -1) {
if (note.indexOf("=") > -1) {
return note;
}
// return "=" + note;
return restoreNote(key, note);
}
} else if (type == "up") {
var tmpnote = "^" + note;
if (tmpnote.toUpperCase().indexOf(notes[j]) > -1) {
if (note.indexOf("=") > -1) {
return note;
}
// return "=" + note;
return restoreNote(key, note);
}
}
}
}
}
}
}
}
if (note.startWith("\\^\\^")) {
if (lastUpOrDown == "^^") {
return note.replace("^^", "");
} else {
return note;
}
} else if (note.startWith("\\^")) {
// 如果该音符前没有升降符号,或者该音符前已经有升号,则该音符不需要加升号
if (lastUpOrDown == "^") {
return note.replace("^", "");
} else {
return note;
}
} else if (note.startWith("\\_\\_")) {
if (lastUpOrDown == "__") {
return note.replace("__", "");
} else {
return note;
}
} else if (note.startWith("\\_")) {
// 如果该音符前没有升降符号,或者该音符前已经有升号,则该音符不需要加升号
if (lastUpOrDown == "_") {
return note.replace("_", "");
} else {
return note;
}
} else {
// 如果该音符前没有升降符号,或者该音符前已经有升号,则该音符不需要加升号
if (lastUpOrDown == "=") {
var rnote = restoreNote(key, note);
return rnote.replace("=", "");
} else {
if (lastUpOrDown != "") {
if (note.indexOf("=") > -1) {
return note;
}
// return "=" + note;
return restoreNote(key, note);
} else {
return note;
}
}
}
return note;
}
// 根据调式取得还原的音符,如bA调的A其还原音符为_A
function restoreNote(key, note) {
var sigs = sd.KeySignature;
var keynote = "";
for (var i = 0; i < sigs.length; i++) {
if (key == sigs[i].key) {
var val = sigs[i].val;
if (val != "") {
var notes = val.split(",");
for (var j = 0; j < notes.length; j++) {
// 符号相应的调子的音符,则去掉前面的升降号,如^F->F
var tmpnote = note.replace(",", "").replace("'", "").replaceAll("\\/", "").replace(/[0-9]{0,}/g, "").toUpperCase();
if (notes[j].toUpperCase().indexOf(tmpnote) > -1) {
keynote = notes[j].substr(0, 1) + note;
}
}
}
}
}
if (keynote == "") {
return "=" + note;
} else {
return keynote;
}
}
function playNote(note) {
var keyBoards = sd.KeyBoard;
var parentIndex = 0;
var index_all = 0;
for (var i = 0; i < keyBoards.length; i++) {
var group = keyBoards[i];
var notes = group.val;
for (var j = 0; j < notes.length; j++) {
if (notes[j] == note) {
/*
* if(i<8){ var c0 = sd.SoundIndex.C0; index_all = i * 12 +
* c0[j]; }else{ var b0 = sd.SoundIndex.B0; index_all = (i-8) *
* 12 + b0[j]; }
* play_one_note(index_all,$("#L").val(),$("#Q").val(),$("#Q_V").val())
*/
insert = false;
// $("#pianoKeysWhite div[group="+group.group
// +"]>div").eq(j).click();
clickPianoKey(group.group, j);
insert = true;
return;
}
}
}
}
// 从字符串中取出所有音符
function getNotes(str) {
//扩展音符
var extendNotes = "";
for(var i=0;i<extnotes.length;i++){
extendNotes += extnotes[i].char;
}
var reg = new RegExp("[cdefgabzCDEFGABZ"+extendNotes+"](\,*)(\'*)(\/*)([1-9]*)","g");
var result = str.match(reg);
return result;
}
// 增加或减少音符长度
function editNoteLen(selectText, editType) {
var lastchar = selectText.substr(selectText.length - 1, selectText.length);
var selectText2 = selectText.substr(0, selectText.length - 1);
var numstr = "0123456789";
var result = selectText;
if (numstr.indexOf(lastchar) > -1) {
// 如果结尾是数字
if (editType == "2") {
if (parseInt(lastchar) >= 8) {
// 这里最多只算到 * 8
$("#source").focus();
return result;
}
// 增加时长
editType = parseInt(lastchar) * 2;
} else if (editType == "/") {
// 减少时长
editType = parseInt(lastchar) / 2;
if (editType == "1") {
editType = "";
}
}
result = selectText2 + editType;
} else if (lastchar == "/") {
if (editType == "2") {
result = selectText.substr(0, selectText.length - 1);
} else {
result = selectText + editType;
}
} else {
result = selectText + editType;
}
return result;
}
// 取音符区域的内容,返回的是一个对象数组,包括属性v:表示是哪一个声部,str:表示对应声部的谱子(如果是多谱表,返回的是多个数组)
function getNoteContent() {
var content = $("#source").val();
content = content + "\n";
// 这里去掉歌词
content = content.replaceAll(/w:.[^\n]*\n/g, "");
var lines = content.split("\n");
var str = "";
var arr = new Array();
var vPattern = /V:[1-9]/;
if (lines != null) {
var lastV = "";
var newV = false;
for (var i = 0; i < lines.length; i++) {
var exist = false;
if (lines[i].indexOf("V:") > -1) {
var v = lines[i].match(vPattern);
if (v != null && v.length > 0) {
lastV = v[0];
}
}
var line_tmp = lines[i].replaceAll(/\".*\"/g, "");
if (line_tmp.replace(/\[.[^\]]*\]/, "").replace(/\{.[^\}]*\}/, "").indexOf("|") > -1) {
var obj = new Object();
for (var j = 0; j < arr.length; j++) {
if (arr[j].v == lastV) {
obj = arr[j];
obj.str = obj.str + lines[i];
exist = true;
break;
}
}
if (!exist) {
obj.str = lines[i];
obj.v = lastV;
arr.push(obj);
}
}
}
}
return arr;
}
// 取标题区域内容
function getTitleContent() {
var content = $("#source").val();
// 这里去掉歌词
content = content.replaceAll(/w:.[^\n]*\n/g, "");
var lines = content.split("\n");
var str = "";
if (lines != null) {
for (var i = 0; i < lines.length; i++) {
var line_tmp = lines[i].replaceAll(/\".*\"/g, "");
if (line_tmp.replace(/\[.[^\]]*\]/, "").replace(/\{.[^\}]*\}/, "").indexOf("|") < 0) {
str = str + lines[i] + "\n";
} else {
break;
}
}
}
return str;
}
// 取
function getNoteAndLyricContent() {
var content = $("#source").val();
// 这里去掉歌词
var lines = content.split("\n");
var str = "";
if (lines != null) {
for (var i = 0; i < lines.length; i++) {
var line_tmp = lines[i].replaceAll(/\".*\"/g, "");
if (line_tmp.replace(/\[.[^\]]*\]/, "").replace(/\{.[^\}]*\}/, "").indexOf("|") > -1 || line_tmp.replace(/\[.[^\]]*\]/, "").replace(/\{.[^\}]*\}/, "").indexOf("w:") > -1) {
str = str + lines[i] + "\n";
}
}
}
return str;
}
// 取小节内前一个升降符号
function getNodePreUpOrDownSymbol() {
try {
var startPos = getStartPos(document.getElementById("source"));
var content = $("#source").val();
var idx = content.lastIndexOf("|")
if (idx == -1) {
idx = content.lastIndexOf("\n");
}
var nodeStr = content.substring(idx + 1, startPos);
var max = -1;
var s = "";
// 最后一个升符的位置
var u = nodeStr.lastIndexOf("^");
if (u > max) {
max = u;
s = "^";
}
// 最后一个还原符的位置
var e = nodeStr.lastIndexOf("=");
if (e > max) {
max = e;
s = "=";
}
// 最后一个降符的位置
var d = nodeStr.lastIndexOf("_");
if (d > max) {
max = d;
s = "_";
}
console.log(nodeStr.substr(max, 2))
// return nodeStr.substr(max,2);
return s;
} catch (e) {
return "";
}
}
// 取小节内所有带升降号、还原号的音符
function getNotesByBarLine() {
var pattern = /(\^{1,2}[a-zA-Z],*)|(\=[a-zA-Z],*)|(\_{1,2}[a-zA-Z],*)/g;
var startPos = getStartPos(document.getElementById("source"));
if(document.getElementById("source").value.length==startPos){
startPos = $("svg rect[style='fill-opacity: 0.4']").attr("istart");
}
var content = $("#source").val();
content = replaceBlankLine(content).substr(0, startPos);
var idx = content.lastIndexOf("|");
if (idx == -1) {
idx = content.lastIndexOf("\n");
}
var nodeStr = content.substring(idx + 1, startPos);
var result = nodeStr.match(pattern);
console.log(result);
return result;
}
// 判断当前输入的音符是否需要加升降号
function getLastFlag(notes, currentNote) {
console.log("currentNote:" + currentNote)
var flag = "";
if (notes != null) {
for (var i = 0; i < notes.length; i++) {
if (notes[i].toLowerCase().indexOf(currentNote.replaceAll("\\^", "").replaceAll("\\_", "").replace("=", "").toLowerCase()) > -1) {
if (notes[i].indexOf("^^") > -1) {
flag = "^^";
} else if (notes[i].indexOf("__") > -1) {
flag = "__";
} else {
flag = notes[i].substring(0, 1);
}
}
}
}
console.log("flag:" + flag)
return flag;
}
|
PHP
|
UTF-8
| 2,167
| 2.9375
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
<?php
/**
* Reshi libray - an assertion library.
*
* @author Armando Sudi <armando.sudi@mixteer.com>
* @copyright 2015 Mixteer
* @link http://os.mixteer.com/baseutils/reshi
* @license http://os.mixteer.com/baseutils/reshi/license
* @version 0.1.0
*
* MIT LICENSE
*/
use \Reshi\Constraints\HasSameContentAs;
class HasSameContentAsTest extends PHPUnit_Framework_TestCase
{
protected $hasSameContentAs;
protected $fileOneHandle = null;
protected $fileTwoHandle = null;
protected function setUp()
{
// Create the files
$this->fileOneHandle = fopen(__DIR__.'/../../assets/file_one.txt', 'w') or die('Could not create the first file while setting up tests for HasSameContentTest.');
$this->fileTwoHandle = fopen(__DIR__.'/../../assets/file_two.txt', 'w') or die('Could not create the second file while setting up tests for HasSameContentTest.');
$this->hasSameContentAs = new HasSameContentAs(__DIR__.'/../../assets/file_one.txt');
}
public function testEvaluateWithCorrectData()
{
fwrite($this->fileOneHandle, "a");
fwrite($this->fileTwoHandle, "a");
$this->assertTrue($this->hasSameContentAs->evaluate(__DIR__.'/../../assets/file_two.txt'), "Failed to assert that the two file have the same content");
}
public function testEvaluateWithIncorrectData()
{
fwrite($this->fileOneHandle, "a");
fwrite($this->fileTwoHandle, "b");
$this->assertFalse($this->hasSameContentAs->evaluate(__DIR__.'/../../assets/file_two.txt'), "Failed to assert that the two file do not have the same content");
}
public function testGetName()
{
$this->assertEquals($this->hasSameContentAs->getName(), "HAS_SAME_CONTENT_AS", "Failed to assert COUNT is the constraint name.");
}
public function tearDown()
{
if ($this->fileOneHandle != null) {
fclose($this->fileOneHandle);
unlink(__DIR__.'/../../assets/file_one.txt');
}
if ($this->fileTwoHandle != null) {
fclose($this->fileTwoHandle);
unlink(__DIR__.'/../../assets/file_two.txt');
}
}
}
|
Python
|
UTF-8
| 3,295
| 3.234375
| 3
|
[] |
no_license
|
#Sentiment Analysis usng Twitter API and TextBlob for sentiment Analysis
#
#https://apps.twitter.com
#Owner ybouakkaz
import csv
import os
import re
import tweepy
from textblob import TextBlob
import numpy as np
import matplotlib.pyplot as plt
class SearchPolarities:
positive = 0.0
neutral = 0.0
negative = 0.0
consumer_key = os.environ['CONSUMER_KEY']
consumer_secret = os.environ['CONSUMER_SECRET']
access_token = os.environ['ACCESS_TOKEN']
access_token_secret = os.environ['ACCESS_TOKEN_SECRET']
try:
auth = tweepy.OAuthHandler(consumer_key,consumer_secret)
auth.set_access_token(access_token,access_token_secret)
api = tweepy.API(auth)
except:
print("Error: Authentication Failed")
#Set Application parameters
analysisQuery = input("Enter keyword you want to apply the sentiment analysis: ")
print('Term to analyze is: ' + analysisQuery )
tweetLang = 'English'
#Search the tweet to analyze based on input
#http://docs.tweepy.org/en/v3.6.0/api.html#API.search
tweets = api.search(analysisQuery)
#tweets = api.search(analysisQuery,lang=tweetLang)
if not tweets:
exit()
search_polarities = SearchPolarities()
#Function of labelisation of analysis
def get_tweet_label(analysis):
if analysis.sentiment.polarity > 0:
return 'positive'
elif analysis.sentiment.polarity == 0:
return 'neutral'
else:
return 'negative'
#Function to clean tweet
def clean_tweet(tweet):
return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweet).split())
#create csv file to store tweets
with open('csv/%s_tweets.csv' % analysisQuery, 'w') as csvFile:
csvWriter = csv.writer(csvFile, delimiter='\t', lineterminator='\n')
csvWriter.writerow(['tweet,tweet cleaned,sentiment_label'])
#Perform Sentiment Analysis on Tweets
for tweet in tweets:
print(tweet.text)
analysis = TextBlob(tweet.text)
#search_polarities.append(analysis.sentiment.polarity)
print(analysis.sentiment.polarity)
if (analysis.sentiment.polarity > 0.00):
search_polarities.positive +=1
elif (analysis.sentiment.polarity < 0.00):
search_polarities.negative +=1
else:
search_polarities.neutral +=1
tweet_cleaned = clean_tweet(tweet.text)
csvWriter.writerow([tweet.text,',',tweet_cleaned ,',', get_tweet_label(analysis)])
search_polarities.positive = search_polarities.positive/len(tweets)*100
search_polarities.negative = search_polarities.negative/len(tweets)*100
search_polarities.neutral = search_polarities.neutral/len(tweets)*100
print('\n Result of sentiment analysis for term ' + analysisQuery + ':\n')
print('%s : %0.3f' % ('Positive', search_polarities.positive))
#use matplotlib to display values on graph
labels = ['Positive ['+ str(search_polarities.positive)+'%]','Negative ['+ str(search_polarities.negative)+'%]','Neutral ['+ str(search_polarities.neutral)+'%]']
sizes = [search_polarities.positive,search_polarities.negative,search_polarities.neutral]
colors = ['green','red','gray']
patches = plt.pie(sizes, colors=colors)
plt.legend(patches[0], labels,loc="best")
plt.title('Twitter sentiment analysis of term ' + analysisQuery)
plt.tight_layout()
plt.show()
|
Markdown
|
UTF-8
| 697
| 2.625
| 3
|
[] |
no_license
|
### Date created
11/25/2018
### Project Title
Explore US Bikeshare Data
### Description
This project uses python code to analyze data related to bike share systems for three cities: Chicago, New York City and Washington.
This project will
1) import data based on user inputs
2) compute descriptive statistics regarding time, stations, trips and users
3) create an interactive experience in the terminal to present these statistics
### Files used
chicago.csv
new_york_city.csv
washington.csv
bikeshare_jn-3.py
### Credits
I referred to this thread on stackoverflow for taking user inputs
https://stackoverflow.com/questions/14907067/how-do-i-restart-a-program-based-on-user-input#
|
Java
|
UTF-8
| 557
| 3.328125
| 3
|
[] |
no_license
|
package KTU;
import java.util.Scanner;
public class Uzd_0_03 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Kiek yra monetu po 5 ct? ");
double a = reader.nextInt();
System.out.println("Kiek yra monetu po 20 ct? ");
double b = reader.nextInt();
System.out.println("Kiek yra monetu po 2 Lt? ");
double c = reader.nextInt();
double sum = a / 20 + b / 5 + c * 2;
System.out.println("Taupykleje yra " + sum + " Lt.");
reader.close();
}
}
|
Markdown
|
UTF-8
| 713
| 2.703125
| 3
|
[
"Apache-2.0"
] |
permissive
|
```
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, preorder, inorder): # 返回以preorder[0]为root的 树节点
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
if len(preorder) == 0 and len(inorder) == 0:
return
root = TreeNode(preorder[0])
index = inorder.index(preorder[0])
root.left = self.buildTree(preorder[1:index+1],inorder[0:index])
root.right = self.buildTree(preorder[index+1:],inorder[index+1:])
return root
```
|
Java
|
UTF-8
| 869
| 3.375
| 3
|
[] |
no_license
|
package Ex46;
/*
* UCF COP3330 Summer 2021 Assignment 3 Solution
* Copyright 2021 Richard Pekarski
*/
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class fileReader {
public List<String> readFile() {
// scans file and add it to List
String text;
List<String> Filelist = new ArrayList<String>();
try {
File read_file = new File("FileInput/Ex46/exercise46_input.txt");
Scanner file_scan = new Scanner(read_file);
while(file_scan.hasNextLine()){
text = file_scan.nextLine();
Filelist.add(text);
}
file_scan.close();
}
catch(IOException e){
System.out.println("File could not be read. ");
}
return Filelist;
}
}
|
Java
|
GB18030
| 6,211
| 2.46875
| 2
|
[] |
no_license
|
package com.lantu.comhelper.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.content.Context;
import android.os.Environment;
/**
* log־ͳƱ
*/
public class LogHelper {
private static LogHelper INSTANCE = null;
private static String LOGCAT_DIR = null;
public static String LOGCAT_DIR_SAVE = null;
public static String DIR = "ComHelperLog";
public static String DIRSECOND = DIR + File.separator + "Save";
public static String TAG = "ComHelperLog";
private int appPid;
private LogThread logThread = null;
/**
* 캯
* @param context
*/
private LogHelper(Context context) {
this.init(context);
appPid = android.os.Process.myPid();
}
/**
* ӿں־
*/
public void start() {
if (logThread == null) {
logThread = new LogThread(String.valueOf(appPid), LOGCAT_DIR);
}
logThread.start();
}
/**
* ־ļ
*/
public void init(Context context) {
// ļ + ݵļ
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // ȱSD
LOGCAT_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + DIR;
LOGCAT_DIR_SAVE = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + DIRSECOND;
} else { // ӦõĿ¼
LOGCAT_DIR = context.getFilesDir().getAbsolutePath() + File.separator + DIR;
LOGCAT_DIR_SAVE = context.getFilesDir().getAbsolutePath() + File.separator + DIRSECOND;
}
File file = new File(LOGCAT_DIR);
if (!file.exists()) {
file.mkdirs();
}
File fileSave = new File(LOGCAT_DIR_SAVE);
if (!fileSave.exists()) {
fileSave.mkdirs();
}
}
/**
* õ־
* @param context
* @return
*/
public static LogHelper getInstance(Context context) {
if (INSTANCE == null) {
INSTANCE = new LogHelper(context);
}
return INSTANCE;
}
/**
* ־洢߳
*/
private class LogThread extends Thread {
private Process logcatProc;
private BufferedReader bufferedReader = null;
private boolean runningFlag = true;
String cmds = null;
private String myPID;
private FileOutputStream out = null;
public LogThread(String pid, String dir) {
myPID = pid;
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
String curDate = format.format(new Date(System.currentTimeMillis()));
out = new FileOutputStream(new File(dir, curDate + ".log"), true);
} catch (Exception e) {
e.printStackTrace();
}
/**
* ־ȼ*:v , *:d , *:w , *:e , *:f , *:s
* ʾǰmPID EWȼ־.
* */
//cmds = "logcat *:e *:w | grep \"(" + myPID + ")\"";
//cmds = "logcat | grep \"(" + myPID + ")\"";//ӡ־Ϣ
//cmds = "logcat -s way";//ӡǩϢ
//cmds = "logcat *:e *:i | grep \"(" + myPID + ")\"";
cmds = "logcat *:e *:w | -s " + TAG + " & grep \"(" + myPID + ")\"";
}
public void stopLogs() {
runningFlag = false;
}
@Override
public void run() {
try {
logcatProc = Runtime.getRuntime().exec(cmds);
bufferedReader = new BufferedReader(new InputStreamReader(logcatProc.getInputStream()), 1024);
String line = null;
while (runningFlag && (line = bufferedReader.readLine()) != null) {
if (!runningFlag) {
break;
}
if (line.length() == 0) {
continue;
}
if (out != null && line.contains(myPID)) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
String curDate = format.format(new Date(System.currentTimeMillis()));
out.write((curDate + " " + line + "\n").getBytes());
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (logcatProc != null) {
logcatProc.destroy();
logcatProc = null;
}
if (bufferedReader != null) {
try {
bufferedReader.close();
bufferedReader = null;
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
out = null;
}
}
}
}
/**
* ֹͣ־¼
*/
public void stop() {
if (logThread != null) {
logThread.stopLogs();
logThread = null;
}
}
}
|
Java
|
UTF-8
| 353
| 2.625
| 3
|
[] |
no_license
|
package utilities;
import javafx.scene.image.Image;
public class Utilities {
public static Image image(String url){
try {
return new Image(Utilities.class.getClassLoader().getResourceAsStream(url));
}catch (Exception e){
System.out.println("image não existe");
return null;
}
}
}
|
C
|
UTF-8
| 4,630
| 3
| 3
|
[
"MIT"
] |
permissive
|
//
// main.c
// Fizteh2
//
// Created by Александр Ноянов on 27/02/2019.
// Copyright © 2019 MPEI. All rights reserved.
//
//#include <stdio.h>
//
//int main(int argc, const char * argv[]) {
// // insert code here...
// printf("Hello, World!\n");
// return 0;
//}
#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* readline();
char** split_string(char*);
/*
* Complete the realEstateBroker function below.
*/
int realEstateBroker(int clients_rows, int clients_columns, int** clients, int houses_rows, int houses_columns, int** houses) {
int numOfHouses = 0;
int i = 0;
int j = 0;
for(i = 0; i < houses_rows; i++ )
{
for(j = 0; j<clients_rows; j++) {
if( (houses[i][0] > clients[j][0]) && ( houses[i][1] <= clients[j][1]) )
{
numOfHouses++;
break;
}
}
}
return numOfHouses;
//return numOf;
}
int main()
{
//FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");
char** nm = split_string(readline());
char* n_endptr;
char* n_str = nm[0];
int n = strtol(n_str, &n_endptr, 10);
int client_row,client_column, house_row,house_column;
if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); }
char* m_endptr;
char* m_str = nm[1];
int m = strtol(m_str, &m_endptr, 10);
if (m_endptr == m_str || *m_endptr != '\0') { exit(EXIT_FAILURE); }
int** clients = malloc(n * sizeof(int*));
for (int clients_row_itr = 0; clients_row_itr < n; clients_row_itr++) {
clients[clients_row_itr] = malloc(2 * (sizeof(int)));
char** clients_item_temp = split_string(readline());
for (int clients_column_itr = 0; clients_column_itr < 2; clients_column_itr++) {
char* clients_item_endptr;
char* clients_item_str = clients_item_temp[clients_column_itr];
int clients_item = strtol(clients_item_str, &clients_item_endptr, 10);
if (clients_item_endptr == clients_item_str || *clients_item_endptr != '\0') { exit(EXIT_FAILURE); }
client_row = clients_row_itr;
client_column = clients_column_itr;
clients[clients_row_itr][clients_column_itr] = clients_item;
}
}
int** houses = malloc(m * sizeof(int*));
for (int houses_row_itr = 0; houses_row_itr < m; houses_row_itr++) {
houses[houses_row_itr] = malloc(2 * (sizeof(int)));
char** houses_item_temp = split_string(readline());
for (int houses_column_itr = 0; houses_column_itr < 2; houses_column_itr++) {
char* houses_item_endptr;
char* houses_item_str = houses_item_temp[houses_column_itr];
int houses_item = strtol(houses_item_str, &houses_item_endptr, 10);
if (houses_item_endptr == houses_item_str || *houses_item_endptr != '\0') { exit(EXIT_FAILURE); }
house_row = houses_row_itr;
house_column = houses_column_itr;
houses[houses_row_itr][houses_column_itr] = houses_item;
}
}
int result = realEstateBroker(n,2,clients, m, 2, houses);
printf("%d\n", result);
//fprintf(fptr, "%d\n", result);
//fclose(fptr);
return 0;
}
char* readline() {
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);
while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);
if (!line) { break; }
data_length += strlen(cursor);
if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; }
size_t new_length = alloc_length << 1;
data = realloc(data, new_length);
if (!data) { break; }
alloc_length = new_length;
}
if (data[data_length - 1] == '\n') {
data[data_length - 1] = '\0';
}
data = realloc(data, data_length);
return data;
}
char** split_string(char* str) {
char** splits = NULL;
char* token = strtok(str, " ");
int spaces = 0;
while (token) {
splits = realloc(splits, sizeof(char*) * ++spaces);
if (!splits) {
return splits;
}
splits[spaces - 1] = token;
token = strtok(NULL, " ");
}
return splits;
}
|
SQL
|
UTF-8
| 125
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
select e1.name as Employee
from
Employee e1
join
Employee e2
on
e1.ManagerId = e2.id
where e1.Salary > e2.Salary
|
JavaScript
|
UTF-8
| 5,775
| 2.640625
| 3
|
[] |
no_license
|
const request = require('supertest');
if (!process.env.USER_STORE_API_SECURED_TEST_URL) {
require('./helper/services');
} else {
jest.setTimeout(10000);
}
const requestUserApi = () => request(process.env.USER_STORE_API_SECURED_TEST_URL);
describe('User API', () => {
it('should return 404 when getting a non-existant user', async() => {
try {
requestUserApi().get(`/user/1`) || fail("Should have been 404");
} catch (err) {
expect(err.statusCode).toEqual(404);
}
});
it('should store information against a user', async() => {
const userInfo = JSON.stringify({ name: "test" });
await requestUserApi().put(`/user/2`).send(userInfo).expect(200);
const response = await requestUserApi().get(`/user/2`);
expect(response.text).toEqual(userInfo);
});
it('should update existing information stored against a user', async() => {
const userInfo1 = JSON.stringify({ name: "test1" });
const userInfo2 = JSON.stringify({ name: "test2" });
await requestUserApi().put(`/user/3`).send(userInfo1).expect(200);
await requestUserApi().put(`/user/3`).send(userInfo2).expect(200);
const response = await requestUserApi().get(`/user/3`);
expect(response.text).toEqual(userInfo2);
});
it('should store relationships between users', async() => {
const userInfo1 = JSON.stringify({ name: "test1" });
const userInfo2 = JSON.stringify({ name: "test2" });
const relationshipInfo = JSON.stringify({ type: "user", id: "5" });
await requestUserApi().put(`/user/4`).send(userInfo1).expect(200);
await requestUserApi().put(`/user/5`).send(userInfo2).expect(200);
await requestUserApi().put(`/user/4/friend`).send(relationshipInfo).expect(200);
const response = await requestUserApi().get(`/user/4/friend/user/5`);
expect(response.text).toEqual("{}");
});
it('should store relationships between users with properties', async() => {
const userInfo1 = JSON.stringify({ name: "test1" });
const userInfo2 = JSON.stringify({ name: "test2" });
const relationshipInfo = JSON.stringify({ type: "user", id: "7", strength: "best" });
await requestUserApi().put(`/user/6`).send(userInfo1).expect(200);
await requestUserApi().put(`/user/7`).send(userInfo2).expect(200);
await requestUserApi().put(`/user/6/friend`).send(relationshipInfo).expect(200);
const response = await requestUserApi().get(`/user/6/friend/user/7`);
expect(response.text).toEqual(JSON.stringify({ strength: "best" }));
});
it('should store relationships between users with properties and be able to update those properties', async() => {
const userInfo1 = JSON.stringify({ name: "test1" });
const userInfo2 = JSON.stringify({ name: "test2" });
const relationshipInfo1 = JSON.stringify({ type: "user", id: "7", strength: "best" });
const relationshipInfo2 = JSON.stringify({ type: "user", id: "7", strength: "acquaintance" });
await requestUserApi().put(`/user/6`).send(userInfo1).expect(200);
await requestUserApi().put(`/user/7`).send(userInfo2).expect(200);
await requestUserApi().put(`/user/6/friend`).send(relationshipInfo1).expect(200);
await requestUserApi().put(`/user/6/friend`).send(relationshipInfo2).expect(200);
const response = await requestUserApi().get(`/user/6/friend/user/7`);
expect(response.text).toEqual(JSON.stringify({ strength: "acquaintance" }));
});
it('should store relationships between users with properties and be able to update those properties', async() => {
const userInfo1 = JSON.stringify({ name: "test1" });
const userInfo2 = JSON.stringify({ name: "test2" });
const relationshipInfo1 = JSON.stringify({ type: "user", id: "7", strength: "best" });
const relationshipInfo2 = JSON.stringify({ type: "user", id: "7", strength: "acquaintance" });
await requestUserApi().put(`/user/6`).send(userInfo1).expect(200);
await requestUserApi().put(`/user/7`).send(userInfo2).expect(200);
await requestUserApi().put(`/user/6/friend`).send(relationshipInfo1).expect(200);
await requestUserApi().put(`/user/6/friend`).send(relationshipInfo2).expect(200);
const response = await requestUserApi().get(`/user/6/friend/user/7`);
expect(response.text).toEqual(JSON.stringify({ strength: "acquaintance" }));
});
it('should store relationships between users with properties and be able to get those relationships', async() => {
const userInfo1 = JSON.stringify({ name: "test1" });
const userInfo2 = JSON.stringify({ name: "test2" });
const userInfo3 = JSON.stringify({ name: "test3" });
const relationshipInfo1 = JSON.stringify({ type: "user", id: "9", strength: "best" });
const relationshipInfo2 = JSON.stringify({ type: "user", id: "10", strength: "acquaintance" });
await requestUserApi().put(`/user/8`).send(userInfo1).expect(200);
await requestUserApi().put(`/user/9`).send(userInfo2).expect(200);
await requestUserApi().put(`/user/10`).send(userInfo3).expect(200);
await requestUserApi().put(`/user/8/friend`).send(relationshipInfo1).expect(200);
await requestUserApi().put(`/user/8/friend`).send(relationshipInfo2).expect(200);
const expected = [{ id: "9", name: "test2" }, { id: "10", name: "test3" }]
const response = JSON.parse((await requestUserApi().get(`/user/8/friend`)).text);
expected.forEach(friend => expect(response).toContainEqual(friend))
expect(expected.length).toBe(response.length)
});
});
|
Swift
|
UTF-8
| 1,728
| 2.578125
| 3
|
[] |
no_license
|
//
// Conversation+CollectionView.swift
// UpFit Coaching
//
// Created by Jason Pierna on 10/05/2018.
// Copyright © 2018 Jason Pierna. All rights reserved.
// Version 1.0
import UIKit
extension ConversationController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return messages.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MessageCell", for: indexPath) as? MessageCell else {
return UICollectionViewCell()
}
guard let currentUser = currentUser else { return cell }
let message = messages[indexPath.item]
cell.messageLabel.text = message.content
if message.sender != currentUser {
cell.contentView.backgroundColor = UIColor(red: 12.0/255.0, green: 200.0/255.0, blue: 165.0/255.0, alpha: 1.0)
} else {
cell.contentView.backgroundColor = UIColor(red: 200.0/255.0, green: 200.0/255.0, blue: 200.0/255.0, alpha: 1.0)
}
return cell
}
}
extension ConversationController: ConversationLayoutDelegate {
func collectionView(_ collectionView: UICollectionView, isMessageFromUserFor indexPath: IndexPath) -> Bool {
guard let currentUser = currentUser else { return false }
let message = messages[indexPath.item]
return message.sender == currentUser
}
func collectionView(_ collectionView: UICollectionView, textAt indexPath: IndexPath) -> String {
return messages[indexPath.item].content
}
func collectionView(_ collectionView: UICollectionView, fontAt indexPath: IndexPath) -> UIFont {
return UIFont.systemFont(ofSize: 17)
}
}
|
PHP
|
UTF-8
| 1,081
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
<?php
session_start();
if(!isset($_SESSION['name'])) {
header('Location: index.php?auth=0');
}
?>
<!DOCTYPE html>
<html lang="en">
<?php include('head.php'); ?>
<body>
<?php include('menu.php'); ?>
<section class="main container pt-5 w-50">
<?php
//When the client places the order
//Empty the cart and show success message
if(isset($_GET['command']) && $_GET['command']==1 && $_SESSION['cart']!=[]){
$_SESSION['cart']=[];
echo '<p class="alert alert-success">Your order has been placed! Thank you for shopping with us.</p>';
}
?>
<h1 class="my-5">Your Cart</h1>
<!-- show the cart -->
<ul class="list-group list-group-flush border rounded">
<li class="list-group-item list-group-item-info fw-bold">List of Products</li>
<?php foreach($_SESSION['cart'] as $key => $cart_item) { ?>
<li class="list-group-item list-group-item-light transp-white"><?= $cart_item['name'] ?></li>
<?php } ?>
</ul>
<a href="cart.php?current=Cart&command=1" class="btn btn-info text-light fs-3 w-100">Place Order</a>
</section>
<?php include('foot.php'); ?>
</body>
</html>
|
Python
|
UTF-8
| 5,281
| 3.5
| 4
|
[] |
no_license
|
# This code demonstrates various tree and tree algorithm implementations.
# Credit to Miller and Ranum, Problem Solving with Algorithms and Data Structures Using Python
from pythonds.basic.stack import Stack
from pythonds.trees.binaryTree import BinaryTree
import operator
# Binary Tree
""" class BinaryTree:
def __init__(self,rootObj):
self.key = rootObj
self.leftChild = None
self.rightChild = None
def insertLeft(self,newNode):
if self.leftChild == None:
self.leftChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.leftChild = self.leftChild
self.leftChild = t
def insertRight(self,newNode):
if self.rightChild == None:
self.rightChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.rightChild = self.rightChild
self.rightChild = t
def getRightChild(self):
return self.rightChild
def getLeftChild(self):
return self.leftChild
def setRootVal(self,obj):
self.key = obj
def getRootVal(self):
return self.key
"""
# Parse Tree
def buildParseTree(fpexp):
fplist = fpexp.split()
pStack = Stack()
eTree = BinaryTree('')
pStack.push(eTree)
currentTree = eTree
for i in fplist:
if i == '(':
currentTree.insertLeft('')
pStack.push(currentTree)
currentTree = currentTree.getLeftChild()
elif i in ['+', '-', '*', '/']:
currentTree.setRootVal(i)
currentTree.insertRight('')
pStack.push(currentTree)
currentTree = currentTree.getRightChild()
elif i == ')':
currentTree = pStack.pop()
elif i not in ['+', '-', '*', '/', ')']:
try:
currentTree.setRootVal(int(i))
parent = pStack.pop()
currentTree = parent
except ValueError:
raise ValueError('token {} is not a valid integer'.format(i))
return eTree
def evaluate(parseTree):
opers = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv}
leftC = parseTree.getLeftChild()
rightC = parseTree.getRightChild()
if leftC and rightC:
fn = opers[parseTree.getRootVal()]
return fn(evaluate(leftC), evaluate(rightC))
else:
return parseTree.getRootVal()
def preorder(tree): #tree traversal method that prioritizes looking for left children
if tree:
print(tree.getRootVal())
preorder(tree.getLeftChild())
preorder(tree.getRightChild())
def postorder(tree):
if tree != None:
postorder(tree.getLeftChild())
postorder(tree.getRightChild())
print(tree.getRootVal())
def postordereval(tree):
opers = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv}
res1 = None
res2 = None
if tree:
res1 = postordereval(tree.getLeftChild())
res2 = postordereval(tree.getRightChild())
if res1 and res2:
return opers[tree.getRootVal()](res1,res2)
else:
return tree.getRootVal()
def inorder(tree): #visits left subtree followed by root followed by right subtree
if tree != None:
inorder(tree.getLeftChild())
print(tree.getRootVal())
inorder(tree.getRightChild())
def printexp(tree):
sVal = ""
if tree:
sVal = '(' + printexp(tree.getLeftChild())
sVal += str(tree.getRootVal())
sVal += printexp(tree.getRightChild()) + ')'
return sVal
# Binary Heap
class BinHeap:
def __init__(self):
self.heapList = [0]
self.currentSize = 0
def percUp(self, i):
while i//2 > 0:
if self.heapList[i] < self.heapList[i//2]:
tmp = self.heapList[i//2]
self.heapList[i//2] = self.heapList[i]
self.heapList[i] = tmp
i = i//2
def insert(self, k):
self.heapList.append(k)
self.currentSize += 1
self.percUp(self.currentSize)
def percDown(self, i):
while (i * 2) <= self.currentSize:
mc = self.minChild(i)
if self.heapList[i] > self.heapList[mc]:
tmp = self.heapList[i]
self.heapList[i] = self.heapList[mc]
self.heapList[mc] = tmp
i = mc
def minChild(self, i):
if i * 2 + 1 > self.currentSize:
return i * 2
else:
if self.heapList[i*2] < self.heapList[i * 2 + 1]:
return i * 2
else: return i * 2 + 1
def delMin(self):
retval = self.heapList[1]
self.heapList[1] = self.heapList[self.currentSize]
self.currentSize = self.currentSize - 1
self.heapList.pop()
self.percDown(1)
return retval
def buildHeap(self,alist):
i = len(alist) // 2
self.currentSize = len(alist)
self.heapList = [0] + alist[:]
while (i > 0):
self.percDown(i)
i = i - 1
bh = BinHeap()
bh.buildHeap([9,5,6,2,3])
print(bh.delMin())
print(bh.delMin())
print(bh.delMin())
print(bh.delMin())
print(bh.delMin())
|
Python
|
UTF-8
| 2,288
| 2.828125
| 3
|
[] |
no_license
|
# These are the dependecies. The bot depends on these to function, hence the name. Please do not change these unless your adding to them, because they can break the bot.
import discord
import asyncio
from discord.ext.commands import Bot
from discord.ext import commands
import platform
import spotipy
import spotipy.util as util
import pandas as pd
from spotipy.oauth2 import SpotifyClientCredentials
client_credentials_manager = SpotifyClientCredentials(client_id="INSERTCLIENTID", client_secret="INSERTCLIENTSECRET")
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
sp.trace=False
client = Bot(description="Spotify to discord bot.", command_prefix="?", pm_help = False)
def getTracks(playlistName, username):
df = pd.DataFrame.from_dict(sp.user_playlists(username)["items"])
filtered = df.loc[df['name'] == playlistName]
filtered_row = filtered.iloc[0]
results = sp.user_playlist(username, filtered_row["id"], fields="tracks,next")
tracks = results['tracks']
tracklist = []
for track in tracks["items"]:
tracklist.append(str(track["track"]["name"]+" - "+track["track"]['artists'][0]['name']))
return tracklist
@client.event
async def on_ready():
print('Logged in as '+client.user.name+' (ID:'+client.user.id+') | Connected to '+str(len(client.servers))+' servers | Connected to '+str(len(set(client.get_all_members())))+' users')
return await client.change_presence(game=discord.Game(name='PLAYING STATUS HERE')) #This is buggy, let us know if it doesn't work.
# This is a basic example of a call and response command. You tell it do "this" and it does it.
@client.command(pass_context=True)
async def playlist(ctx, playlistname, username):
await client.say("Oído. Voy a cargar esa playlist en el Rythm bot.")
await client.join_voice_channel(ctx.message.author.voice.voice_channel)
await client.say("Por favor, espera, "+str(ctx.message.author))
for track in getTracks(playlistname, username):
await client.say("!play "+track)
client.run('INSERTOKEN')
# El bot de Rythm no hace caso a otros bots. Solución: usar la API de youtube para crear una playlist con las canciones y pasárselo al bot de discord para que el user copie y pegue.
|
C#
|
UTF-8
| 3,172
| 3.15625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Xml;
using System.Text;
namespace ProtoEngine
{
/// <summary>
/// Klasa odpowiadająca opcji lub zmiennej dowolnego typu.
/// Dziedziczące klasy muszą udostępniać konstruktory:
/// (string name) - tworzy pustą instancję o nazwie name
/// (string name, XmlNode node) - tworszy nową instancję na podstawie DOM node
/// </summary>
public abstract class Option
{
/// <summary>
/// Nazwa opcji lub zmiennej.
/// </summary>
public String Name { get; set; }
abstract public String TypeName { get; }
/// <summary>
/// Zwraca wartość tej opcji jako tablicę bajtów, lub null jeśli nie ma wartości.
/// </summary>
/// <returns></returns>
abstract public byte[] toBytes();
/// <summary>
/// Dopasuj fragment danych wejściowych do tego typu opcji
/// </summary>
/// <param name="s">strumień który będzie dopasowywany</param>
/// <returns></returns>
abstract public bool match(TransactionalStreamReader s);
/// <summary>
/// Zwraca kopię (COW lub pełną) tej opcji.
/// </summary>
/// <returns>referencja do stworzonej kopii</returns>
abstract public Option copy();
/// <summary>
/// Ustawia wartość opcji na podstawie ciągu znaków.
/// </summary>
/// <param name="valueString"></param>
abstract public void setValueFromString(string valueString);
/// <summary>
/// Zwraca wartość opcji jako ciąg znaków. Zwrócona wartość musi
/// się nadawać do przekazania setValueFromString, i operacja:
/// o.setValueFromString(o.getValueFromString()) nie może zmieniać
/// wartości opcji
/// </summary>
/// <param name="valueString"></param>
abstract public string getValueAsString();
public abstract override bool Equals(object obj);
public static Dictionary<String, Type> optionClasses = new Dictionary<String, Type>() {
{"bool", typeof(OptionBool)},
{"byte", typeof(OptionInt)},
{"word", typeof(OptionInt)},
{"dword", typeof(OptionInt)},
{"int", typeof(OptionInt)},
{"array", typeof(OptionArray)}
};
public static Option fromXml(XmlNode node)
{
XmlNode nameNode = node.Attributes.GetNamedItem("name");
String name;
if (nameNode == null)
name = "";
else
name = nameNode.Value;
String typeName = node.Attributes["type"].Value.Split(null)[0];
Type type = optionClasses[typeName];
ConstructorInfo constructor = type.GetConstructor(new Type[] {
typeof(String), // name
typeof(XmlNode) });
return (Option)constructor.Invoke(new object[] { name, node });
}
public Option(String name) {
this.Name = name;
}
}
}
|
Java
|
UTF-8
| 346
| 2.34375
| 2
|
[] |
no_license
|
package model.repository;
public interface Queryable {
public static final int TYPE_STORY = 0,TYPE_GUEST=1,TYPE_SUB=2,TYPE_REP=3;
public int getType();
public boolean hasMember(String memName);
public Object getMember(String memName);
public boolean isMemberEqualTo(String memName,Queryable comparTo);
public String toString();
}
|
Java
|
UTF-8
| 136,583
| 2.515625
| 3
|
[] |
no_license
|
import com.sun.javaws.exceptions.InvalidArgumentException;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.*;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Border;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.concurrent.ThreadLocalRandom;
/**
* Created by Daniel Oh on 3/22/2017.
* This is Display class for ABIC
* Last Update: 4/5/2017
*/
public class Display extends Application {
Stage mainStage;
Scene Login_Scene, Forgot_Password_Scene, Enroll_idpass_Scene, Login_Help_Scene,
Enroll_Scene, Profile_Scene, Withdrawal_Scene, Post_Transfer_Scene,
Deposit_Scene, Transfer_Scene, Billpay_Scene, Post_Transaction_Scene, Help_Scene,User_Login_Scene,
Post_Login_Scene, Enroll_Success_Scene, Reset_Password_Scene, Reset_Password_Success_Scene;
Image Logo = new Image("ABIC_Logo.png");
public static void main(String[] args) {
DatabaseDriver db = new DatabaseDriver();
db.createNewDatabase("Main.db");
db.createNewTable(db.createLocalAccount());
db.createNewTable(db.createAccount());
db.createNewTable(db.createPerson());
launch(args);
}
@Override
public void start(Stage primaryStage) {
//Call Login scene at the start of the program
mainStage = primaryStage;
Login_Scene_Call();
mainStage.getIcons().add(new Image("ABIC_icon.png"));
mainStage.setTitle("");
mainStage.show();
}
/**
* Login Scene will be called at the beginning of the program
* And it will be the main menu throughout the program
*/
protected void Login_Scene_Call() {
//Main Gridpane set up
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(5);
grid.setVgap(5);
grid.setPadding(new Insets(10, 10, 20, 20));
grid.setStyle("-fx-background-color: white");
//Row 1 (Logo)
ImageView LogoView = new ImageView();
LogoView.setImage(Logo);
LogoView.setFitWidth(Logo.getWidth() / 4);
LogoView.setFitHeight(Logo.getHeight() / 4);
grid.add(LogoView, 6, 0, 3, 1);
//Row 2
//Row3
Button User_Login_Button = new Button("User Login");
User_Login_Button.setAlignment(Pos.CENTER);
User_Login_Button.setPadding(new Insets(5, 5, 5, 5));
User_Login_Button.setFont(Font.font("Tahoma", FontWeight.BOLD, 12));
User_Login_Button.setMinWidth(200);
grid.add(User_Login_Button, 0, 3, 2, 1);
User_Login_Button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
User_Login_Call();
}
});
//Row4
Button Enroll_Button = new Button("Enroll");
Enroll_Button.setAlignment(Pos.CENTER);
Enroll_Button.setPadding(new Insets(5, 5, 5, 5));
Enroll_Button.setFont(Font.font("Tahoma", FontWeight.BOLD, 12));
Enroll_Button.setMinWidth(70);
grid.add(Enroll_Button, 0, 4, 1, 1);
Enroll_Button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Enroll_idpass_Call();
}
});
Button Forgot_Button = new Button("Forgot Password");
Forgot_Button.setAlignment(Pos.CENTER);
Forgot_Button.setPadding(new Insets(5, 5, 5, 5));
Forgot_Button.setFont(Font.font("Tahoma", FontWeight.BOLD, 12));
Forgot_Button.setMinWidth(125);
grid.add(Forgot_Button, 1, 4, 1, 1);
Button help_Button = new Button("Help");
help_Button.setAlignment(Pos.CENTER);
help_Button.setPadding(new Insets(5, 5, 5, 5));
help_Button.setFont(Font.font("Tahoma", FontWeight.BOLD, 12));
help_Button.setMinWidth(200);
grid.add(help_Button, 0, 5, 2, 1);
help_Button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
help_Call();
}
});
Forgot_Button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Forgot_Password_Call();
}
});
Login_Scene = new Scene(grid, 800, 600);
mainStage.setScene(Login_Scene);
}
protected void help_Call(){
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(5);
grid.setVgap(5);
grid.setPadding(new Insets(10, 10, 20, 20));
grid.setStyle("-fx-background-color: white");
//Row 0 (Logo)
ImageView LogoView = new ImageView();
LogoView.setImage(Logo);
LogoView.setFitWidth(Logo.getWidth() / 4);
LogoView.setFitHeight(Logo.getHeight() / 4);
grid.add(LogoView, 3, 0, 3, 1);
Help help = new Help();
help.FAQ(grid);
help.contact(grid);
help.privacy(grid);
Button back_Button = new Button();
back_Button = Cancel_Button();
back_Button.setText("Back");
grid.add(back_Button, 1,21,1,1);
Login_Help_Scene = new Scene(grid,800,600);
mainStage.setScene(Login_Help_Scene);
}
protected void User_Login_Call() {
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(5);
grid.setVgap(5);
grid.setPadding(new Insets(10, 10, 20, 20));
grid.setStyle("-fx-background-color: white");
//Row 0 (Logo)
ImageView LogoView = new ImageView();
LogoView.setImage(Logo);
LogoView.setFitWidth(Logo.getWidth() / 4);
LogoView.setFitHeight(Logo.getHeight() / 4);
grid.add(LogoView, 3, 0, 3, 1);
//Row 1
Label welcome = new Label();
welcome.setText("Welcome Back to ABIC");
welcome.setFont(Font.font("Calibri", FontWeight.BOLD, 14));
grid.add(welcome, 0, 1, 2, 1);
//Row 2
Label user_Label = new Label();
user_Label.setText("Username");
user_Label.setFont(Font.font("", FontWeight.NORMAL, 12));
user_Label.setAlignment(Pos.CENTER_LEFT);
grid.add(user_Label, 1, 2, 1, 1);
//Row 3
TextField user_Field = new TextField();
grid.add(user_Field, 1, 3, 1, 1);
//Row 4
//Row 5
Label password_Label = new Label();
password_Label.setText("Password");
password_Label.setFont(Font.font("", FontWeight.NORMAL, 12));
password_Label.setAlignment(Pos.CENTER_LEFT);
grid.add(password_Label, 1, 5, 1, 1);
//Row 6
PasswordField password_Field = new PasswordField();
grid.add(password_Field, 1, 6, 1, 1);
//Row 7
HBox button_Box = new HBox();
button_Box.setAlignment(Pos.CENTER_RIGHT);
button_Box.setSpacing(5);
Button submit = new Button();
submit.setText("Submit");
submit.setAlignment(Pos.CENTER);
button_Box.getChildren().addAll(Cancel_Button(), submit);
grid.add(button_Box, 1, 7, 1, 1);
//Row 8
Label console_Label = new Label();
console_Label.setText("");
console_Label.setTextFill(Color.RED);
grid.add(console_Label,0,8,4,1);
submit.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
if (user_Field.getText().isEmpty() || password_Field.getText().isEmpty()){
console_Label.setText("Please enter username and password");
}
else{
String username = user_Field.getText();
String password = password_Field.getText();
//Validate username and password
//Search DB
String sql;
sql = "SELECT PASSWORD "
+ "FROM 'LOCAL ACCOUNT' WHERE USERNAME = " + "\"" + username + "\"";
DatabaseDriver db = new DatabaseDriver();
if(password.equals(db.getPassword(sql))){
String sql2;
sql2 = "SELECT Pk_LocalAccount_Id "
+ "FROM 'LOCAL ACCOUNT' WHERE USERNAME = " + "\"" + username + "\"";
String accountNumber = db.getAccountNumber(sql2);
Post_Login_Call(accountNumber);
}
else{
console_Label.setText("Username and password does not match");
}
}
}
});
//Start the Scene
User_Login_Scene = new Scene(grid, 800, 600);
mainStage.setScene(User_Login_Scene);
}
/**
* Forgot password scene will be called when user presses forgot password button
* it will search and validate the input using database and return current password back to user
* Since the program is strictly used in infranet, it won't involve sending emails
*/
protected void Forgot_Password_Call() {
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(5);
grid.setVgap(5);
grid.setPadding(new Insets(10, 10, 20, 20));
grid.setStyle("-fx-background-color: white");
//Row 0 (Logo)
ImageView LogoView = new ImageView();
LogoView.setImage(Logo);
LogoView.setFitWidth(Logo.getWidth() / 4);
LogoView.setFitHeight(Logo.getHeight() / 4);
grid.add(LogoView, 4, 0, 3, 1);
//Row 1
Label Forgot_Password_Label = new Label("Forgot Password");
Forgot_Password_Label.setFont(Font.font("Tahoma", FontWeight.BOLD, 14));
grid.add(Forgot_Password_Label, 0, 1, 2, 1);
//Row 2
Label reset_password_info = new Label("Reset Password through:");
reset_password_info.setFont(Font.font("Calibri", FontWeight.NORMAL, 11));
grid.add(reset_password_info, 0, 2, 2, 1);
//Row 3
Label username_label = new Label();
username_label.setText("○ Username:");
username_label.setFont(Font.font("Calibri", FontWeight.NORMAL, 11));
TextField username_Field = new TextField();
username_Field.setPromptText("Enter username");
grid.add(username_label, 1, 3, 1, 1);
grid.add(username_Field, 2, 3, 2, 1);
//Row 4
Label ssn_label = new Label();
ssn_label.setText("○ Social Security Number:");
ssn_label.setFont(Font.font("Calibri", FontWeight.NORMAL, 11));
TextField ssn_Field = new TextField();
ssn_Field.setPromptText("Enter SSN");
grid.add(ssn_label, 1, 4, 1, 1);
grid.add(ssn_Field, 2, 4, 2, 1);
//Row 5
Label empty_label = new Label(" ");
empty_label.setTextFill(Color.RED);
grid.add(empty_label, 0, 5, 5, 1);
//Row 6
//Row 7
Button submit_Button = new Button("Submit");
submit_Button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
DatabaseDriver db = new DatabaseDriver();
String sql = "";
if (username_Field.getText().isEmpty() || ssn_Field.getText().isEmpty()){
empty_label.setText("Please enter username and Social security number");
}
else {
sql = "SELECT * "
+ " FROM Person WHERE SSN = " + "\"" + ssn_Field.getText() + "\"";
String result = db.getSSN(sql);
if (result.isEmpty()){
empty_label.setText("No such account exists");
}
else{
sql = "SELECT Pk_Person_Id FROM Person WHERE SSN = " + "\"" + ssn_Field.getText() + "\"";
String accountNumber = db.getAccountNumber2(sql);
Reset_Password_Call(accountNumber);
}
}
}
});
HBox button_Box = new HBox();
button_Box.setSpacing(5);
button_Box.setPadding(new Insets(5, 5, 5, 5));
button_Box.getChildren().addAll(Cancel_Button(), submit_Button);
grid.add(button_Box, 0, 7, 3, 1);
//Change the Scene
Forgot_Password_Scene = new Scene(grid, 800, 600);
mainStage.setScene(Forgot_Password_Scene);
}
/**
* Program will ask user to input username and password for enrollment.
* it will take username parameter and search the database to see if it already exists in the database
*/
protected void Enroll_idpass_Call() {
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(5);
grid.setVgap(5);
grid.setPadding(new Insets(10, 10, 20, 20));
grid.setStyle("-fx-background-color: white");
//Row 0
ImageView LogoView = new ImageView();
LogoView.setImage(Logo);
LogoView.setFitWidth(Logo.getWidth() / 4);
LogoView.setFitHeight(Logo.getHeight() / 4);
grid.add(LogoView, 3, 0, 3, 1);
//Row 1
Label username_Label = new Label();
username_Label.setText("Username");
grid.add(username_Label, 0, 1, 1, 1);
//Row 2
TextField username_Field = new TextField();
username_Field.setPromptText("Enter username");
grid.add(username_Field, 0, 2, 1, 1);
//Row 3
Label password_Label = new Label();
password_Label.setText("Enter password");
Label password_Label2 = new Label();
password_Label2.setText("Confirm Password");
grid.add(password_Label, 0, 3, 1, 1);
grid.add(password_Label2,1,3,1,1);
//Row 4
PasswordField password_Field = new PasswordField();
grid.add(password_Field, 0, 4, 1, 1);
PasswordField password_Field2 = new PasswordField();
grid.add(password_Field2,1,4,1,1);
//Row 5
//Row 6
HBox button_Box = new HBox();
Button submit = new Button();
submit.setText("Submit");
grid.add(button_Box, 0, 6, 1, 1);
//Row 7
Label username_Console = new Label();
username_Console.setTextFill(Color.RED);
username_Console.setText("");
grid.add(username_Console, 0, 7, 3, 1);
/**
EventHandle
If username or password textfield is empty, it will ask user to enter the fields
else it will add the value into database and proceed to next screen
*/
submit.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
boolean passed = true;
String username = username_Field.getText();
String password = password_Field.getText();
String password2 = password_Field2.getText();
//If the username or password field is empty, it will ask user to fill the field
if (username.isEmpty() || password.isEmpty()) {
username_Console.setText("Please Enter username and password");
passed = false;
}
else if (!password.equals(password2)){
username_Console.setText("Passwords does not match");
}
else if (password.length() < 4){
username_Console.setText("Password is too short. Please enter more than 4 letters");
}
else {
int max = 999999999;
int min = 100000000;
int randomNumber = ThreadLocalRandom.current().nextInt(min, max + 1);
String sql = "";
// Tries to insert username into database, tells user if username already exists
try {
sql = String.format("INSERT INTO 'LOCAL ACCOUNT' (Pk_LocalAccount_Id, USERNAME, PASSWORD)" +
"VALUES (%d, \"%s\", \"%s\")", randomNumber, username, password);
if (!DatabaseDriver.checkDuplicates(username)) {
DatabaseDriver.run(sql);
DatabaseDriver.viewTable("'LOCAL ACCOUNT'");
Enroll_Call(username);
}
else {
username_Console.setText("Username already Exists.");
passed = false;
}
} catch (Exception e) {
username_Console.setText("Username already Exists.");
passed = false;
}
}
}
});
button_Box.setAlignment(Pos.CENTER_RIGHT);
button_Box.setSpacing(5);
button_Box.getChildren().addAll(Cancel_Button(), submit);
//Start the scene
Enroll_idpass_Scene = new Scene(grid, 800, 600);
mainStage.setScene(Enroll_idpass_Scene);
}
/**
* After username and password is validated, program will ask for personal information and validate it.
* After validation, it will store the data into database
*/
protected void Enroll_Call(String username) {
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(5);
grid.setVgap(5);
grid.setPadding(new Insets(10, 10, 20, 20));
grid.setStyle("-fx-background-color: white");
//Row 0
ImageView LogoView = new ImageView();
LogoView.setImage(Logo);
LogoView.setFitWidth(Logo.getWidth() / 4);
LogoView.setFitHeight(Logo.getHeight() / 4);
grid.add(LogoView, 3, 1, 3, 1);
//Row 1
Label Welcome_Logo = new Label();
Welcome_Logo.setText("Welcome to ABIC Banking Enrollment");
Welcome_Logo.setFont(Font.font("Calibri", FontWeight.BOLD, 13));
grid.add(Welcome_Logo, 0, 1, 3, 1);
//Row 2
Label Info_Logo = new Label();
Info_Logo.setText("Please enter your information in the spaces provided below");
Info_Logo.setFont(Font.font("Calibri", FontWeight.BOLD, 12));
grid.add(Info_Logo, 0, 2, 3, 1);
//Row 3
HBox First_Name_Box = new HBox();
First_Name_Box.setAlignment(Pos.CENTER_LEFT);
Label First_Name_Label = new Label();
First_Name_Label.setText("First Name");
First_Name_Label.setFont(Font.font("", FontWeight.BOLD, 11));
First_Name_Box.getChildren().addAll(First_Name_Label, red_star());
TextField First_Name_Field = new TextField();
First_Name_Field.setPromptText("Enter First Name");
Label First_Name_Console = new Label();
/**
* ***_Console is a label that will only appear when user pressed submit, and when there is/are an invalid
* input. Once user inputs valid value, it will disappear
*/
First_Name_Console.setText("");
grid.add(First_Name_Box, 0, 3, 1, 1);
grid.add(First_Name_Field, 1, 3, 1, 1);
grid.add(First_Name_Console, 2, 3, 1, 1);
//Row 4
Label First_Name_Info = new Label();
First_Name_Info.setText("Enter your first name as it appears on your primary billing account.");
First_Name_Info.setFont(Font.font("", FontWeight.NORMAL, 11));
grid.add(First_Name_Info, 0, 4, 3, 1);
//Row 5
HBox Last_Name_Box = new HBox();
Last_Name_Box.setAlignment(Pos.CENTER_LEFT);
Label Last_Name_Label = new Label();
Last_Name_Label.setText("Last Name");
Last_Name_Label.setFont(Font.font("", FontWeight.BOLD, 11));
Last_Name_Box.getChildren().addAll(Last_Name_Label, red_star());
TextField Last_Name_Field = new TextField();
Last_Name_Field.setPromptText("Enter Last Name");
Label Last_Name_Console = new Label();
Last_Name_Console.setText("");
grid.add(Last_Name_Box, 0, 5, 1, 1);
grid.add(Last_Name_Field, 1, 5, 1, 1);
grid.add(Last_Name_Console, 2, 5, 1, 1);
//Row 6
Label Last_Name_Info = new Label();
Last_Name_Info.setText("Enter your last name as it appears on your primary billing account.");
Last_Name_Info.setFont(Font.font("", FontWeight.NORMAL, 11));
grid.add(Last_Name_Info, 0, 6, 3, 1);
//Row 7
HBox ssn_Box = new HBox();
ssn_Box.setAlignment(Pos.CENTER_LEFT);
Label ssn_Label = new Label();
ssn_Label.setText("Social Security Number");
ssn_Label.setFont(Font.font("", FontWeight.BOLD, 11));
ssn_Box.getChildren().addAll(ssn_Label, red_star());
TextField ssn_Field = new TextField();
ssn_Field.setPromptText("_________");
Label ssn_Console = new Label();
ssn_Console.setText("");
grid.add(ssn_Box, 0, 7, 1, 1);
grid.add(ssn_Field, 1, 7, 1, 1);
grid.add(ssn_Console, 2, 7, 1, 1);
//Row 8
Label pAccount_Info = new Label();
pAccount_Info.setText("This account may be subject to billing or fees per our Terms and Conditions agreement. Enter numbers only as they appear on your monthly account statement. Do not use spaces or dashes.");
pAccount_Info.setFont(Font.font("", FontWeight.NORMAL, 11));
pAccount_Info.setWrapText(true);
grid.add(pAccount_Info, 0, 8, 3, 1);
//Row 9
HBox dob_Box = new HBox();
dob_Box.setAlignment(Pos.CENTER_LEFT);
Label dob_Label = new Label();
dob_Label.setText("Date of Birth");
dob_Label.setFont(Font.font("", FontWeight.BOLD, 11));
dob_Box.getChildren().addAll(dob_Label, red_star());
final DatePicker datePicker = new DatePicker();
datePicker.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
LocalDate date = datePicker.getValue();
}
});
Label dob_Console = new Label();
dob_Console.setText("");
grid.add(dob_Box, 0, 9, 1, 1);
grid.add(datePicker, 1, 9, 1, 1);
grid.add(dob_Console, 2, 9, 1, 1);
//Row 10
HBox hPhone_Box = new HBox();
hPhone_Box.setAlignment(Pos.CENTER_LEFT);
Label hPhone_Label = new Label();
hPhone_Label.setText("Home Phone");
hPhone_Label.setFont(Font.font("", FontWeight.BOLD, 11));
hPhone_Box.getChildren().addAll(hPhone_Label, red_star());
TextField hPhone_Field = new TextField();
hPhone_Field.setPromptText("XXXXXXXXXX");
Label hPhone_Console = new Label();
hPhone_Console.setText("");
grid.add(hPhone_Box, 0, 10, 1, 1);
grid.add(hPhone_Field, 1, 10, 1, 1);
grid.add(hPhone_Console, 2, 10, 1, 1);
//Row 11
HBox wPhone_Box = new HBox();
wPhone_Box.setAlignment(Pos.CENTER_LEFT);
Label wPhone_Label = new Label();
wPhone_Label.setText("Work Phone");
wPhone_Label.setFont(Font.font("", FontWeight.NORMAL, 11));
wPhone_Box.getChildren().addAll(wPhone_Label);
TextField wPhone_Field = new TextField();
wPhone_Field.setPromptText("XXXXXXXXXX");
Label wPhone_Console = new Label();
wPhone_Console.setText("");
grid.add(wPhone_Box, 0, 11, 1, 1);
grid.add(wPhone_Field, 1, 11, 1, 1);
grid.add(wPhone_Console, 2, 11, 1, 1);
//Row 12
Label phone_Info = new Label();
phone_Info.setText("If only one phone number is available, please enter it in Home phone categories. No Dashes");
phone_Info.setFont(Font.font("", FontWeight.NORMAL, 11));
phone_Info.setWrapText(true);
grid.add(phone_Info, 0, 12, 3, 1);
//Row 13
HBox address_Box = new HBox();
address_Box.setAlignment(Pos.CENTER_LEFT);
Label address_Label = new Label();
address_Label.setText("Address Line 1");
address_Label.setFont(Font.font("", FontWeight.BOLD, 11));
address_Box.getChildren().addAll(address_Label, red_star());
TextField address_Field = new TextField();
address_Field.setPromptText("Street Address");
Label address_Console = new Label();
address_Console.setText("");
grid.add(address_Box, 0, 13, 1, 1);
grid.add(address_Field, 1, 13, 1, 1);
grid.add(address_Console, 2, 13, 1, 1);
//Row 14
Label address2_Label = new Label();
address2_Label.setText("Address Line 2");
address2_Label.setFont(Font.font("", FontWeight.NORMAL, 11));
TextField address2_Field = new TextField();
address2_Field.setPromptText("Apartment, suite, unit");
grid.add(address2_Label, 0, 14, 1, 1);
grid.add(address2_Field, 1, 14, 1, 1);
//Row 15
//Row 16
HBox city_Box = new HBox();
city_Box.setAlignment(Pos.CENTER_LEFT);
Label city_Label = new Label();
city_Label.setText("City");
city_Label.setFont(Font.font("", FontWeight.BOLD, 11));
city_Box.getChildren().addAll(city_Label, red_star());
TextField city_Field = new TextField();
city_Field.setPromptText("Enter City");
Label city_Console = new Label();
city_Console.setText("");
grid.add(city_Box, 0, 16, 1, 1);
grid.add(city_Field, 1, 16, 1, 1);
grid.add(city_Console, 2, 16, 1, 1);
//Row 17
HBox State_Box = new HBox();
State_Box.setAlignment(Pos.CENTER_LEFT);
Label State_Label = new Label();
State_Label.setText("State");
State_Label.setFont(Font.font("", FontWeight.BOLD, 11));
ObservableList<String> states =
FXCollections.observableArrayList(
"Alabama",
"Alaska",
"Arizona",
"Arkansas",
"California",
"Colorado",
"Connecticut",
"Delaware",
"Florida",
"Georgia",
"Hawaii",
"Idaho",
"Illinois",
"Indiana",
"Iowa",
"Kansas",
"Kentucky",
"Louisiana",
"Maine",
"Maryland",
"Massachusetts",
"Michigan",
"Minnesota",
"Mississippi",
"Missouri",
"Montana",
"Nebraska",
"Nevada",
"New Hampshire",
"New Jersey",
"New Mexico",
"New York",
"North Carolina",
"North Dakota",
"Ohio",
"Oklahoma",
"Oregon",
"Pennsylvania",
"Rhode Island",
"South Carolina",
"South Dakota",
"Tennessee",
"Texas",
"Utah",
"Vermont",
"Virginia",
"Washington",
"West Virginia",
"Wisconsin",
"Wyoming"
);
ComboBox state_combo_box = new ComboBox(states);
state_combo_box.setMaxWidth(Double.MAX_VALUE);
Label state_Console = new Label();
state_Console.setText("");
State_Box.getChildren().addAll(State_Label, red_star());
grid.add(State_Box, 0, 17, 1, 1);
grid.add(state_combo_box, 1, 17, 1, 1);
grid.add(state_Console, 2, 17, 1, 1);
//Row 18
HBox zip_Box = new HBox();
zip_Box.setAlignment(Pos.CENTER_LEFT);
Label zip_Label = new Label();
zip_Label.setText("Zip Code");
zip_Label.setFont(Font.font("", FontWeight.BOLD, 11));
zip_Box.getChildren().addAll(zip_Label, red_star());
TextField zip_Field = new TextField();
zip_Field.setPromptText("Enter Zip");
Label zip_Console = new Label();
zip_Console.setText("");
grid.add(zip_Box, 0, 18, 1, 1);
grid.add(zip_Field, 1, 18, 1, 1);
grid.add(zip_Console, 2, 18, 1, 1);
//Row 19
HBox address_Info_Box = new HBox();
Label address_Info1 = new Label();
address_Info1.setText("All Fields marked with an asterisk (");
Label address_Info2 = new Label();
address_Info2.setText(") are required.");
address_Info_Box.getChildren().addAll(address_Info1, red_star(), address_Info2);
grid.add(address_Info_Box, 0, 19, 3, 1);
//Row 20
HBox button_Box = new HBox();
button_Box.setSpacing(5);
Button submit = new Button();
submit.setText("Submit");
submit.setAlignment(Pos.CENTER);
button_Box.getChildren().addAll(Cancel_Button(), submit);
grid.add(button_Box, 3, 20, 1, 1);
//EventHandler
submit.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//validate inputs and compare it with db
ssn_Console.setTextFill(Color.RED);
First_Name_Console.setTextFill(Color.RED);
Last_Name_Console.setTextFill(Color.RED);
dob_Console.setTextFill(Color.RED);
wPhone_Console.setTextFill(Color.RED);
hPhone_Console.setTextFill(Color.RED);
address_Console.setTextFill(Color.RED);
city_Console.setTextFill(Color.RED);
state_Console.setTextFill(Color.RED);
zip_Console.setTextFill(Color.RED);
boolean passed = true;
if (First_Name_Field.getText().isEmpty()) {
First_Name_Console.setText("Please enter first name");
passed = false;
} else
First_Name_Console.setText("");
if (Last_Name_Field.getText().isEmpty()) {
Last_Name_Console.setText("Please enter last name");
passed = false;
} else
Last_Name_Console.setText("");
if (ssn_Field.getText().isEmpty()) {
ssn_Console.setText("Please enter Social Security Number");
passed = false;
} else if (ssn_Field.getText().matches("[0-9]+") && ssn_Field.getText().length() == 9) {
ssn_Console.setText("");
} else {
ssn_Console.setText("Invalid Social Security Number");
passed = false;
}
if (datePicker.getValue() == null) {
dob_Console.setText("Please enter Date of Birth");
passed = false;
} else
dob_Console.setText("");
if (hPhone_Field.getText().isEmpty()) {
hPhone_Console.setText("Please Enter Home Phone");
passed = false;
} else if (hPhone_Field.getText().matches("[0-9]+") && hPhone_Field.getText().length() == 10) {
hPhone_Console.setText("");
} else {
hPhone_Console.setText("Invalid Phone number");
passed = false;
}
if (address_Field.getText().isEmpty()) {
address_Console.setText("Please Enter Address");
passed = false;
} else
address_Console.setText("");
if (city_Field.getText().isEmpty()) {
city_Console.setText("Please Enter City");
passed = false;
} else
city_Console.setText("");
if (state_combo_box.getValue() == null) {
state_Console.setText("Please choose State");
passed = false;
} else
state_Console.setText("");
if (zip_Field.getText().isEmpty()) {
zip_Console.setText("Please enter Zip code");
passed = false;
} else if (zip_Field.getText().matches("[0-9]+") && zip_Field.getText().length() == 5) {
zip_Console.setText("");
} else {
zip_Console.setText("Invalid Zip Code");
passed = false;
}
if (passed) {
String sql = String.format("INSERT INTO Person (Pk_Person_Id, 'FIRST NAME', 'LAST NAME', SSN, DOB, 'ADDRESS', CITY, STATE, 'ZIP CODE', 'HOME NUMBER', 'WORK NUMBER')" +
"VALUES ((SELECT Pk_LocalAccount_Id FROM 'LOCAL ACCOUNT' WHERE USERNAME = \"%s\" limit 1), \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\")",
username, First_Name_Field.getText(), Last_Name_Field.getText(), ssn_Field.getText(), datePicker.getValue().toString(),
address_Field.getText() + " " + address2_Field.getText(), city_Field.getText(), state_combo_box.getValue().toString(), zip_Field.getText(), hPhone_Field.getText(),
wPhone_Field.getText());
DatabaseDriver.run(sql);
DatabaseDriver.viewTable("Person");
Calendar calendar = Calendar.getInstance();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(calendar.getTime().getTime());
int min = 100000000;
int max = 999999999;
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);
String sql2 = String.format("INSERT INTO Account ('Pk_Account_Id', Account_Number, Type, Balance, Interest_Rate, Overdraft, Last_Access_Time_Stamp)" +
"VALUES ((SELECT Pk_LocalAccount_Id FROM 'LOCAL ACCOUNT' WHERE USERNAME = \"%s\" limit 1), \"%s\", \"1\", \"0.0\", \"0\", \"0.00\", \"%s\")", username, randomNum, currentTimestamp);
DatabaseDriver.run(sql2);
System.out.println("Passed!");
Enroll_Success_Call(First_Name_Field.getText(), ssn_Field.getText());
}
}
});
//Start new screen
Enroll_Scene = new Scene(grid, 800, 600);
mainStage.setScene(Enroll_Scene);
}
protected void Enroll_Success_Call(String first_Name, String ssn){
//Main Gridpane set up
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(5);
grid.setVgap(5);
grid.setPadding(new Insets(10, 10, 20, 20));
grid.setStyle("-fx-background-color: white");
//Row 1 (Logo)
ImageView LogoView = new ImageView();
LogoView.setImage(Logo);
LogoView.setFitWidth(Logo.getWidth() / 4);
LogoView.setFitHeight(Logo.getHeight() / 4);
grid.add(LogoView, 4, 0, 3, 1);
//Row 1 (Label with users name)
Label thanks_Label = new Label();
thanks_Label.setText("Thank you " + first_Name + "!");
thanks_Label.setFont(Font.font("", FontWeight.BOLD, 13));
grid.add(thanks_Label,0,1,1,1);
//Row 2
String sql = "SELECT * FROM Person WHERE SSN = " + ssn;
DatabaseDriver db = new DatabaseDriver();
Label account_Info_Label = new Label();
account_Info_Label.setText("Your account number is " + db.getAccountNumber2(sql));
account_Info_Label.setFont(Font.font("",FontWeight.BOLD,13));
grid.add(account_Info_Label,0,2,1,1);
//Row 3
Label info_Label = new Label();
info_Label.setText("You can now use your account to use our online banking service");
info_Label.setFont(Font.font("", FontWeight.NORMAL, 12));
grid.add(info_Label,0,3,1,1);
//Row 4
Button back_Button = new Button();
back_Button = Cancel_Button();
back_Button.setText("Login Page");
grid.add(back_Button,1,4,1,1);
Enroll_Success_Scene = new Scene(grid,800,600);
mainStage.setScene(Enroll_Success_Scene);
}
/**
* @return Return cancel button that will take user back to main menu(login scene)
*/
protected void Post_Login_Call(String accountNumber){
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER_LEFT);
grid.setHgap(5);
grid.setVgap(5);
grid.setPadding(new Insets(10,10,20,20));
grid.setStyle("-fx-background-color: white");
//Row 0 (Logo)
ImageView LogoView = new ImageView();
LogoView.setImage(Logo);
LogoView.setFitWidth(Logo.getWidth()/4);
LogoView.setFitHeight(Logo.getHeight()/4);
grid.add(LogoView,4,0,1,1);
//Menu Box
VBox menu_Box = new VBox();
menu_Box.setAlignment(Pos.CENTER_LEFT);
menu_Box.setMinWidth(100);
Hyperlink overview_Link = new Hyperlink();
overview_Link.setText("Overview");
overview_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
overview_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
overview_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
overview_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
overview_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
overview_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Post_Login_Call(accountNumber);
}
});
overview_Link.setBorder(Border.EMPTY);
Hyperlink profile_Link = new Hyperlink();
profile_Link.setText("Profile");
profile_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
profile_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
profile_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
profile_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
profile_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
profile_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Profile_Call(accountNumber);
}
});
profile_Link.setBorder(Border.EMPTY);
Hyperlink transaction_Link = new Hyperlink();
transaction_Link.setText("Transaction");
transaction_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
transaction_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transaction_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
transaction_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transaction_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
transaction_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Withdrawal_Call(accountNumber);
}
});
transaction_Link.setBorder(Border.EMPTY);
Hyperlink deposit_Link = new Hyperlink();
deposit_Link.setText("Deposit");
deposit_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
deposit_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
deposit_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
deposit_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
deposit_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
deposit_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Deposit_Call(accountNumber);
}
});
deposit_Link.setBorder(Border.EMPTY);
Hyperlink transfer_Link = new Hyperlink();
transfer_Link.setText("Transfer");
transfer_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
transfer_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transfer_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
transfer_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transfer_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
transfer_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Transfer_Call(accountNumber);
}
});
transfer_Link.setBorder(Border.EMPTY);
Hyperlink billpay_Link = new Hyperlink();
billpay_Link.setText("Bill pay");
billpay_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
billpay_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
billpay_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
billpay_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
billpay_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
billpay_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Billpay_Call(accountNumber);
}
});
billpay_Link.setBorder(Border.EMPTY);
Hyperlink help_Link = new Hyperlink();
help_Link.setText("Help");
help_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
help_Link.setTextFill(Color.BLUE);
help_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
help_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
help_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
help_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
help_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Help_Call(accountNumber);
}
});
help_Link.setBorder(Border.EMPTY);
Hyperlink logout_Link = new Hyperlink();
logout_Link.setText("Logout");
logout_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
logout_Link.setTextFill(Color.RED);
logout_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
logout_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
logout_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
logout_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
logout_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Login_Scene_Call();
}
});
logout_Link.setBorder(Border.EMPTY);
menu_Box.getChildren().addAll(
overview_Link,
profile_Link,
deposit_Link,
transfer_Link,
billpay_Link,
help_Link,
logout_Link);
grid.add(menu_Box,0,2,1,10);
//Row 1
Label account_Detail = new Label();
account_Detail.setText("Account Details");
account_Detail.setFont(Font.font("",FontWeight.BOLD,12));
grid.add(account_Detail,1,1,1,1);
//Row 2
DatabaseDriver db = new DatabaseDriver();
System.out.println(accountNumber);;
Label hello_Label = new Label();
hello_Label.setFont(Font.font("",FontWeight.NORMAL,13));
hello_Label.setAlignment(Pos.CENTER);
String hello_text = "Hello ";
String sql = "SELECT * "
+ " FROM Person WHERE Pk_Person_Id = " + "\"" + accountNumber + "\"";
hello_text = hello_text + db.getFirstName(sql)+ " " + db.getLastName(sql);
hello_Label.setText(hello_text);
grid.add(hello_Label,1,2,1,1);
//Row 3
Label balance_Label = new Label();
balance_Label.setText("Your balance is: ");
balance_Label.setFont(Font.font("",FontWeight.BOLD,12));
grid.add(balance_Label,1,3,1,1);
sql = "SELECT Balance "
+ "FROM Account WHERE Pk_Account_Id = " + "\"" + accountNumber + "\"";
Label balance = new Label();
balance.setAlignment(Pos.CENTER_RIGHT);
balance.setText("$ " + db.getBalance(sql));
balance.setFont(Font.font("",FontWeight.NORMAL,12));
grid.add(balance,2,3,1,1);
//Start the scene
Post_Login_Scene = new Scene(grid, 800, 600);
mainStage.setScene(Post_Login_Scene);
}
protected void Profile_Call(String accountNumber){
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER_LEFT);
grid.setHgap(5);
grid.setVgap(5);
grid.setPadding(new Insets(10,10,20,20));
grid.setStyle("-fx-background-color: white");
//Row 0 (Logo)
ImageView LogoView = new ImageView();
LogoView.setImage(Logo);
LogoView.setFitWidth(Logo.getWidth()/4);
LogoView.setFitHeight(Logo.getHeight()/4);
grid.add(LogoView,4,0,1,1);
//Menu Box
VBox menu_Box = new VBox();
menu_Box.setAlignment(Pos.CENTER_LEFT);
menu_Box.setMinWidth(100);
Hyperlink overview_Link = new Hyperlink();
overview_Link.setText("Overview");
overview_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
overview_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
overview_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
overview_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
overview_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
overview_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Post_Login_Call(accountNumber);
}
});
overview_Link.setBorder(Border.EMPTY);
Hyperlink profile_Link = new Hyperlink();
profile_Link.setText("Profile");
profile_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
profile_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
profile_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
profile_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
profile_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
profile_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Profile_Call(accountNumber);
}
});
profile_Link.setBorder(Border.EMPTY);
Hyperlink transaction_Link = new Hyperlink();
transaction_Link.setText("Transaction");
transaction_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
transaction_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transaction_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
transaction_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transaction_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
transaction_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Withdrawal_Call(accountNumber);
}
});
transaction_Link.setBorder(Border.EMPTY);
Hyperlink deposit_Link = new Hyperlink();
deposit_Link.setText("Deposit");
deposit_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
deposit_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
deposit_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
deposit_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
deposit_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
deposit_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Deposit_Call(accountNumber);
}
});
deposit_Link.setBorder(Border.EMPTY);
Hyperlink transfer_Link = new Hyperlink();
transfer_Link.setText("Transfer");
transfer_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
transfer_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transfer_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
transfer_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transfer_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
transfer_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Transfer_Call(accountNumber);
}
});
transfer_Link.setBorder(Border.EMPTY);
Hyperlink billpay_Link = new Hyperlink();
billpay_Link.setText("Bill pay");
billpay_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
billpay_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
billpay_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
billpay_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
billpay_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
billpay_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Billpay_Call(accountNumber);
}
});
billpay_Link.setBorder(Border.EMPTY);
Hyperlink logout_Link = new Hyperlink();
logout_Link.setText("Logout");
logout_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
logout_Link.setTextFill(Color.RED);
logout_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
logout_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
logout_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
logout_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
logout_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Login_Scene_Call();
}
});
logout_Link.setBorder(Border.EMPTY);
Hyperlink help_Link = new Hyperlink();
help_Link.setText("Help");
help_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
help_Link.setTextFill(Color.BLUE);
help_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
help_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
help_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
help_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
help_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Help_Call(accountNumber);
}
});
help_Link.setBorder(Border.EMPTY);
menu_Box.getChildren().addAll(
overview_Link,
profile_Link,
deposit_Link,
transfer_Link,
billpay_Link,
help_Link,
logout_Link);
grid.add(menu_Box,0,2,1,10);
DatabaseDriver db = new DatabaseDriver();
//Row 1
Label profile_Top_Label = new Label();
profile_Top_Label.setText("Profile");
profile_Top_Label.setFont(Font.font("",FontWeight.BOLD,14));
grid.add(profile_Top_Label,1,1,1,1);
//Row 2
Label first_Name_Label = new Label();
first_Name_Label.setText("First name ");
String sql = "SELECT * "
+ " FROM Person WHERE Pk_Person_Id = " + "\"" + accountNumber + "\"";
TextField first_Name_Field = new TextField();
first_Name_Field.setAlignment(Pos.CENTER_LEFT);
first_Name_Field.setEditable(false);
first_Name_Field.setText(db.getFirstName(sql));
grid.add(first_Name_Label,1,2,1,1);
grid.add(first_Name_Field,2,2,1,1);
//Row 3
Label last_Name_Label = new Label();
last_Name_Label.setText("Last name ");
TextField last_Name_Field = new TextField();
last_Name_Field.setAlignment(Pos.CENTER_LEFT);
last_Name_Field.setEditable(false);
last_Name_Field.setText(db.getLastName(sql));
grid.add(last_Name_Label,1,3,1,1);
grid.add(last_Name_Field,2,3,1,1);
//Row 4
Label ssn_Label = new Label();
ssn_Label.setText("Social Security Number ");
TextField ssn_Field = new TextField();
ssn_Field.setAlignment(Pos.CENTER_LEFT);
ssn_Field.setEditable(false);
ssn_Field.setText(db.getSSN(sql));
grid.add(ssn_Label,1,4,1,1);
grid.add(ssn_Field,2,4,1,1);
//Row 5
Label dob_Label = new Label();
dob_Label.setText("Date of Birth ");
TextField dob_Field = new TextField();
dob_Field.setAlignment(Pos.CENTER_LEFT);
dob_Field.setEditable(false);
dob_Field.setText(db.getDOB(sql));
grid.add(dob_Label,1,5,1,1);
grid.add(dob_Field,2,5,1,1);
//Row 6
Label address_Label = new Label();
address_Label.setText("Address ");
TextField address_Field = new TextField();
address_Field.setAlignment(Pos.CENTER_LEFT);
address_Field.setEditable(false);
address_Field.setText(db.getADDRESS(sql));
grid.add(address_Label,1,6,1,1);
grid.add(address_Field,2,6,1,1);
//Row 7
Label city_Label = new Label();
city_Label.setText("City ");
TextField city_Field = new TextField();
city_Field.setAlignment(Pos.CENTER_LEFT);
city_Field.setEditable(false);
city_Field.setText(db.getCITY(sql));
grid.add(city_Label,1,7,1,1);
grid.add(city_Field,2,7,1,1);
//Row 8
Label state_Label = new Label();
state_Label.setText("State ");
TextField state_Field = new TextField();
state_Field.setAlignment(Pos.CENTER_LEFT);
state_Field.setEditable(false);
state_Field.setText(db.getSTATE(sql));
grid.add(state_Label,1,8,1,1);
grid.add(state_Field,2,8,1,1);
//Row 9
Label zip_Label = new Label();
zip_Label.setText("Zip Code ");
TextField zip_Field = new TextField();
zip_Field.setAlignment(Pos.CENTER_LEFT);
zip_Field.setEditable(false);
zip_Field.setText(db.getZIPCODE(sql));
grid.add(zip_Label,1,9,1,1);
grid.add(zip_Field,2,9,1,1);
//Row 10
Label home_Number_Label = new Label();
home_Number_Label.setText("Home Phone Number ");
TextField home_Number_Field = new TextField();
home_Number_Field.setAlignment(Pos.CENTER_LEFT);
home_Number_Field.setEditable(false);
home_Number_Field.setText(db.getHOMENUMBER(sql));
grid.add(home_Number_Label,1,10,1,1);
grid.add(home_Number_Field,2,10,1,1);
//Row 11
Label work_Number_Label = new Label();
work_Number_Label.setText("Work Phone Number ");
TextField work_Number_Field = new TextField();
work_Number_Field.setAlignment(Pos.CENTER_LEFT);
work_Number_Field.setEditable(false);
work_Number_Field.setText(db.getWORKNUMBER(sql));
grid.add(work_Number_Label,1,11,1,1);
grid.add(work_Number_Field,2,11,1,1);
//Start the scene
Profile_Scene = new Scene(grid, 800, 600);
mainStage.setScene(Profile_Scene);
}
protected void Withdrawal_Call(String accountNumber){
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER_LEFT);
grid.setHgap(5);
grid.setVgap(5);
grid.setPadding(new Insets(10,10,20,20));
grid.setStyle("-fx-background-color: white");
//Row 0 (Logo)
ImageView LogoView = new ImageView();
LogoView.setImage(Logo);
LogoView.setFitWidth(Logo.getWidth()/4);
LogoView.setFitHeight(Logo.getHeight()/4);
grid.add(LogoView,4,0,1,1);
//Menu Box
VBox menu_Box = new VBox();
menu_Box.setAlignment(Pos.CENTER_LEFT);
menu_Box.setMinWidth(100);
Hyperlink overview_Link = new Hyperlink();
overview_Link.setText("Overview");
overview_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
overview_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
overview_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
overview_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
overview_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
overview_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Post_Login_Call(accountNumber);
}
});
overview_Link.setBorder(Border.EMPTY);
Hyperlink profile_Link = new Hyperlink();
profile_Link.setText("Profile");
profile_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
profile_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
profile_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
profile_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
profile_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
profile_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Profile_Call(accountNumber);
}
});
profile_Link.setBorder(Border.EMPTY);
Hyperlink transaction_Link = new Hyperlink();
transaction_Link.setText("Transaction");
transaction_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
transaction_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transaction_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
transaction_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transaction_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
transaction_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Withdrawal_Call(accountNumber);
}
});
transaction_Link.setBorder(Border.EMPTY);
Hyperlink deposit_Link = new Hyperlink();
deposit_Link.setText("Deposit");
deposit_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
deposit_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
deposit_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
deposit_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
deposit_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
deposit_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Deposit_Call(accountNumber);
}
});
deposit_Link.setBorder(Border.EMPTY);
Hyperlink transfer_Link = new Hyperlink();
transfer_Link.setText("Transfer");
transfer_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
transfer_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transfer_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
transfer_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transfer_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
transfer_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Transfer_Call(accountNumber);
}
});
transfer_Link.setBorder(Border.EMPTY);
Hyperlink billpay_Link = new Hyperlink();
billpay_Link.setText("Bill pay");
billpay_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
billpay_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
billpay_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
billpay_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
billpay_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
billpay_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Billpay_Call(accountNumber);
}
});
billpay_Link.setBorder(Border.EMPTY);
Hyperlink help_Link = new Hyperlink();
help_Link.setText("Help");
help_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
help_Link.setTextFill(Color.BLUE);
help_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
help_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
help_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
help_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
help_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Help_Call(accountNumber);
}
});
help_Link.setBorder(Border.EMPTY);
Hyperlink logout_Link = new Hyperlink();
logout_Link.setText("Logout");
logout_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
logout_Link.setTextFill(Color.RED);
logout_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
logout_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
logout_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
logout_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
logout_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Login_Scene_Call();
}
});
logout_Link.setBorder(Border.EMPTY);
menu_Box.getChildren().addAll(
overview_Link,
profile_Link,
deposit_Link,
transfer_Link,
billpay_Link,
help_Link,
logout_Link);
grid.add(menu_Box,0,2,1,10);
String sql = "";
//Row 1
Label withdrawal_Label = new Label();
withdrawal_Label.setText("Transaction History");
withdrawal_Label.setFont(Font.font("",FontWeight.BOLD,13));
grid.add(withdrawal_Label,1,1,1,1);
//Start the scene
Withdrawal_Scene = new Scene(grid,800,600);
mainStage.setScene(Withdrawal_Scene);
}
protected void Deposit_Call(String accountNumber){
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER_LEFT);
grid.setHgap(5);
grid.setVgap(5);
grid.setPadding(new Insets(10,10,20,20));
grid.setStyle("-fx-background-color: white");
//Row 0 (Logo)
ImageView LogoView = new ImageView();
LogoView.setImage(Logo);
LogoView.setFitWidth(Logo.getWidth()/4);
LogoView.setFitHeight(Logo.getHeight()/4);
grid.add(LogoView,4,0,1,1);
//Menu Box
VBox menu_Box = new VBox();
menu_Box.setAlignment(Pos.CENTER_LEFT);
menu_Box.setMinWidth(100);
Hyperlink overview_Link = new Hyperlink();
overview_Link.setText("Overview");
overview_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
overview_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
overview_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
overview_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
overview_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
overview_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Post_Login_Call(accountNumber);
}
});
overview_Link.setBorder(Border.EMPTY);
Hyperlink profile_Link = new Hyperlink();
profile_Link.setText("Profile");
profile_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
profile_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
profile_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
profile_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
profile_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
profile_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Profile_Call(accountNumber);
}
});
profile_Link.setBorder(Border.EMPTY);
Hyperlink transaction_Link = new Hyperlink();
transaction_Link.setText("Transaction");
transaction_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
transaction_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transaction_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
transaction_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transaction_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
transaction_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Withdrawal_Call(accountNumber);
}
});
transaction_Link.setBorder(Border.EMPTY);
Hyperlink deposit_Link = new Hyperlink();
deposit_Link.setText("Deposit");
deposit_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
deposit_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
deposit_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
deposit_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
deposit_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
deposit_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Deposit_Call(accountNumber);
}
});
deposit_Link.setBorder(Border.EMPTY);
Hyperlink transfer_Link = new Hyperlink();
transfer_Link.setText("Transfer");
transfer_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
transfer_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transfer_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
transfer_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transfer_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
transfer_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Transfer_Call(accountNumber);
}
});
transfer_Link.setBorder(Border.EMPTY);
Hyperlink billpay_Link = new Hyperlink();
billpay_Link.setText("Bill pay");
billpay_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
billpay_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
billpay_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
billpay_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
billpay_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
billpay_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Billpay_Call(accountNumber);
}
});
billpay_Link.setBorder(Border.EMPTY);
Hyperlink help_Link = new Hyperlink();
help_Link.setText("Help");
help_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
help_Link.setTextFill(Color.BLUE);
help_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
help_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
help_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
help_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
help_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Help_Call(accountNumber);
}
});
help_Link.setBorder(Border.EMPTY);
Hyperlink logout_Link = new Hyperlink();
logout_Link.setText("Logout");
logout_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
logout_Link.setTextFill(Color.RED);
logout_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
logout_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
logout_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
logout_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
logout_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Login_Scene_Call();
}
});
logout_Link.setBorder(Border.EMPTY);
menu_Box.getChildren().addAll(
overview_Link,
profile_Link,
deposit_Link,
transfer_Link,
billpay_Link,
help_Link,
logout_Link);
grid.add(menu_Box,0,2,1,10);
//Row 1
Label deposit_Label = new Label();
deposit_Label.setText("Deposit");
deposit_Label.setFont(Font.font("",FontWeight.BOLD,13));
grid.add(deposit_Label,1,1,1,1);
//Row 2
DatabaseDriver db = new DatabaseDriver();
Label current_Label = new Label();
current_Label.setText("Current Balance: $");
current_Label.setFont(Font.font("",FontWeight.NORMAL, 11));
grid.add(current_Label,1,2,1,1);
TextField current_Field = new TextField();
String sql = "SELECT * FROM Account WHERE Pk_Account_Id = " + accountNumber;
double current_Balance = Double.valueOf(db.getBalance(sql));
current_Field.setText(String.valueOf(current_Balance));
current_Field.setEditable(false);
grid.add(current_Field,2,2,1,1);
//Row 3
Label desire_Label = new Label();
desire_Label.setText("Enter deposit amount");
desire_Label.setFont(Font.font("",FontWeight.NORMAL, 11));
grid.add(desire_Label,1,3,1,1);
TextField desire_Field = new TextField();
desire_Field.setPromptText("Enter amount");
grid.add(desire_Field,2,3,1,1);
//Row 4
Label console = new Label();
console.setTextFill(Color.RED);
grid.add(console,1,4,4,1);
//Row 5
Button submit = new Button();
submit.setText("Submit");
submit.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
if (desire_Field.getText().isEmpty()){
console.setText("Please enter deposit amount");
}
else if (Double.valueOf(desire_Field.getText()) < 0){
console.setText("Please enter correct amount");
}
else {
String sql2 = "SELECT * FROM Account WHERE Pk_Account_Id = " + accountNumber;
BankAccountDriver bd = new BankAccountDriver();
bd.deposit(Double.valueOf(desire_Field.getText()), Integer.valueOf(accountNumber), Integer.valueOf(db.getBankAccount(sql2)));
double new_balance = current_Balance + Double.valueOf(desire_Field.getText());
Post_Transaction_Call(accountNumber, new_balance);
}
}
});
grid.add(submit, 1,5,1,1);
//Start the scene
Deposit_Scene = new Scene(grid,800,600);
mainStage.setScene(Deposit_Scene);
}
protected void Transfer_Call(String accountNumber){
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER_LEFT);
grid.setVgap(5);
grid.setPadding(new Insets(10,10,20,20));
grid.setStyle("-fx-background-color: white");
//Row 0 (Logo)
ImageView LogoView = new ImageView();
LogoView.setImage(Logo);
LogoView.setFitWidth(Logo.getWidth()/4);
LogoView.setFitHeight(Logo.getHeight()/4);
grid.add(LogoView,4,0,1,1);
//Menu Box
VBox menu_Box = new VBox();
menu_Box.setAlignment(Pos.CENTER_LEFT);
menu_Box.setMinWidth(100);
Hyperlink overview_Link = new Hyperlink();
overview_Link.setText("Overview");
overview_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
overview_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
overview_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
overview_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
overview_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
overview_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Post_Login_Call(accountNumber);
}
});
overview_Link.setBorder(Border.EMPTY);
Hyperlink profile_Link = new Hyperlink();
profile_Link.setText("Profile");
profile_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
profile_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
profile_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
profile_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
profile_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
profile_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Profile_Call(accountNumber);
}
});
profile_Link.setBorder(Border.EMPTY);
Hyperlink transaction_Link = new Hyperlink();
transaction_Link.setText("Transaction");
transaction_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
transaction_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transaction_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
transaction_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transaction_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
transaction_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Withdrawal_Call(accountNumber);
}
});
transaction_Link.setBorder(Border.EMPTY);
Hyperlink deposit_Link = new Hyperlink();
deposit_Link.setText("Deposit");
deposit_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
deposit_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
deposit_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
deposit_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
deposit_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
deposit_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Deposit_Call(accountNumber);
}
});
deposit_Link.setBorder(Border.EMPTY);
Hyperlink transfer_Link = new Hyperlink();
transfer_Link.setText("Transfer");
transfer_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
transfer_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transfer_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
transfer_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transfer_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
transfer_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Transfer_Call(accountNumber);
}
});
transfer_Link.setBorder(Border.EMPTY);
Hyperlink billpay_Link = new Hyperlink();
billpay_Link.setText("Bill pay");
billpay_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
billpay_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
billpay_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
billpay_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
billpay_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
billpay_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Billpay_Call(accountNumber);
}
});
billpay_Link.setBorder(Border.EMPTY);
Hyperlink help_Link = new Hyperlink();
help_Link.setText("Help");
help_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
help_Link.setTextFill(Color.BLUE);
help_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
help_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
help_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
help_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
help_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Help_Call(accountNumber);
}
});
help_Link.setBorder(Border.EMPTY);
Hyperlink logout_Link = new Hyperlink();
logout_Link.setText("Logout");
logout_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
logout_Link.setTextFill(Color.RED);
logout_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
logout_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
logout_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
logout_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
logout_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Login_Scene_Call();
}
});
logout_Link.setBorder(Border.EMPTY);
menu_Box.getChildren().addAll(
overview_Link,
profile_Link,
deposit_Link,
transfer_Link,
billpay_Link,
help_Link,
logout_Link);
grid.add(menu_Box,0,2,1,10);
//Row 1
Label transfer_Label = new Label();
transfer_Label.setText("Transfer");
transfer_Label.setFont(Font.font("",FontWeight.BOLD,13));
grid.add(transfer_Label,1,1,1,1);
//Row 2
Label current_acc_Label = new Label();
current_acc_Label.setText("Your account number ");
current_acc_Label.setFont(Font.font("",FontWeight.NORMAL,12));
TextField current_acc_Field = new TextField();
DatabaseDriver db = new DatabaseDriver();
String sql = "SELECT Account_Number "
+ "FROM Account WHERE Pk_Account_Id = " + "\"" + accountNumber + "\"";
current_acc_Field.setText(db.getBankAccount(sql));
current_acc_Field.setEditable(false);
current_acc_Field.setStyle("-fx-control-inner-background: lightgrey");
grid.add(current_acc_Label,1,2,1,1);
grid.add(current_acc_Field,2,2,1,1);
//Saving user bank account number to use later
int user_account_number = Integer.valueOf(db.getBankAccount(sql));
//Row 3
Label current_balance_Label = new Label();
current_balance_Label.setText("Your current balance ");
current_balance_Label.setFont(Font.font("",FontWeight.NORMAL,12));
TextField current_balance_Field = new TextField();
sql = "SELECT Balance "
+ "FROM Account WHERE Pk_Account_Id = " + "\"" + accountNumber + "\"";
current_balance_Field.setText("$ " + db.getBalance(sql));
current_balance_Field.setEditable(false);
current_balance_Field.setStyle("-fx-control-inner-background: lightgrey");
grid.add(current_balance_Label,1,3,1,1);
grid.add(current_balance_Field,2,3,1,1);
//Saving user bank account number to use later
double user_balance = Double.valueOf(db.getBalance(sql));
//Row 4
Label destination_Label = new Label();
destination_Label.setText("Designated account number ");
destination_Label.setFont(Font.font("",FontWeight.NORMAL,12));
TextField destination_Field = new TextField();
grid.add(destination_Label,1,4,1,1);
grid.add(destination_Field,2,4,1,1);
//Row 5
Label destination_balance_Label = new Label();
destination_balance_Label.setText("Transfer amount ");
destination_balance_Label.setFont(Font.font("",FontWeight.NORMAL,12));
TextField destination_balance_Field = new TextField();
grid.add(destination_balance_Label,1,5,1,1);
grid.add(destination_balance_Field,2,5,1,1);
//Row 6
Button submit = new Button();
submit.setText("Submit");
Label console = new Label();
console.setTextFill(Color.RED);
grid.add(submit,1,6,1,1);
grid.add(console,2,6,7,1);
db.viewTable("Account");
submit.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
try{
if (Double.valueOf(destination_balance_Field.getText()) > user_balance){
console.setText("Insufficient balance");
}
else if (Double.valueOf(destination_balance_Field.getText()) == 0 || destination_balance_Field.getText().isEmpty()){
console.setText("Enter amount");
}
else if (Double.valueOf(destination_balance_Field.getText()) < 0){
console.setText("Enter valid amount");
}
else{
String sql2 = "SELECT * FROM Account WHERE Account_Number = " + destination_Field.getText();
BankAccountDriver bd = new BankAccountDriver();
bd.withdraw(Double.valueOf(destination_balance_Field.getText()),
Integer.valueOf(accountNumber),
user_account_number);
bd.deposit(Double.valueOf(destination_balance_Field.getText()),
Integer.valueOf(db.getAccountNumber3(sql2)),
Integer.valueOf(destination_Field.getText()));
Post_Transaction_Call(accountNumber, user_balance -
Double.valueOf(destination_balance_Field.getText()));
}
} catch (Exception e){
console.setText("Enter valid amount and account number");
}
System.out.println("Success!");
}
});
Transfer_Scene = new Scene(grid,800,600);
mainStage.setScene(Transfer_Scene);
}
protected void Billpay_Call(String accountNumber){
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER_LEFT);
grid.setHgap(5);
grid.setVgap(5);
grid.setPadding(new Insets(10,10,20,20));
grid.setStyle("-fx-background-color: white");
//Row 0 (Logo)
ImageView LogoView = new ImageView();
LogoView.setImage(Logo);
LogoView.setFitWidth(Logo.getWidth()/4);
LogoView.setFitHeight(Logo.getHeight()/4);
grid.add(LogoView,4,0,1,1);
//Menu Box
VBox menu_Box = new VBox();
menu_Box.setAlignment(Pos.CENTER_LEFT);
menu_Box.setMinWidth(100);
Hyperlink overview_Link = new Hyperlink();
overview_Link.setText("Overview");
overview_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
overview_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
overview_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
overview_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
overview_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
overview_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Post_Login_Call(accountNumber);
}
});
overview_Link.setBorder(Border.EMPTY);
Hyperlink profile_Link = new Hyperlink();
profile_Link.setText("Profile");
profile_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
profile_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
profile_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
profile_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
profile_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
profile_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Profile_Call(accountNumber);
}
});
profile_Link.setBorder(Border.EMPTY);
Hyperlink transaction_Link = new Hyperlink();
transaction_Link.setText("Transaction");
transaction_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
transaction_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transaction_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
transaction_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transaction_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
transaction_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Withdrawal_Call(accountNumber);
}
});
transaction_Link.setBorder(Border.EMPTY);
Hyperlink deposit_Link = new Hyperlink();
deposit_Link.setText("Deposit");
deposit_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
deposit_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
deposit_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
deposit_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
deposit_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
deposit_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Deposit_Call(accountNumber);
}
});
deposit_Link.setBorder(Border.EMPTY);
Hyperlink transfer_Link = new Hyperlink();
transfer_Link.setText("Transfer");
transfer_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
transfer_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transfer_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
transfer_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transfer_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
transfer_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Transfer_Call(accountNumber);
}
});
transfer_Link.setBorder(Border.EMPTY);
Hyperlink billpay_Link = new Hyperlink();
billpay_Link.setText("Bill pay");
billpay_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
billpay_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
billpay_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
billpay_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
billpay_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
billpay_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Billpay_Call(accountNumber);
}
});
billpay_Link.setBorder(Border.EMPTY);
Hyperlink help_Link = new Hyperlink();
help_Link.setText("Help");
help_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
help_Link.setTextFill(Color.BLUE);
help_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
help_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
help_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
help_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
help_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Help_Call(accountNumber);
}
});
help_Link.setBorder(Border.EMPTY);
Hyperlink logout_Link = new Hyperlink();
logout_Link.setText("Logout");
logout_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
logout_Link.setTextFill(Color.RED);
logout_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
logout_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
logout_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
logout_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
logout_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Login_Scene_Call();
}
});
logout_Link.setBorder(Border.EMPTY);
menu_Box.getChildren().addAll(
overview_Link,
profile_Link,
deposit_Link,
transfer_Link,
billpay_Link,
help_Link,
logout_Link);
grid.add(menu_Box,0,2,1,10);
//Row 1
Label transfer_Label = new Label();
transfer_Label.setText("Bill Pay");
transfer_Label.setFont(Font.font("",FontWeight.BOLD,13));
grid.add(transfer_Label,1,1,1,1);
//Row 2
Label current_acc_Label = new Label();
current_acc_Label.setText("Your account number ");
current_acc_Label.setFont(Font.font("",FontWeight.NORMAL,12));
TextField current_acc_Field = new TextField();
DatabaseDriver db = new DatabaseDriver();
String sql = "SELECT Account_Number "
+ "FROM Account WHERE Pk_Account_Id = " + "\"" + accountNumber + "\"";
current_acc_Field.setText(db.getBankAccount(sql));
current_acc_Field.setEditable(false);
current_acc_Field.setStyle("-fx-control-inner-background: lightgrey");
grid.add(current_acc_Label,1,2,1,1);
grid.add(current_acc_Field,2,2,1,1);
//Saving user bank account number to use later
int user_account_number = Integer.valueOf(db.getBankAccount(sql));
//Row 3
Label current_balance_Label = new Label();
current_balance_Label.setText("Your current balance ");
current_balance_Label.setFont(Font.font("",FontWeight.NORMAL,12));
TextField current_balance_Field = new TextField();
sql = "SELECT Balance "
+ "FROM Account WHERE Pk_Account_Id = " + "\"" + accountNumber + "\"";
current_balance_Field.setText("$ " + db.getBalance(sql));
current_balance_Field.setEditable(false);
current_balance_Field.setStyle("-fx-control-inner-background: lightgrey");
grid.add(current_balance_Label,1,3,1,1);
grid.add(current_balance_Field,2,3,1,1);
//Saving user bank account number to use later
double user_balance = Double.valueOf(db.getBalance(sql));
//Row 4
Label company_Label = new Label();
company_Label.setText("Company name");
company_Label.setFont(Font.font("",FontWeight.NORMAL,12));
TextField company_Field = new TextField();
grid.add(company_Label,1,4,1,1);
grid.add(company_Field,2,4,1,1);
//Row 5
Label destination_Label = new Label();
destination_Label.setText("Designated account number ");
destination_Label.setFont(Font.font("",FontWeight.NORMAL,12));
TextField destination_Field = new TextField();
grid.add(destination_Label,1,5,1,1);
grid.add(destination_Field,2,5,1,1);
//Row 6
Label destination_balance_Label = new Label();
destination_balance_Label.setText("Pay amount ");
destination_balance_Label.setFont(Font.font("",FontWeight.NORMAL,12));
TextField destination_balance_Field = new TextField();
grid.add(destination_balance_Label,1,6,1,1);
grid.add(destination_balance_Field,2,6,1,1);
//Row 7
Button submit = new Button();
submit.setText("Submit");
Label console = new Label();
console.setTextFill(Color.RED);
grid.add(submit,1,7,1,1);
grid.add(console,2,7,7,1);
db.viewTable("Account");
submit.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
try{
if (Double.valueOf(destination_balance_Field.getText()) > user_balance){
console.setText("Insufficient balance");
}
else if (Double.valueOf(destination_balance_Field.getText()) == 0 || destination_balance_Field.getText().isEmpty()){
console.setText("Enter amount");
}
else if (Double.valueOf(destination_balance_Field.getText()) < 0){
console.setText("Enter valid amount");
}
else{
String sql2 = "SELECT * FROM Account WHERE Account_Number = " + destination_Field.getText();
BankAccountDriver bd = new BankAccountDriver();
bd.withdraw(Double.valueOf(destination_balance_Field.getText()),
Integer.valueOf(accountNumber),
user_account_number);
bd.deposit(Double.valueOf(destination_balance_Field.getText()),
Integer.valueOf(db.getAccountNumber3(sql2)),
Integer.valueOf(destination_Field.getText()));
Post_BillPay_Call(accountNumber, company_Field.getText(),user_balance -
Double.valueOf(destination_balance_Field.getText()));
}
} catch (Exception e){
console.setText("Enter valid amount and account number");
}
System.out.println("Success!");
}
});
Billpay_Scene = new Scene(grid,800,600);
mainStage.setScene(Billpay_Scene);
}
protected void Help_Call(String accountNumber){
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER_LEFT);
grid.setHgap(5);
grid.setVgap(5);
grid.setPadding(new Insets(10,10,20,20));
grid.setStyle("-fx-background-color: white");
//Row 0 (Logo)
ImageView LogoView = new ImageView();
LogoView.setImage(Logo);
LogoView.setFitWidth(Logo.getWidth()/4);
LogoView.setFitHeight(Logo.getHeight()/4);
grid.add(LogoView,4,0,1,1);
//Menu Box
VBox menu_Box = new VBox();
menu_Box.setAlignment(Pos.CENTER_LEFT);
menu_Box.setMinWidth(100);
Hyperlink overview_Link = new Hyperlink();
overview_Link.setText("Overview");
overview_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
overview_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
overview_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
overview_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
overview_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
overview_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Post_Login_Call(accountNumber);
}
});
overview_Link.setBorder(Border.EMPTY);
Hyperlink profile_Link = new Hyperlink();
profile_Link.setText("Profile");
profile_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
profile_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
profile_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
profile_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
profile_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
profile_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Profile_Call(accountNumber);
}
});
profile_Link.setBorder(Border.EMPTY);
Hyperlink transaction_Link = new Hyperlink();
transaction_Link.setText("Transaction");
transaction_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
transaction_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transaction_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
transaction_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transaction_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
transaction_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Withdrawal_Call(accountNumber);
}
});
transaction_Link.setBorder(Border.EMPTY);
Hyperlink deposit_Link = new Hyperlink();
deposit_Link.setText("Deposit");
deposit_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
deposit_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
deposit_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
deposit_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
deposit_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
deposit_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Deposit_Call(accountNumber);
}
});
deposit_Link.setBorder(Border.EMPTY);
Hyperlink transfer_Link = new Hyperlink();
transfer_Link.setText("Transfer");
transfer_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
transfer_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transfer_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
transfer_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transfer_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
transfer_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Transfer_Call(accountNumber);
}
});
transfer_Link.setBorder(Border.EMPTY);
Hyperlink billpay_Link = new Hyperlink();
billpay_Link.setText("Bill pay");
billpay_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
billpay_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
billpay_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
billpay_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
billpay_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
billpay_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Billpay_Call(accountNumber);
}
});
billpay_Link.setBorder(Border.EMPTY);
Hyperlink help_Link = new Hyperlink();
help_Link.setText("Help");
help_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
help_Link.setTextFill(Color.BLUE);
help_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
help_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
help_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
help_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
help_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Help_Call(accountNumber);
}
});
help_Link.setBorder(Border.EMPTY);
Hyperlink logout_Link = new Hyperlink();
logout_Link.setText("Logout");
logout_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
logout_Link.setTextFill(Color.RED);
logout_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
logout_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
logout_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
logout_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
logout_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Login_Scene_Call();
}
});
logout_Link.setBorder(Border.EMPTY);
menu_Box.getChildren().addAll(
overview_Link,
profile_Link,
deposit_Link,
transfer_Link,
billpay_Link,
help_Link,
logout_Link);
grid.add(menu_Box,0,2,1,10);
Help help= new Help();
help.FAQ(grid);
help.contact(grid);
help.privacy(grid);
//Start the scene
Help_Scene = new Scene(grid,800,600);
mainStage.setScene(Help_Scene);
}
protected void Post_Transaction_Call(String accountNumber, double balance){
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER_LEFT);
grid.setHgap(5);
grid.setVgap(5);
grid.setPadding(new Insets(10,10,20,20));
grid.setStyle("-fx-background-color: white");
//Row 0 (Logo)
ImageView LogoView = new ImageView();
LogoView.setImage(Logo);
LogoView.setFitWidth(Logo.getWidth()/4);
LogoView.setFitHeight(Logo.getHeight()/4);
grid.add(LogoView,4,0,1,1);
//Menu Box
VBox menu_Box = new VBox();
menu_Box.setAlignment(Pos.CENTER_LEFT);
menu_Box.setMinWidth(100);
Hyperlink overview_Link = new Hyperlink();
overview_Link.setText("Overview");
overview_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
overview_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
overview_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
overview_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
overview_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
overview_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Post_Login_Call(accountNumber);
}
});
overview_Link.setBorder(Border.EMPTY);
Hyperlink profile_Link = new Hyperlink();
profile_Link.setText("Profile");
profile_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
profile_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
profile_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
profile_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
profile_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
profile_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Profile_Call(accountNumber);
}
});
profile_Link.setBorder(Border.EMPTY);
Hyperlink transaction_Link = new Hyperlink();
transaction_Link.setText("Transaction");
transaction_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
transaction_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transaction_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
transaction_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transaction_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
transaction_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Withdrawal_Call(accountNumber);
}
});
transaction_Link.setBorder(Border.EMPTY);
Hyperlink deposit_Link = new Hyperlink();
deposit_Link.setText("Deposit");
deposit_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
deposit_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
deposit_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
deposit_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
deposit_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
deposit_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Deposit_Call(accountNumber);
}
});
deposit_Link.setBorder(Border.EMPTY);
Hyperlink transfer_Link = new Hyperlink();
transfer_Link.setText("Transfer");
transfer_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
transfer_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transfer_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
transfer_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transfer_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
transfer_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Transfer_Call(accountNumber);
}
});
transfer_Link.setBorder(Border.EMPTY);
Hyperlink billpay_Link = new Hyperlink();
billpay_Link.setText("Bill pay");
billpay_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
billpay_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
billpay_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
billpay_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
billpay_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
billpay_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Billpay_Call(accountNumber);
}
});
billpay_Link.setBorder(Border.EMPTY);
Hyperlink help_Link = new Hyperlink();
help_Link.setText("Help");
help_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
help_Link.setTextFill(Color.BLUE);
help_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
help_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
help_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
help_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
help_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Help_Call(accountNumber);
}
});
help_Link.setBorder(Border.EMPTY);
Hyperlink logout_Link = new Hyperlink();
logout_Link.setText("Logout");
logout_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
logout_Link.setTextFill(Color.RED);
logout_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
logout_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
logout_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
logout_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
logout_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Login_Scene_Call();
}
});
logout_Link.setBorder(Border.EMPTY);
menu_Box.getChildren().addAll(
overview_Link,
profile_Link,
deposit_Link,
transfer_Link,
billpay_Link,
help_Link,
logout_Link);
grid.add(menu_Box,0,2,1,10);
//Row 1
Label post_trans_Label = new Label();
post_trans_Label.setText("Your transaction was successful");
post_trans_Label.setFont(Font.font("",FontWeight.BOLD,13));
grid.add(post_trans_Label, 1,1,1,1);
//Row 2
Label post_Trans_balance_Label = new Label();
post_Trans_balance_Label.setText("Your new balance is: $" + balance);
post_Trans_balance_Label.setFont(Font.font("",FontWeight.NORMAL,11));
grid.add(post_Trans_balance_Label, 1,2,1,1);
Post_Transaction_Scene = new Scene(grid,800,600);
mainStage.setScene(Post_Transaction_Scene);
}
protected void Post_BillPay_Call(String accountNumber, String company, double balance){
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER_LEFT);
grid.setHgap(5);
grid.setVgap(5);
grid.setPadding(new Insets(10,10,20,20));
grid.setStyle("-fx-background-color: white");
//Row 0 (Logo)
ImageView LogoView = new ImageView();
LogoView.setImage(Logo);
LogoView.setFitWidth(Logo.getWidth()/4);
LogoView.setFitHeight(Logo.getHeight()/4);
grid.add(LogoView,4,0,1,1);
//Menu Box
VBox menu_Box = new VBox();
menu_Box.setAlignment(Pos.CENTER_LEFT);
menu_Box.setMinWidth(100);
Hyperlink overview_Link = new Hyperlink();
overview_Link.setText("Overview");
overview_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
overview_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
overview_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
overview_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
overview_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
overview_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Post_Login_Call(accountNumber);
}
});
overview_Link.setBorder(Border.EMPTY);
Hyperlink profile_Link = new Hyperlink();
profile_Link.setText("Profile");
profile_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
profile_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
profile_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
profile_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
profile_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
profile_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Profile_Call(accountNumber);
}
});
profile_Link.setBorder(Border.EMPTY);
Hyperlink transaction_Link = new Hyperlink();
transaction_Link.setText("Transaction");
transaction_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
transaction_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transaction_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
transaction_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transaction_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
transaction_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Withdrawal_Call(accountNumber);
}
});
transaction_Link.setBorder(Border.EMPTY);
Hyperlink deposit_Link = new Hyperlink();
deposit_Link.setText("Deposit");
deposit_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
deposit_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
deposit_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
deposit_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
deposit_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
deposit_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Deposit_Call(accountNumber);
}
});
deposit_Link.setBorder(Border.EMPTY);
Hyperlink transfer_Link = new Hyperlink();
transfer_Link.setText("Transfer");
transfer_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
transfer_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transfer_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
transfer_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
transfer_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
transfer_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Transfer_Call(accountNumber);
}
});
transfer_Link.setBorder(Border.EMPTY);
Hyperlink billpay_Link = new Hyperlink();
billpay_Link.setText("Bill pay");
billpay_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
billpay_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
billpay_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
billpay_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
billpay_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
billpay_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Billpay_Call(accountNumber);
}
});
billpay_Link.setBorder(Border.EMPTY);
Hyperlink help_Link = new Hyperlink();
help_Link.setText("Help");
help_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
help_Link.setTextFill(Color.BLUE);
help_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
help_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
help_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
help_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
help_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Help_Call(accountNumber);
}
});
help_Link.setBorder(Border.EMPTY);
Hyperlink logout_Link = new Hyperlink();
logout_Link.setText("Logout");
logout_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
logout_Link.setTextFill(Color.RED);
logout_Link.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
logout_Link.setFont(Font.font("",FontWeight.BOLD,11));
}
});
logout_Link.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
logout_Link.setFont(Font.font("",FontWeight.NORMAL, 11));
}
});
logout_Link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Login_Scene_Call();
}
});
logout_Link.setBorder(Border.EMPTY);
menu_Box.getChildren().addAll(
overview_Link,
profile_Link,
deposit_Link,
transfer_Link,
billpay_Link,
help_Link,
logout_Link);
grid.add(menu_Box,0,2,1,10);
//Row 1
Label post_trans_Label = new Label();
post_trans_Label.setText("Your Billpay to " + company +" was successful");
post_trans_Label.setFont(Font.font("",FontWeight.BOLD,13));
grid.add(post_trans_Label, 1,1,1,1);
//Row 2
Label post_Trans_balance_Label = new Label();
post_Trans_balance_Label.setText("Your new balance is: $" + balance);
post_Trans_balance_Label.setFont(Font.font("",FontWeight.NORMAL,11));
grid.add(post_Trans_balance_Label, 1,2,1,1);
Post_Transaction_Scene = new Scene(grid,800,600);
mainStage.setScene(Post_Transaction_Scene);
}
protected void Reset_Password_Call(String accountNumber){
//Main Gridpane set up
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(5);
grid.setVgap(5);
grid.setPadding(new Insets(10, 10, 20, 20));
grid.setStyle("-fx-background-color: white");
//Row 0 (Logo)
ImageView LogoView = new ImageView();
LogoView.setImage(Logo);
LogoView.setFitWidth(Logo.getWidth() / 4);
LogoView.setFitHeight(Logo.getHeight() / 4);
grid.add(LogoView, 4, 0, 3, 1);
//Row 1
Label reset_Label = new Label();
reset_Label.setText("Reset Password");
reset_Label.setFont(Font.font("",FontWeight.NORMAL,13));
grid.add(reset_Label,0,1,1,1);
//Row 2
Label new_Pass_Label = new Label();
new_Pass_Label.setText("Enter new password ");
PasswordField new_pass_Field = new PasswordField();
grid.add(new_Pass_Label,0,2,1,1);
grid.add(new_pass_Field,1,2,1,1);
//Row 3
Label new_Pass_Label2 = new Label();
new_Pass_Label2.setText("Confirm new password ");
PasswordField new_pass_Field2 = new PasswordField();
grid.add(new_Pass_Label2,0,3,1,1);
grid.add(new_pass_Field2,1,3,1,1);
//Row 4
Text console = new Text();
console.setFill(Color.RED);
grid.add(console, 0,4,6,1);
//Row 5
Button submit = new Button();
submit.setText("Submit");
submit.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
if (new_pass_Field.getText().equals(new_pass_Field2.getText())){
BankAccountDriver bd = new BankAccountDriver();
bd.reset_Password(new_pass_Field.getText(),Integer.valueOf(accountNumber));
Reset_Password_Success_Call();
}
else{
console.setText("Passwords does not match");
}
}
});
grid.add(submit,0,5,1,1);
Reset_Password_Scene = new Scene(grid,800,600);
mainStage.setScene(Reset_Password_Scene);
}
protected void Reset_Password_Success_Call(){
//Main Gridpane set up
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(5);
grid.setVgap(5);
grid.setPadding(new Insets(10, 10, 20, 20));
grid.setStyle("-fx-background-color: white");
//Row 0 (Logo)
ImageView LogoView = new ImageView();
LogoView.setImage(Logo);
LogoView.setFitWidth(Logo.getWidth() / 4);
LogoView.setFitHeight(Logo.getHeight() / 4);
grid.add(LogoView, 4, 0, 3, 1);
//Row 1
Label reset_Label = new Label();
reset_Label.setText("Password has been reseted. Please use your new password to login");
reset_Label.setFont(Font.font("",FontWeight.NORMAL,13));
grid.add(reset_Label,0,1,1,1);
//Row 2
Button back = new Button();
back = Cancel_Button();
back.setText("Back");
grid.add(back,0,2,1,1);
Reset_Password_Success_Scene = new Scene(grid,800,600);
mainStage.setScene(Reset_Password_Success_Scene);
}
protected Button Cancel_Button() {
Button cancel_Button = new Button("Cancel");
cancel_Button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
mainStage.setScene(Login_Scene);
}
});
return cancel_Button;
}
/**
* @return red-colored * to be used in various labels
*/
public Text red_star() {
//Red Star
Text rs = new Text();
rs.setText("*");
rs.setFill(Color.RED);
return rs;
}
}
|
Python
|
UTF-8
| 3,077
| 2.78125
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 22 23:16:30 2020
@author: PC MILO fixe
"""
import os
import matplotlib.pyplot as plt
from Src.controllers.swarmDescriptor import swarmDescriptor
from Src.milolib import toussaint
def testEverythingOnAnInstance( points, save = False, affiche = True ) :
"""
prend un ensemble de points sous la forme d'une liste de paires en entrée et effectue les tests dessus
affiche les points, l'enveloppe convexe, le diametre, le rectangle minimum et le cercle minimum si plote = Ture
renvoie l'enveloppe sous la forme d'une liste de paires
"""
if affiche :
fig, ax = plt.subplots()
plt.scatter([i[0] for i in points], [i[1] for i in points])
plt.axis([0, 800, 0, 800])
plt.axis('equal')
env = toussaint.enveloppeConvexe(points)
if affiche :
x = [i[0] for i in env]
y = [i[1] for i in env]
plt.plot(x, y, '-or')
diam = toussaint.calculDiametreOpti(points)
if affiche :
plt.plot([i[0] for i in diam], [i[1] for i in diam], 'yo-')
Rect = toussaint.Toussaint(env)
if affiche :
plt.plot([i[0] for i in Rect], [i[1] for i in Rect], 'go-')
Circle = toussaint.calculCercleMin(env)
if affiche :
circPlot = plt.Circle(Circle[0], radius = Circle[1], color = "orange", fill = False)
ax.add_artist(circPlot)
if save and affiche :
fig.savefig("everythingPlot.png")
return env
def justToussaintOnAnInstance( points, affiche = True ) :
"""
prend un ensemble de points sous la forme d'une liste de paires en entrée et effectue les tests dessus
affiche les points et l'enveloppe convexe si plote = True
renvoie l'enveloppe sous la forme d'une liste de paires
"""
if affiche :
fig, ax = plt.subplots()
plt.scatter([i[0] for i in points], [i[1] for i in points])
plt.axis([0, 800, 0, 800])
plt.axis('equal')
env = toussaint.enveloppeConvexe(points)
if affiche :
x = [i[0] for i in env]
y = [i[1] for i in env]
plt.plot(x, y, '-or')
return env
def display_topology(C):
D = C.data
print(D)
points = []
for i in D:
points.append((int(i["x_position"]), int(i['y_position'])))
print("Les points sont : ")
testEverythingOnAnInstance(points, affiche=True)
plt.show()
if(__name__=="__main__"):
print("Début du test de l'extracteur des propriétés de l'essaim sur le chemin : ",os.getcwd())
os.chdir("../..")
print("Le simulateur s'execute sur : ",os.getcwd())
C = swarmDescriptor("morphogenesis")
C.setTime(1000)
C.setTopology("random")
C.setNb_robots(100)
C.setRange(70)
C.executeSimulation()
D= C.data
print(D)
points = []
for i in D:
points.append((int(i["x_position"]), int(i['y_position'])))
print("Les points sont : ")
testEverythingOnAnInstance(points, affiche=True)
plt.show()
|
Java
|
UTF-8
| 1,116
| 1.90625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.avatech.edi.codegen.service.sql;
import com.avatech.edi.codegen.data.ModelConstant;
import com.avatech.edi.codegen.model.bo.DomainModel;
import com.avatech.edi.codegen.model.bo.project.ProjectStructure;
import com.avatech.edi.codegen.model.bo.project.modelparameter.BaseModelParameter;
import com.avatech.edi.codegen.service.imp.project.CommonService;
import com.avatech.edi.codegen.data.DataBaseType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.File;
import java.util.HashMap;
import java.util.List;
@Component
public class HANAHandler extends DataBaseHandler {
@Autowired
private CommonService commonService;
@Override
public DataBaseType getDBType() {
return DataBaseType.HANA;
}
/**
* 创建HANA数据库脚本
* @param domainModels
* @param baseModelParameter
*/
@Override
public void createDBSqlScript(List<DomainModel> domainModels, BaseModelParameter baseModelParameter) {
super.createDBSqlScript(domainModels,baseModelParameter);
}
}
|
Java
|
UTF-8
| 3,360
| 2.28125
| 2
|
[] |
no_license
|
package com.kpos.dao;
import com.kpos.domain.MenuCategory;
import org.springframework.stereotype.Repository;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import java.util.List;
/**
* Created by kpos.
* Author: kkwang
* Date: 3/10/12 11:21 PM
*/
@Repository
public class CategoryDao extends AbstractJpaDao<MenuCategory> implements ICategoryDao {
@Override
protected Class getEntityClass() {
return MenuCategory.class;
}
@Override
public MenuCategory findByName(String aName) {
Query namedQuery = this.entityManager.createNamedQuery("findCategoryByName");
namedQuery.setParameter("aName", aName);
try {
Object obj = namedQuery.getSingleResult();
if(obj != null) {
return (MenuCategory)obj;
}
return null;
}catch (NoResultException exception) {
return null;
}
}
@Override
public List<MenuCategory> listCategoriesByNameAsc() {
Query namedQuery = this.entityManager.createNamedQuery("listCategoriesByNameAsc");
return (List<MenuCategory>)namedQuery.getResultList();
}
@Override
public List<MenuCategory> listCategoriesByNameAsc(int begin, int maxSize) {
Query namedQuery = this.entityManager.createNamedQuery("listCategoriesByNameAsc");
if(begin >= 0 && maxSize >= 0) {
namedQuery.setFirstResult(begin);
namedQuery.setMaxResults(maxSize);
}
return (List<MenuCategory>)namedQuery.getResultList();
}
public void insertCategory(MenuCategory aCategory) {
if(aCategory.getId() == null) {
this.insert(aCategory);
} else {
MenuCategory temp = this.findById(aCategory.getId());
if(temp == null) {
aCategory.setId(null);
this.insert(aCategory);
}
}
}
@Override
public boolean deleteCategory(MenuCategory aCategory) {
if(aCategory.getId() != null) {
return this.delete(aCategory);
}
return false;
}
@Override
public MenuCategory updateCategory(MenuCategory aCategory) {
return this.update(aCategory);
}
@Override
public List<MenuCategory> listCategories() {
return this.findAll();
}
@Override
public MenuCategory findCategory(long aId) {
return this.findById(aId);
}
@Override
public List<MenuCategory> findCategoriesInGroup(long aGroupId) {
Query namedQuery = this.entityManager.createNamedQuery("listCategoriesByGroup");
namedQuery.setParameter("aGroupId", aGroupId);
return (List<MenuCategory>)namedQuery.getResultList();
}
@Override
public List<MenuCategory> findCategoriesInGroup(long aGroupId, int start, int maxSize) {
Query namedQuery = this.entityManager.createNamedQuery("listCategoriesByGroup");
namedQuery.setParameter("aGroupId", aGroupId);
if(start >= 0) {
namedQuery.setFirstResult(start);
}
if(maxSize >= 0) {
namedQuery.setMaxResults(maxSize);
}
return (List<MenuCategory>)namedQuery.getResultList();
}
}
|
C++
|
UTF-8
| 371
| 3.59375
| 4
|
[] |
no_license
|
/* Time Duration 4 Minutes (1746-1749)
* Write a C program to check whether a number is negative, positive, or zero.
*/
#include <stdio.h>
int main()
{
long int number;
scanf("%ld", &number);
if(number==0)
printf("0\n");
else if(number<0)
printf("negative number.\n");
else
printf("positive number.\n");
return 0;
}
|
PHP
|
UTF-8
| 3,210
| 2.5625
| 3
|
[
"Apache-2.0"
] |
permissive
|
<?php
namespace App\Controller\Api;
use App\Cache;
use Doctrine\ORM\EntityManager;
use App\Entity;
use App\Http\Request;
use App\Http\Response;
class NowplayingController
{
/** @var EntityManager */
protected $em;
/** @var Cache */
protected $cache;
/**
* @param EntityManager $em
* @param Cache $cache
* @see \App\Provider\ApiProvider
*/
public function __construct(EntityManager $em, Cache $cache)
{
$this->em = $em;
$this->cache = $cache;
}
/**
* @OA\Get(path="/nowplaying",
* tags={"Now Playing"},
* description="Returns a full summary of all stations' current state.",
* parameters={},
* @OA\Response(
* response=200,
* description="Success",
* @OA\Schema(
* type="array",
* @OA\Items(ref="#/components/schemas/NowPlaying")
* )
* )
* )
*
* @OA\Get(path="/nowplaying/{station_id}",
* tags={"Now Playing"},
* description="Returns a full summary of the specified station's current state.",
* @OA\Parameter(ref="#/components/parameters/station_id_required"),
* @OA\Response(
* response=200,
* description="Success",
* @OA\Schema(
* ref="#/components/schemas/NowPlaying"
* )
* ),
* @OA\Response(response=404, description="Station not found")
* )
*/
public function indexAction(Request $request, Response $response, $id = null): Response
{
$response = $response
->withHeader('Cache-Control', 'public, max-age=15')
->withHeader('X-Accel-Expires', 15); // CloudFlare caching
// Pull from cache, or load from flatfile otherwise.
/** @var Entity\Api\NowPlaying[] $np */
$np = $this->cache->get('api_nowplaying_data', function () {
$nowplaying_db = $this->em->createQuery('SELECT s.nowplaying FROM '.Entity\Station::class.' s WHERE s.is_enabled = 1')
->getArrayResult();
$np = [];
foreach($nowplaying_db as $np_row) {
$np[] = $np_row['nowplaying'];
}
return $np;
});
// Sanity check for now playing data.
if (empty($np)) {
return $response->withJson('Now Playing data has not loaded into the cache. Wait for file reload.', 500);
}
if (!empty($id)) {
foreach ($np as $np_row) {
if ($np_row->station->id == (int)$id || $np_row->station->shortcode === $id) {
$np_row->now_playing->recalculate();
return $response->withJson($np_row);
}
}
return $response->withJson('Station not found.', 404);
}
// If unauthenticated, hide non-public stations from full view.
if ($request->getAttribute('user') === null) {
$np = array_filter($np, function($np_row) {
return $np_row->station->is_public;
});
}
foreach ($np as $np_row) {
$np_row->now_playing->recalculate();
}
return $response->withJson($np);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.