language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
|---|---|---|---|---|---|---|---|
C#
|
UTF-8
| 5,082
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using RaptorDB;
namespace SampleViews
{
#region [ class definitions ]
//public enum State
//{
// Open,
// Closed,
// Approved
//}
public class LineItem
{
public decimal QTY { get; set; }
public string Product { get; set; }
public decimal Price { get; set; }
public decimal Discount { get; set; }
}
public class SalesInvoice
{
public SalesInvoice()
{
ID = Guid.NewGuid();
}
public Guid ID { get; set; }
public string CustomerName { get; set; }
public string NoCase { get; set; }
public string Address { get; set; }
public List<LineItem> Items { get; set; }
public DateTime Date { get; set; }
public int Serial { get; set; }
public byte Status { get; set; }
public bool Approved { get; set; }
//public State InvoiceState { get; set; }
}
#endregion
#region [ views ]
public class TestData
{
public Guid id;
public string username;
public string password;
}
public class TestSchema : RDBSchema
{
public string username;
public string password;
}
public class TestView : View<TestData>
{
public TestView()
{
this.Name = "test";
this.Schema = typeof(TestSchema);
this.Version = 1;
this.isPrimaryList = true;
this.isActive = true;
this.BackgroundIndexing = true;
this.Mapper = (api, docid, doc) =>
{
api.EmitObject(docid, doc);
};
}
}
[RegisterView]
public class SalesInvoiceViewRowSchema : RDBSchema
{
//[FullText]
public string CustomerName;
[CaseInsensitive]
[StringIndexLength(255)]
public string NoCase;
public DateTime Date;
public string Address;
public int Serial;
public byte Status;//{ get; set; }
public bool? Approved;// { get; set; }
//public State InvoiceState;
}
[RegisterView]
public class SalesInvoiceView : View<SalesInvoice>
{
public SalesInvoiceView()
{
this.Name = "SalesInvoice";
this.Description = "A primary view for SalesInvoices";
this.isPrimaryList = true;
this.isActive = true;
this.BackgroundIndexing = true;
this.Version = 6;
//// uncomment the following for transaction mode
//this.TransactionMode = true;
this.Schema = typeof(SalesInvoiceViewRowSchema);
this.FullTextColumns.Add(nameof(SalesInvoiceViewRowSchema.CustomerName));// "customername"); // this or the attribute
this.FullTextColumns.Add(nameof(SalesInvoiceViewRowSchema.Address));// "address");
this.CaseInsensitiveColumns.Add(nameof(SalesInvoiceViewRowSchema.NoCase));// "nocase"); // this or the attribute
//this.StringIndexLength.Add("nocase", 255);
this.Mapper = (api, docid, doc) =>
{
//int c = api.Count("SalesItemRows", "product = \"prod 1\"");
if (doc.Serial == 0)
api.RollBack();
api.EmitObject(docid, doc);
};
}
}
public class SalesItemRowsViewRowSchema : RDBSchema
{
public string Product;
public decimal QTY;
public decimal Price;
public decimal Discount;
}
[RegisterView]
public class SalesItemRowsView : View<SalesInvoice>
{
public SalesItemRowsView()
{
this.Name = "SalesItemRows";
this.Description = "";
this.isPrimaryList = false;
this.isActive = true;
this.BackgroundIndexing = true;
this.Schema = typeof(SalesItemRowsViewRowSchema);
this.Mapper = (api, docid, doc) =>
{
if (doc.Status == 3 && doc.Items != null)
foreach (var item in doc.Items)
api.EmitObject(docid, item);
};
}
}
public class NewViewRowSchema : RDBSchema
{
public string Product;
public decimal QTY;
public decimal Price;
public decimal Discount;
}
[RegisterView]
public class newview : View<SalesInvoice>
{
public newview()
{
this.Name = "newview";
this.Description = "";
this.isPrimaryList = false;
this.isActive = true;
this.BackgroundIndexing = true;
this.Version = 1;
this.Schema = typeof(NewViewRowSchema);
this.Mapper = (api, docid, doc) =>
{
if (doc.Status == 3 && doc.Items != null)
foreach (var i in doc.Items)
api.EmitObject(docid, i);
};
}
}
#endregion
}
|
Shell
|
UTF-8
| 7,224
| 3.84375
| 4
|
[
"MIT"
] |
permissive
|
#!/bin/bash
# create global ENVS associated array
source $HOME/.IPS
echo "cfgenv $cfgenv"
echo "ipscmd $ipscmd"
echo "ipsenv $ipsenv"
echo "runenv $runenv"
echo
echo
echo "$ipscmd creation"
echo
if [ -z $1 ] ; then
etcdctl ls --sort $cfgenv
exit 1
fi
etcdctl ls $cfgenv/${1} 2>/dev/null
if [ $? -ne 0 ] ; then
echo
echo "No secure VPC setup for gw ${1}"
echo
etcdctl ls --sort $cfgenv
echo
exit 1
fi
declare -A ENVS
# string for the vars
environmentVariables=""
tag="${1}"
gwhost="${tag}"
# string for the vars
tmpfile=/tmp/${ipscmd}.${gwhost}
echo "#!/bin/bash" > $tmpfile
##
##
# Take a key value array and add that into the $environmentVariables string
# $1 = array of data
generateEnvString(){
echo "generating the environment"
for i in ${!ENVS[@]}; do
val="${ENVS[$i]}"
key="$i"
echo "echo \"$key=$val\" >> /home/admin/firstconfig" >> $tmpfile
#environmentVariables="${environmentVariables} echo \"$key=$val\" >> /home/admin/firstconfig"
done
#echo "$environmentVariables" >> $tmpfile
echo "clish -c 'set timezone America / Toronto' -s" >> $tmpfile
echo "clish -c 'set ntp server primary 0.pool.ntp.org version 4' -s" >> $tmpfile
echo "clish -c 'set ntp server secondary 1.pool.ntp.org version 4' -s" >> $tmpfile
echo "clish -c 'set ntp active on' -s" >> $tmpfile
echo "clish -c 'set user admin shell /bin/bash' -s" >> $tmpfile
echo "config_system -f /home/admin/firstconfig" >> $tmpfile
echo "shutdown -r now" >> $tmpfile
}
##
# fetch the data from the segment of etcd specified and convert into a key value array
# presumes the segment is under /env/
# $1 = segment to use on etcd
environmentDataFromEtcd(){
# if no arg passed, return erro
#if [[ -z $1 ]]; then
# echo "No arugment passed, returning."
# return 1
#fi
tag=${1}
# check the env segment exists
local notFound=$(etcdctl ls ${cfgenv}/${tag}/config_system | grep 'Key not found' | wc -l)
# return error if not found
if [[ "$notFound" -gt "1" ]]; then
echo "Environment segment not set, returning."
return 2
fi
echo "fetching data from keystore"
# loop over the env vars and fetch the data
for i in `etcdctl ls ${cfgenv}/${tag}/config_system`; do
key=$(echo $i | sed -r "s#${cfgenv}/${tag}/config_system/##gi")
# fetch the env var
val=$(etcdctl get ${i});
if [ -z $val ]; then
echo "Could not retrive $i, possibly a directory, ignoring"
else
ENVS[$key]=${val};
fi
done
echo "fetched"
}
# create some test data
#generateTestEnvData
# fetch from a test area in the etcd env vars
environmentDataFromEtcd ${tag}
generateEnvString
# output the result:
msgbus "$ipscmd config_system file created for launch of gw instance $tag "
rm -rf ${tmpfile}.gz
gzip $tmpfile
# launch script
#
#
msgbus "$ipscmd started gw in $tag $site from $BUD"
mgenv="ctrl/cfg/mg/smc"
gwenv="${cfgenv}/${tag}"
region=$(etcdctl get $gwenv/region)
az=$(etcdctl get $gwenv/az)
AMI=$(etcdctl get $gwenv/AMI)
disk=$(etcdctl get $gwenv/disk)
sizeing=$(etcdctl get $gwenv/size)
size=$(etcdctl get size/gw/${sizeing})
points=$(etcdctl get points/${size})
vpcid=$(etcdctl get $gwenv/vpc)
subid=$(etcdctl get $gwenv/subnetid128)
eth1=$(etcdctl get $gwenv/eth1)
site=$(etcdctl get $gwenv/site)
secgroup=$(etcdctl get $gwenv/secgroup)
hostname=$(etcdctl get $gwenv/config_system/hostname)
sic=$(etcdctl get $gwenv/config_system/ftw_sic_key)
password=$(etcdctl get $mgenv/config_system/mgmt_admin_passwd)
host=$(echo "$hostname" | cut -d '.' -f 1)
InstanceId=$(aws ec2 run-instances --region $region --image-id $AMI --key-name $SKEY --user-data fileb://${tmpfile}.gz --instance-type $size --subnet-id $subid --private-ip-address 10.0.${site}.250 --block-device-mappings ${disk} | jq -r '.Instances[].InstanceId')
if [ "$InstanceId" == "" ] ; then
echo "couldn't start instance."
msgbus "$ipscmd could not start instance in region $region vpc $vpcid, exiting $BUD from this mess."
#kill-ops $host
#kill-secvpc $tag $site
exit 1
fi
#
msgbus "$ipscmd initalizing instance $InstanceId in region $region vpc $vpcid, congrats "
sleep 44
getdef=$(aws ec2 describe-instances --region $region --instance-ids $InstanceId | jq '.Reservations[].Instances[]')
declare -A myarray
while IFS="=" read -r key value ; do
myarray[$key]="$value"
done < <(echo "${getdef[@]}" | jq -cr 'to_entries | map("\(.key)=\(.value)") | flatten[]')
for key in "${!myarray[@]}" ; do
etcdctl set ${runenv}/${host}/$key "${myarray[$key]}"
done
#
# tag the instances so we can identify it
#
ENI=$(etcdctl get ${runenv}/${host}/NetworkInterfaces | jq -r '.[].NetworkInterfaceId')
aws ec2 create-tags --region $region --tags Key=Name,Value=$host --resources $InstanceId
msgbus "Tagging $InstanceId as $host "
aws ec2 create-tags --region $region --tags Key=session,Value=$SKEY --resources $InstanceId
echo "Waiting for public IP."
sleep 8
blastoff=$(date)
sleep 24
chkeni=$(aws ec2 modify-network-interface-attribute --region $region --network-interface-id $ENI --no-source-dest-check) ||
{ msgbus " $ipscmd $BUDDY failed to set interface src/dst check: ${NC}${chkeni} " ; exit 1 ; }
sleep 9
#
attachid=$(aws ec2 attach-network-interface --region $region --network-interface-id $eth1 --instance-id $InstanceId --device-index 1) ||
{ msgbus " ${TAGIPS} $ipscmd $BUD failed to attach: ${NC}${attachid} " ; exit 1 ; }
# Set DNS record
#
msgbus "$ipscmd $BUD additional ENI attached: ${attachid} ${NC} "
sleep 9
chketh=$(aws ec2 modify-network-interface-attribute --region $region --network-interface-id $eth1 --no-source-dest-check) ||
{ msgbus " $ipscmd $BUD failed to attach: ${NC}${attachid} " ; exit 1 ; }
IP=$(etcdctl get ${runenv}/${host}/PublicIpAddress)
sleep 3
msgbus "$hostname is $InstanceId at $IP "
dnsid=$(echo "$hostname" | cut -d '.' -f 2-)
zoneid=$(etcdctl get zone/${dnsid}.)
dns=$HOME/names/DNS.${host}.${dnsid}
echo "dns injection to resolve $1 to $IP"
echo "{" > $dns
echo " \"Comment\": \"${hostname} DNS\"," >> $dns
echo " \"Changes\": [" >> $dns
echo " {" >> $dns
echo "\"Action\": \"UPSERT\"," >> $dns
echo "\"ResourceRecordSet\": {" >> $dns
echo "\"Name\": \"${hostname}\"," >> $dns
echo "\"Type\": \"A\"," >> $dns
echo "\"TTL\": 60," >> $dns
echo "\"ResourceRecords\": [" >> $dns
echo " {" >> $dns
echo "\"Value\": \"$IP\"" >> $dns
echo " }" >> $dns
echo " ]" >> $dns
echo " }" >> $dns
echo " }" >> $dns
echo " ]" >> $dns
echo " }" >> $dns
aws route53 change-resource-record-sets --hosted-zone-id $zoneid --change-batch file://$dns
#
# let the user know whats happened
#
echo " "
sleep 5
echo "deployed"
#
# set launch time and cleanup before exit
#
land=$(date)
msgbus "$InstanceId launched at $blastoff, and should be landed in 10 minutes from $land time for a break? "
echo ""
echo "Please leave the gateway alone to self-configure."
echo " ElasticIP: $IP"
echo " Hostname: $hostname"
echo ""
echo ""
echo " "
curscore=$(etcdctl get score)
newscore=$(echo "$curscore + $points" | bc)
etcdctl set score "$newscore" &>/dev/null
msgbus "SCORE ${scoreit} $BUDDY has scored $points points"
etcdctl set ${gwenv}/status "launched" &>/dev/null
#/ips/ops/gwstat $tag $site &>>/dev/null &!
|
JavaScript
|
UTF-8
| 862
| 3.484375
| 3
|
[] |
no_license
|
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
//Runtime: 72ms, Memory Usage: 33.4MB
var bstToGst = function(root) {
/*
Construct a dictionary from the elements in the original tree as key
The value of the key will be the greater than sum
Remake the tree based off of the original tree but return a tree of just the values
*/
var carry = 0
const traverse = (node) => {
if(node != null){
traverse(node.right);
carry += node.val;
node.val = carry;
traverse(node.left);
}
}
traverse(root);
return root;
};
|
PHP
|
UTF-8
| 1,481
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace lib\Media\Filtering;
class Pixelate
extends \lib\Media\Filtering\AbstractImageFilter
implements \lib\Interfaces\InterfaceImageFilter
{
/**
* Pixelate::__construct()
*
* @param mixed $args (0=Pixelgröße (default=5), 1=AntializeOn (default=true) )
* @return void
*/
public function __construct( $args = array() )
{
#$intPixelSize=5, $bAntiAliazed=true
$this->filterName = 'Pixelate';
$this->args = $args;
$this->setPixelSize( (is_array($args) && count($args) > 0 ? intval($args[0]) : 5) );
$this->setAntialiaze( (is_array($args) && count($args) > 1 && !$args[1] ? false : true) );
}
public function setPixelSize($intPixelSize=0.0)
{
$this->args[0] = intval($intPixelSize);
}
public function setAntialiaze($bAntiAliazed)
{
$this->args[1] = $bAntiAliazed;
}
public function getPixelSize()
{
return $this->args[0];
}
public function isAntialiazed()
{
return $this->args[1];
}
public function applyFilter()
{
imagefilter($this->canvas, IMG_FILTER_PIXELATE, $this->getPixelSize(), $this->isAntialiazed());
}
}
|
Markdown
|
UTF-8
| 1,510
| 2.921875
| 3
|
[] |
no_license
|
从emploee表中查询出num,name,age,sex,homeaddr等5个字段的所有记录
```
mysql> SELECT num,name,age,sex,homeaddr FROM emploee;
+------+--------+------+------+----------+
| num | name | age | sex | homeaddr |
+------+--------+------+------+----------+
| 1 | 张三 | 26 | 男 | 北京 |
| 2 | 李思 | 24 | 女 | 北京 |
| 3 | 王五 | 25 | 男 | 长沙 |
| 4 | Aric | 15 | 男 | England |
+------+--------+------+------+----------+
4 rows in set (0.00 sec)
```
从emploee中查询出age小于26的记录,按照num字段降序进行排列。
```
mysql> SELECT num,name,age,sex,homeaddr FROM emploee WHERE age<26 ORDER BY num DESC;
+------+--------+------+------+----------+
| num | name | age | sex | homeaddr |
+------+--------+------+------+----------+
| 4 | Aric | 15 | 男 | England |
| 3 | 王五 | 25 | 男 | 长沙 |
| 2 | 李思 | 24 | 女 | 北京 |
+------+--------+------+------+----------+
3 rows in set (0.00 sec)
```
可以使用“*”代替所有字段
```
mysql> SELECT * FROM emploee;
+------+--------+------+------+----------+
| num | name | age | sex | homeaddr |
+------+--------+------+------+----------+
| 1 | 张三 | 26 | 男 | 北京 |
| 2 | 李思 | 24 | 女 | 北京 |
| 3 | 王五 | 25 | 男 | 长沙 |
| 4 | Aric | 15 | 男 | England |
+------+--------+------+------+----------+
4 rows in set (0.00 sec)
```
|
Markdown
|
UTF-8
| 3,072
| 3.53125
| 4
|
[] |
no_license
|
# STRINGS
* Strings are a series of characters between " or '
* String interpolation doesn't work with '' and neither do backslash
* characters like newline
```
puts "Add Them #{4+5} \n\n"
puts 'Add Them #{4+5} \n\n'
Add Them 9
Add Them #{4+5} \n\n
```
### A here-doc is normally used when you want a multiline string
```
multiline_string = <<EOM
This is a very long string
that contains interpolation
like #{600 + 66} \n\n
EOM
puts multiline_string
> This is a very long string
that contains interpolation
like 666
```
### Find all string methods by typing irb in terminal and "string".methods
```
first_name = 'Jacob'
last_name = 'Stevens'
```
### You can combine or concatenate strings with `+`
```
full_name1 = first_name + " "+ last_name
```
### Combining strings with interpolation
```
middle_name = "Justin"
full_name = "#{first_name} #{middle_name} #{last_name}"
```
### You can check if a string contains a string with `include`
```
puts full_name2.include?("Justin")
puts full_name1.include?("Justin")
> true
> false
```
### Get the `length` of a string
```
puts full_name1.size
>>> 13
```
### `Count` the number of vowels and Count the consonants
```
puts "Vowels : " + full_name.count("aeiou").to_s
puts "Consonants : " + full_name.count("^aeiou").to_s
> Vowels : 6
> Consonants : 14
```
### You can check if a string starts with another string
```
puts full_name2.start_with?("Stevens")
> false
```
### Return the index for the match
```
puts "Index : " + full_name2.index("Stevens").to_s
> 13
```
### Check equality of strings
```
puts "a == a : " + ("a" == "a").to_s
> a == a : true
```
### Check if they are the same object
```
puts "\"a\".equal?(\"a\") : " + ("a".equal?"a").to_s
puts first_name.equal?first_name
> "a".equal?("a") : false
> true
```
### Changing Case
```
puts full_name1.upcase
puts full_name1.downcase
puts full_name1.swapcase
> JACOB STEVENS
> jacob stevens
> jACOB sTEVENS
```
### Stripping white space
```
full_name = " " + full_name
full_name = full_name.lstrip
full_name = full_name.rstrip
full_name = full_name.strip
puts full_name
```
### Formatting Strings
```
puts full_name.rjust(20, '.')
puts full_name.ljust(20, '.')
puts full_name.center(20, '.')
> .......Jacob Stevens
> Jacob Stevens.......
> ...Jacob Stevens....
```
### Chop eliminates the last character
```
puts full_name2.chop
> Jacob Justin Steven
```
### Chomp eliminates `\n` or a specific string
```
puts full_name2.chomp
puts full_name2.chomp("ns")
> Jacob Justin Stevens
> Jacob Justin Stev
```
### Delete deletes provided characters
```
puts full_name.delete("a")
> Jcob Stevens
```
### Split a string into an array
```
name_array = full_name.split(//)
puts name_array
J
a
c
o
b
S
t
e
v
e
n
s
```
```
name_array = full_name2.split(/ /)
puts name_array
Jacob
Justin
Stevens
```
### String Conversions
```
puts "a".to_i
puts "2".to_f
puts "2".to_sym
> 0
> 2.0
> 2
```
```
# Escape sequences
# \\ Backslash
# \' Single-quote
# \" Double-quote
# \a Bell
# \b Backspace
# \f Formfeed
# \n Newline
# \r Carriage
# \t Tab
# \v Vertical tab
```
|
C++
|
UTF-8
| 4,543
| 3.6875
| 4
|
[] |
no_license
|
// HashTable.h -- class template for a hash table using chaining
#include "Queue.h"
#include "Array.h"
// client must provide a hash function with the following characteristics:
// 1 input parameter of DataType (see below), passed by const reference
// returns an integer between 0 and size - 1, inclusive, where size is the
// number of elements in the hash table
// the name of the function is passed as the first parameter to the HashTable
// constructor
// client may make as many hash functions for as many HashTables as desired
// if a struct is used for DataType, a typical use of retrieve, remove, and update would
// be to set the key of an object and then pass the object into the function
// retrieve, remove, and update will return false if:
// (1) the hash function supplied above does not return a valid index
// (2) the supplied key or element cannot be found in the hash table
// otherwise, these functions will return true if successful
// For retrieve, remove and update functions, if you are using an object as an element, a
// typical use would be to set the key of the desired object to retrieve, remove, or
// update; then pass the object into the function.
// If an object of a struct is used for DataType, the == operator must be
// overloaded for it; the left and right operands are both DataType objects
// the == comparison is used for finding elements, usually by key value
// Exceptions can be thrown in the constructor, the (default) copy constructor,
// the (default) assignment operator, or the insert function if out of heap memory.
// Uses the struct Profile made in earlier assignments
struct Profile {
std::string user;
// took out state since we don't use it
// std::string state;
// overloaded operator for printing out the contents of info
friend std::ostream& operator << (std::ostream& os, Profile profile) {
os << profile.user;
return os;
}
};
template <class DataType>
class HashTable
{
public:
HashTable(int(*hf)(const DataType &), int s);
bool insert(const DataType & newObject); // returns true if successful; returns
// false if invalid index was returned
// from hash function
bool retrieve(DataType & retrieved); // see description above class template
bool remove(DataType & removed); // see description above class template
bool update(DataType & updateObject); // see description above class template
void makeEmpty();
void printTable();
private:
Array< Queue<DataType> > table;
int(*hashfunc)(const DataType &); // pointer to hash function from client
};
// HashTable.cpp -- function definitions for a hash table using chaining
template <class DataType>
HashTable<DataType>::HashTable(int(*hf)(const DataType &), int s)
: table(s)
{
hashfunc = hf;
}
// fixed to use enqueue
template <class DataType>
bool HashTable<DataType>::insert(const DataType & newObject)
{
int location = hashfunc(newObject);
if (location < 0 || location >= table.length())
return false;
table[location].enqueue(newObject);
return true;
}
// fixed to use peek
template <class DataType>
bool HashTable<DataType>::retrieve(DataType & retrieved)
{
int location = hashfunc(retrieved);
if (location < 0 || location >= table.length())
return false;
if (!table[location].peek(retrieved))
return false;
return true;
}
// fixed to use dequeue
template <class DataType>
bool HashTable<DataType>::remove(DataType & removed)
{
int location = hashfunc(removed);
if (location < 0 || location >= table.length())
return false;
if (!table[location].dequeue(removed))
return false;
return true;
}
// TODO make find and replace functionality in Queue.h
template <class DataType>
bool HashTable<DataType>::update(DataType & updateObject)
{
int location = hashfunc(updateObject);
if (location < 0 || location >= table.length())
return false;
if (!table[location].findElement(updateObject))
return false;
table[location].replace(updateObject);
return true;
}
template <class DataType>
void HashTable<DataType>::makeEmpty()
{
for (int i = 0; i < table.length(); i++)
table[i].makeEmpty();
}
// created printTable function to print out entire table at the end
template<class DataType>
inline void HashTable<DataType>::printTable()
{
std::cout << std::endl << std::endl << "This is the current table: " << std::endl << std::endl;
for (int i = 0; i < table.length(); i++)
{
std::cout << "The queue at location " << i << " from first to last is: " << std::endl;
table[i].print();
std::cout << std::endl;
}
}
|
Python
|
UTF-8
| 150
| 2.859375
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
# Stdlib imports
import re
def split_uppercase(word):
word = re.findall('[A-Z][^A-Z]*', word)
return ' '.join(word)
|
Java
|
UTF-8
| 859
| 3.625
| 4
|
[] |
no_license
|
import java.util.Scanner;
class jervee1
{
public static void main(String[] args)
{
Scanner jerv = new Scanner(System.in);
String name, gender;
boolean status;
String singlemarried;
System.out.println("Enter name: ");
name = jerv.nextLine();
System.out.println("Enter gender: ");
gender = jerv.nextLine();
System.out.println("Are you Single? True/False: ");
status = jerv.nextBoolean();
switch(gender)
{
case 'Male':
case 'male':
singlemarried = status ? "Hi Mr. " + name + "How's single life?" : "Hi Mr. " + name + "How's married life?":
System.out.println(singlemarried);
break;
case 'Female':
case 'female':
singlemarried = status ? "Hi Miss " + name + "How's single life?" : "Hi Mrs. " + name + "How's married life?":
System.out.println(singlemarried);
break;
default:
System.out.println("Invalid");
}
}
}
|
Markdown
|
UTF-8
| 898
| 3.015625
| 3
|
[] |
no_license
|
# remoteControl
there are two pieces of software in this project:
1. an arduino program to do the following:
* Generate signal pulses out of 8 pins in pairs arranged as 4 channels
* Rotate a servo to a specific position indicated as 0 to 100
* Accept infrared remote control signals
* Accept USB remote control signals
* Indicate status on a 4 digit display
* timeout and turn off if no commands for 60 seconds
2. A web server to do the following
* connect to an arduino on a USB port running the above software
* Accept websocket connections from a client page and authenticate
* receive commands from the websocket client and forward them to the arduino
* receive status from the arduino and forward to a connected webclient
* simple webclient page to connect to the server and send various commands
* turn on/off pulses
* rotate servo up/down
* reset timeout
|
Markdown
|
UTF-8
| 541
| 2.59375
| 3
|
[] |
no_license
|
# Laravel Source Code Study
研讀 Laravel 程式碼的心得紀錄
# 目錄
* [前言](/preface.md)
* 準備工作
* [安裝](/install.md)
* 程式基本邏輯
* [開始](/start.md)
* [路由](/routes.md)
* [回傳](/response.md)
* MVC 架構
* [模型](/models.md)
* [視圖](/views.md)
* [控制器](/controllers.md)
* 輔助方法
* [輔助方法概觀](/helpers/index.md)
* [陣列](/helpers/array.md)
* 物件
* 路徑
* 字串
* 網址
* 其他
* 針對框架的測試
* 測試概觀
* 怎麼分析
|
Java
|
UTF-8
| 2,764
| 2.90625
| 3
|
[] |
no_license
|
package sun;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import jpcap.JpcapCaptor;
import jpcap.NetworkInterface;
import jpcap.NetworkInterfaceAddress;
import jpcap.packet.Packet;
public class SnifferDemo {
public static void main( String[] args ) throws IOException{
Scanner console = new Scanner(System.in);
getDevices();//显示PC机上可用的网卡的信息
System.out.println("请输入网卡号<0-2>");
int num = console.nextInt();//获取用户要打开的网卡号
System.out.println("请输入抓包时间(分钟)");
int minuets = console.nextInt();//获取用户抓包时间
oneByOneReceiver(num, minuets);//调用抓包方法
}
// 获取网络接口列表
public static void getDevices() {
NetworkInterface[] devices = JpcapCaptor.getDeviceList();
for (int i = 0; i < devices.length; i++) {
System.out.println(i + ": " + devices[i].name + "("
+ devices[i].description + ")");
System.out.println(" datalink: " + devices[i].datalink_name + "("
+ devices[i].datalink_description + ")");
System.out.print(" MAC address:");
for (byte b : devices[i].mac_address)
System.out.print(Integer.toHexString(b & 0xff) + ":");
System.out.println();
for (NetworkInterfaceAddress a : devices[i].addresses)
System.out.println(" address:" + a.address + " " + a.subnet
+ " " + a.broadcast);
}
}
// 使用逐个捕获方法, 从网络接口捕获数据包
public static void oneByOneReceiver(int index, int time) throws IOException {
NetworkInterface[] devices = JpcapCaptor.getDeviceList();
JpcapCaptor captor = JpcapCaptor.openDevice(devices[index], 65535,
false, 20);
PrintWriter pw = new PrintWriter(new FileWriter(new File("packets.txt")));
// 设置过滤器
captor.setFilter("ip", true);
int counter = 0;
Packet packet;
long startTime = System.currentTimeMillis();
while (startTime + time * 60 * 10 >= System.currentTimeMillis()) {
packet = captor.getPacket();
System.out.println(packet);
if (packet != null) {
String ips = packet.toString().split("\\s+")[1];
pw.write(ips);
pw.println();
counter++;
}
}
pw.close();
CounterPackets cp = new CounterPackets();
cp.readPackets();
cp.print();
System.out.println("PacketNumbers:" + counter);
}
}
|
JavaScript
|
UTF-8
| 595
| 3.75
| 4
|
[] |
no_license
|
var removeDuplicates = function (nums) {
let slow = 0;
for (let fast = 1; fast < nums.length; fast++) {
if (nums[fast] !== nums[slow]) {
slow++;
nums[slow] = nums[fast];
}
}
console.log(nums);
console.log(slow + 1);
return slow + 1;
}
// var removeDuplicates = function (nums) {
// let counter = 1;
// let current = nums[0];
// for (let i = 1; i < nums.length; i++) {
// if (current !== nums[i]) {
// counter++;
// current = nums[i]
// }
// }
// return counter;
// }
nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
removeDuplicates(nums)
|
Shell
|
UTF-8
| 7,287
| 4.09375
| 4
|
[] |
no_license
|
#!/bin/bash
#
# SPDX-License-Identifier: Apache-2.0
#
# Name:
# Create image utility
#
# Authors:
# 2017 Zack YL Shih <ZackYL.Shih@moxa.com>
# 2018 Fero JD Zhou <FeroJD.Zhou@moxa.com>
# 2019 Ken CJ Chou <KenCJ.Chou@moxa.com>
#
set -e
VERSION=1.3.0
usage() {
echo -e "Usage:"
echo -e " # ${0} <image_file> <partition_options1> [<partition_options2> ...]"
echo -e ""
echo -e "Parameters:"
echo -e " image_file"
echo -e " The image filename to be created"
echo -e ""
echo -e " partition_optionsX"
echo -e " A partition option is in the format:"
echo -e " <part_no>,<part_size>,<boot_flag>,<part_type>,<fs_type>"
echo -e " For example:"
echo -e " 1,32,y,b,vfat"
echo -e " this means partition number 1 is a partition with"
echo -e " 32MB size, boot flag enabled, and vfat filesystem"
echo -e ""
echo -e "Example:"
echo -e " Create an image named \"output.img\" with 2 partitions"
echo -e " whose partition 1 is 32MB size, boot flag enabled, and vfat filesystem"
echo -e " and partition 2 is 100MB size, boot flag disabled, and ext4 filesystem"
echo -e " # ./create-img output.img \"1,32,y,b,vfat\" \"2,100,n,83,ext4\""
echo -e ""
return 0
}
log_msg() {
local msg=${1}
echo -ne "\e[1;33m[create-img]\e[0m "
echo "${msg}"
return 0
}
is_number() {
local string=${1}
case "${string}" in
""|*[!0-9]*)
return 1
;;
*)
return 0
;;
esac
}
PARTITION_TYPES=" 0 1 2 3 4 5 6 7 8 9 a b c e f 10 11 12 14 16 17 18 "\
"1b 1c 1e 24 27 39 3c 40 41 42 4d 4e 4f 50 51 52 53 54 55 56 5c 61 63 64 65 "\
"70 75 80 81 82 83 84 85 86 87 88 8e 93 94 9f a0 a5 a6 a7 a8 a9 ab af b7 b8 "\
"bb bc be bf c1 c4 c6 c7 da db de df e1 e3 e4 ea eb ee ef f0 f1 f2 f4 fb fc "\
"fd fe ff "
is_valid_partition_type() {
local part_type=${1}
if echo "${PARTITION_TYPES}" | grep -q " ${part_type} "; then
return 0
else
return 1
fi
}
is_valid_fs_type() {
local fs_type=${1}
# Currently we only support raw, vfat and ext4
local fs_support_list="raw vfat ext4"
local i
for i in ${fs_support_list}; do
if [ "${fs_type}" == "${i}" ]; then
return 0
fi
done
return 1
}
get_value() {
local tmp
tmp="$(echo "${1}" | grep "^${2}=")"
echo "${tmp##*=}"
return 0
}
get_image_info() {
local imgfile=${1}
local fdisk_l_output sec_size num_part part_info
local line count tmp
echo "IMAGE_FILE=${imgfile}"
echo "IMAGE_FILENAME=${imgfile##*/}"
fdisk_l_output="$(fdisk -l ${imgfile})"
# get sector size
sec_size="$(echo "${fdisk_l_output}" | grep "^Units:")"
sec_size="${sec_size##*= }"
sec_size="${sec_size%% bytes}"
echo "IMAGE_SECTOR_SIZE=${sec_size}"
# get partition information
part_info="$(echo "${fdisk_l_output}" | grep "^${imgfile}[0-9]")"
num_part=$(echo "${part_info}" | wc -l)
echo "IMAGE_NUM_OF_PARTITIONS=${num_part}"
count=0
while read -r line; do
count=$((count + 1))
# bootflag is set if the line contains '*'
if echo "${line}" | grep -q "*"; then
line="$(echo "${line}" | sed 's/*//')"
echo "IMAGE_P${count}_BOOTFLAG=y"
else
echo "IMAGE_P${count}_BOOTFLAG=n"
fi
tmp="$(echo "${line}" | awk '{print $1}')"
echo "IMAGE_P${count}_NUMBER=${tmp##*${imgfile}}"
tmp="$(echo "${line}" | awk '{print $2}')"
echo "IMAGE_P${count}_OFFSET=$((tmp * sec_size))"
tmp="$(echo "${line}" | awk '{print $4}')"
echo "IMAGE_P${count}_SIZE=$((tmp * sec_size))"
tmp="$(echo "${line}" | awk '{print $6}')"
echo "IMAGE_P${count}_FSTYPE=${tmp}"
done <<< "${part_info}"
return 0
}
extract_information() {
local num_of_partitions
local img_size=0
local fdisk_cmd=""
num_of_partitions=$#
for i in $(seq 1 ${num_of_partitions}); do
# "<part_no>,<part_size>,<boot_flag>,<part_type>,<fs_type>"
local part_no="$(echo "${!i}" | awk -F, '{print $1}')"
local part_size="$(echo "${!i}" | awk -F, '{print $2}')"
local boot_flag="$(echo "${!i}" | awk -F, '{print $3}')"
local part_type="$(echo "${!i}" | awk -F, '{print $4}')"
local fs_type="$(echo "${!i}" | awk -F, '{print $5}')"
# Check if values are valid
if ! is_number "${part_no}"; then
echo -e "Partition number \"${part_no}\" not valid" >&2
return 1
fi
if ! is_number "${part_size}"; then
echo -e "Partition size \"${part_size}\" not valid" >&2
return 1
fi
if [ "${boot_flag}" != "y" ] && [ "${boot_flag}" != "n" ]; then
echo -e "Boot flag should be \"y\" or \"n\"" >&2
return 1
fi
if ! is_valid_partition_type "${part_type}"; then
echo -e "Partition type \"${part_type}\" not valid" >&2
return 1
fi
if ! is_valid_fs_type "${fs_type}"; then
echo -e "Filesystem type \"${fs_type}\" not valid" >&2
return 1
fi
# Count image total size
img_size="$(( img_size + part_size ))"
# Generate command for fdisk
fdisk_cmd="${fdisk_cmd}n\np\n${part_no}\n\n"
if [ ${i} -eq 1 ]; then
fdisk_cmd="${fdisk_cmd}+${part_size}M\n"
if [ "${boot_flag}" == "y" ]; then
fdisk_cmd="${fdisk_cmd}a\n"
fi
fdisk_cmd="${fdisk_cmd}t\n${part_type}\n"
elif [ ${i} -eq ${num_of_partitions} ]; then
fdisk_cmd="${fdisk_cmd}\n"
if [ "${boot_flag}" == "y" ]; then
fdisk_cmd="${fdisk_cmd}a\n${part_no}\n"
fi
fdisk_cmd="${fdisk_cmd}t\n${part_no}\n${part_type}\n"
else
fdisk_cmd="${fdisk_cmd}+${part_size}M\n"
if [ "${boot_flag}" == "y" ]; then
fdisk_cmd="${fdisk_cmd}a\n${part_no}\n"
fi
fdisk_cmd="${fdisk_cmd}t\n${part_no}\n${part_type}\n"
fi
done
fdisk_cmd="${fdisk_cmd}w\n"
echo "Num_of_Partitions=${num_of_partitions}"
echo "Image_Size=${img_size}"
echo "Fdisk_Command=${fdisk_cmd}"
return 0
}
format_partitions() {
local img=${1}
local img_info i n_part
shift 1
img_info="$(get_image_info "${img}")"
n_part=$(get_value "${img_info}" "IMAGE_NUM_OF_PARTITIONS")
for i in $(seq 1 ${n_part}); do
# "<part_no>,<part_size>,<boot_flag>,<part_type>,<fs_type>"
local fs_type="$(echo "${!i}" | awk -F, '{print $5}')"
local p_offset=$(get_value "${img_info}" "IMAGE_P${i}_OFFSET")
local p_size=$(get_value "${img_info}" "IMAGE_P${i}_SIZE")
local loopdev
loopdev="$(losetup -f)"
losetup -o ${p_offset} --sizelimit ${p_size} ${loopdev} ${img}
# Perform formation for different fs_type
# vfat: format
# ext4: format with journal
# raw: do nothing
if [ "${fs_type}" == "ext4" ]; then
mkfs -t ${fs_type} -J size=8 ${loopdev} >/dev/null 2>&1
elif [ "${fs_type}" == "vfat" ]; then
mkfs -t ${fs_type} ${loopdev} >/dev/null
fi
losetup -d ${loopdev}
done
return 0
}
main() {
local image=${1}
local extracted_info img_size fdisk_cmd
if [ "${image}" == "-v" ] || [ "${image}" == "--version" ]; then
echo "${VERSION}"
return 0
fi
shift 1
if [ -f ${image} ]; then
echo "Error: file \"${image}\" already exist" >&2
return 1
fi
log_msg "Extract information from options"
extracted_info="$(extract_information "$@")"
img_size="$(get_value "${extracted_info}" "Image_Size")"
fdisk_cmd="$(get_value "${extracted_info}" "Fdisk_Command")"
log_msg "Generating image file"
truncate -s $((img_size * 1024 * 1024)) ${image}
log_msg "Creating partitions"
echo -ne "${fdisk_cmd}" | fdisk "${image}" >/dev/null
log_msg "Formating partitions"
format_partitions "${image}" "$@"
log_msg "OK"
return 0
}
if [ "${EUID}" -ne 0 ]; then
echo "Please run as root" >&2
exit 1
fi
if [ $# -lt 2 ]; then
usage >&2
exit 1
fi
main "$@"
exit 0
|
JavaScript
|
UTF-8
| 1,675
| 2.703125
| 3
|
[] |
no_license
|
import React from 'react';
const CheckBox = ({ name, label, onChange, selectedOptions, options }) => {
// potential improvement may be change this component to a class so we don't recreate this function in all rendering?
const onChangeLocal = (event) => {
let newSelectionArray = [];
document.getElementsByName(name).forEach(item => {
if (item.checked) {
newSelectionArray.push(item.value);
}
});
// call generic callback with my fake an 'synthetic' event.
return onChange({
target: {
name,
value: newSelectionArray
}
})
}
return(
<div>
<label className="form-label">{label}</label>
<div className="checkbox-group">
{options.map(option => {
return (
<label key={option.value} className="form-label capitalize">
<input
className="form-checkbox"
name={name}
onChange={onChangeLocal}
value={option.value}
checked={selectedOptions.indexOf(option.value) > -1}
type='checkbox' /> {option.text}
</label>
);
})}
</div>
</div>
)
};
CheckBox.defaultProps = {
selectedOptions: []
}
CheckBox.propTypes = {
label: React.PropTypes.string.isRequired,
name: React.PropTypes.string.isRequired,
options: React.PropTypes.arrayOf(React.PropTypes.shape({
value: React.PropTypes.string.isRequired,
text: React.PropTypes.string.isRequired
})).isRequired,
selectedOptions: React.PropTypes.arrayOf(React.PropTypes.string),
onChange: React.PropTypes.func.isRequired
};
export default CheckBox;
|
Java
|
UTF-8
| 979
| 2.09375
| 2
|
[] |
no_license
|
package net.bible.service.format.osistohtml.tei;
import net.bible.service.format.osistohtml.HtmlTextWriter;
import net.bible.service.format.osistohtml.NoteHandler;
import net.bible.service.format.osistohtml.OsisToHtmlParameters;
import net.bible.service.format.osistohtml.ReferenceHandler;
import org.xml.sax.Attributes;
/**
* @author Martin Denham [mjdenham at gmail dot com]
* @see gnu.lgpl.License for license details.<br>
* The copyright to this program is held by it's author.
*/
public class RefHandler extends ReferenceHandler {
public RefHandler(OsisToHtmlParameters osisToHtmlParameters, NoteHandler noteHandler, HtmlTextWriter theWriter) {
super(osisToHtmlParameters, noteHandler, theWriter);
}
@Override
public String getTagName() {
return TEIUtil.TEI_ELEMENT_REF;
}
@Override
public void start(Attributes attrs) {
String target = attrs.getValue(TEIUtil.TEI_ATTR_TARGET);
start(target);
}
}
|
Java
|
UTF-8
| 2,038
| 2.21875
| 2
|
[
"Unlicense"
] |
permissive
|
package certyficate.sheetHandlers.insert;
import java.util.List;
import org.jopendocument.dom.spreadsheet.Sheet;
import certyficate.datalogger.Logger;
import certyficate.datalogger.PointData;
import certyficate.property.CalibrationData;
import certyficate.property.SheetData;
import certyficate.sheetHandlers.CalibrationPoint;
public class DataInsert {
private static final int MEASUREMENTS_POINTS = 10;
private int devicePosition;
private Sheet sheet;
private List<CalibrationPoint> points;
private boolean Rh;
private PointData[][] data;
public DataInsert(Sheet sheet) {
this.sheet = sheet;
Rh = SheetData.Rh;
}
public void setPoints(List<CalibrationPoint> points) {
this.points = points;
}
public void putLoggerData(Logger logger) {
setLoggerData(logger);
insertData();
}
private void setLoggerData(Logger logger) {
data = logger.getPointData();
devicePosition = logger.getDeviceNumber();
}
private void insertData() {
int length = data.length;
for(int i = 0; i < length; i++) {
checkPointData(i);
}
}
private void checkPointData(int index) {
if(data[index] != null) {
insetPointData(index);
}
}
private void insetPointData(int index) {
int line = setLine(index);
insetLine(data[index], line);
}
private void insetLine(PointData[] data, int line) {
int column = SheetData.timeColumn;
for(int i = 0; i < MEASUREMENTS_POINTS; i++) {
insertPoint(data[i], column, line);
column += 3;
}
}
private void insertPoint(PointData data, int column, int line) {
setPoint(data.getTemperature(), column, line);
if(Rh) {
setPoint(data.getHumidity(), column, line + 1);
}
}
private void setPoint(String[] array, int column, int line) {
sheet.setValueAt(array[0], column, line);
sheet.setValueAt(array[1], column + 2, line);
}
private int setLine(int index) {
int line = SheetData.startRow;
line += CalibrationData.numberOfParameters * devicePosition;
line += SheetData.pointGap * points.get(index).getPointNumber();
return line;
}
}
|
Python
|
UTF-8
| 445
| 2.671875
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
from collections.abc import Iterable
from typing import Any, overload
from typing_extensions import TypeGuard
class LazyFixture:
name: str
def __init__(self, name: str) -> None: ...
def __eq__(self, other: object) -> bool: ...
@overload
def lazy_fixture(names: str) -> LazyFixture: ...
@overload
def lazy_fixture(names: Iterable[str]) -> list[LazyFixture] | Any: ...
def is_lazy_fixture(val: object) -> TypeGuard[LazyFixture]: ...
|
C#
|
UTF-8
| 1,971
| 2.640625
| 3
|
[] |
no_license
|
using FunChat.GrainIntefaces;
using FunChat.UnitTest.Tools;
using Orleans.TestingHost;
using System;
using System.Threading.Tasks;
using Xunit;
namespace FunChat.UnitTest
{
[Collection(ClusterCollection.Name)]
public class LoginTest
{
private readonly TestCluster _cluster;
public LoginTest(ClusterFixture fixture)
{
_cluster = fixture.Cluster;
}
internal async Task Login(string username, string password, bool isvalid)
{
var user = _cluster.GrainFactory.GetGrain<IUser>(Guid.NewGuid());
Result<UserInfo> result = new Result<UserInfo>();
if (user != null)
result = await user.Login(username, password);
if (isvalid)
Assert.True(result.Success == true);
else
Assert.True(result.Success == false);
}
//I can login to FunChat using any(and only) alphanumeric characters as login name, the password is the same as the user’s login name.
//Login name characters must be 3 ~ 10 characters
[Fact]
public async Task LoginAlpha2CharsInvalid()
{
await Login("ab", "ab", false);
}
[Fact]
public async Task LoginAlpha3CharsValid()
{
await Login("abc", "abc", true);
}
[Fact]
public async Task LoginAlpha10CharsValid()
{
await Login("abcdefghij", "abcdefghij", true);
}
[Fact]
public async Task LoginAlpha11CharsInValid()
{
await Login("abcdefghijk", "abcdefghijk", false);
}
[Fact]
public async Task LoginUserPasswordDifferent()
{
await Login("username", "password", false);
}
[Fact]
public async Task LoginUserNotAlphanumeric()
{
await Login("user_name", "user_name", false);
}
}
}
|
Markdown
|
UTF-8
| 16,412
| 3.125
| 3
|
[] |
no_license
|
# 译|Using Go Modules
## Introduction
Go 1.11 和 1.12 初步包含了 [对模块的支持](https://golang.org/doc/go1.11#modules),Go 的 [新依赖管理系统](https://learnku.com/docs/go-blog/versioning-proposal) 使依赖版本信息明确且易于管理。本文介绍了开始使用模块所需要的基本操作。
模块是 [Go packages](https://golang.org/ref/spec#Packages) 的集合,以 `go.mod` 文件的形式存储在文件树的根目录。`go.mod` 定义了模块的 *模块路径* (根目录的导入路径)和 *依赖项需求* (成功构建所需要的其他模块)。每一个依赖项需求都以模块路径和特定 [语义版本](http://semver.org/) 的形式给出。
从 Go 1.11 开始,当前目录或者任何父目录包含 `go.mod` 文件时,Go 命令就可以使用模块,前提是该目录要在 `$GOPATH/src` *之外*。(在 `$GOPATH/src` 内的目录,出于兼容性考虑,Go 命令仍然以旧的 GOPATH 模式运行,即使存在 `go.mod` 文件。详细内容请参阅 [Go 命令文档](https://golang.org/cmd/go/#hdr-Preliminary_module_support) )。从 Go 1.13 开始,模块模式将是所有开发的默认模式。
本文介绍了使用模块进行 Go 开发的一系列常见操作:
- 创建新模块。
- 添加依赖。
- 升级依赖。
- 添加对新的主版本的依赖。
- 将依赖升级到新的主版本。
- 删除未使用的依赖。
## Creating a new module
让我们创建一个新模块。
在 `$GOPATH/src` 之外的某个地方创建一个新的空目录,在该目录中的 `cd` 内,然后创建一个新的源文件 `hello.go`:
```go
package hello
func Hello() string {
return "Hello, world."
}
```
让我们也在 `hello_test.go` 中编写一个测试:
```go
package hello
import "testing"
func TestHello(t *testing.T) {
want := "Hello, world."
if got := Hello(); got != want {
t.Errorf("Hello() = %q, want %q", got, want)
}
}
```
此时,该目录包含一个软件包,但不包含模块,因为没有 `go.mod` 文件。如果我们在 `/home/gopher/hello` 中工作并且现在运行 `go test`,我们会看到:
```bash
$ go test
PASS
ok _/home/gopher/hello 0.020s
$
```
后一行总结了整体包装测试。因为我们在`$GOPATH`之外以及任何模块之外工作,所以`go`命令不知道当前目录的导入路径,而是根据目录名称组成一个伪目录:` _/home/gopher/hello` 。
让我们使用 `go mod init` 将当前目录设为模块的根目录,然后再次尝试 `go test`:
```bash
$ go mod init example.com/hello
go: creating new go.mod: module example.com/hello
$ go test
PASS
ok example.com/hello 0.020s
$
```
恭喜你!您已经编写并测试了第一个模块。
`go mod init` 命令编写了一个 `go.mod` 文件:
```go
$ cat go.mod
module example.com/hello
go 1.12
$
```
`go.mod` 文件仅出现在模块的根目录中。子目录中的程序包具有由模块路径以及子目录路径组成的导入路径。例如,如果我们创建了一个子目录 `world`,则无需 (也不希望) 运行 `go mod init`。该软件包将自动被识别为 `example.com/hello` 模块的一部分,并带有导入路径 `example.com/hello/world`。
## Adding a dependency
Go 模块的首要目的是提高其他开发者使用代码(也就是添加依赖)的效率。
让我们更新下 `hello.go` 代码,导入 `rsc.io/quote` 包,使用这个包来实现 `Hello` :
```go
package hello
import "rsc.io/quote"
func Hello() string {
return quote.Hello()
}
```
现在我们再次运行这个测试代码:
```bash
$ go test
go: finding rsc.io/quote v1.5.2
go: downloading rsc.io/quote v1.5.2
go: extracting rsc.io/quote v1.5.2
go: finding rsc.io/sampler v1.3.0
go: finding golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c
go: downloading rsc.io/sampler v1.3.0
go: extracting rsc.io/sampler v1.3.0
go: downloading golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c
go: extracting golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c
PASS
ok example.com/hello 0.023s
$
```
`go` 命令通过使用 `go.mod` 中列出的指定模块版本来解析依赖。当遇到 `import` 了一个没有在 `go.mod` 中提供的模块中包含的包时,`go` 命令会自动搜索包含这个包的模块,并将其添加到 `go.mod` 中,并且使用这个包的最新版本(「最新」指的是包的最新的带标签的稳定版(非[预发布版](https://semver.org/#spec-item-9)),如果没有稳定版,这使用预发布版,如果都没有,再使用不打标签的最新版本)。在这个例子中,`go test` 命令将新添加的导入包 `rsc.io/quote` 解析为模块 `rsc.io/quote v1.5.2` 。同时,命令自动下载了 `rsc.io/quote` 使用的名为 `rsc.io/sampler` 和 `golang.org/x/text` 的两个依赖,但是,只有**源码直接依赖**的包会被记录到 `go.mod` 文件中,如下所示:
```go
$ cat go.mod
module example.com/hello
go 1.12
require rsc.io/quote v1.5.2
$
```
第二次运行 `go test` 命令,不会重复下载依赖这些工作,因为 `go.mod` 文件现在已经是最新,且下载的模块已经缓存在本地了(在目录 `$GOPATH/pkg/mod` 中),此命令运行输出如下所示:
```bash
$ go test
PASS
ok example.com/hello 0.020s
$
```
注意,虽然 `go` 命令添加新的依赖时,很快很方便,但它也有代价。例如,你的模块*真正地*在关键的地方,依赖新的库的正确性、安全性和许可证要求。更多需要考虑的地方,请参考 Russ Cox 的博客 「[Our Software Dependency Problem](https://research.swtch.com/deps)」。
如上所述,添加一个直接依赖,经常会引入其他间接依赖。命令 `go list -m all` 会列出当前模块的所有依赖,如下所示:
```go
$ go list -m all
example.com/hello
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c
rsc.io/quote v1.5.2
rsc.io/sampler v1.3.0
$
```
在 `go list` 命令的输出中,当前模块,也就是*主模块*,总是出现在第一行,后面按模块路径的顺序列出所有依赖。
`golang.org/x/text` 包的版本 `v0.0.0-20170915032832-14c0d48ead0c` 就是一个 [伪版本](https://golang.org/cmd/go/#hdr-Pseudo_versions) 的例子,这个版本号是 `go` 命令为不打标签的提交所定义的版本。
除了 `go.mod` 文件, `go` 命令也维护了一个名为 `go.sum` 的文件,文件内容为指定版本的模块内容的 [加密哈希值](https://golang.org/cmd/go/#hdr-Module_downloading_and_verification) ,如下所示:
```bash
$ cat go.sum
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c h1:qgOY6WgZO...
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:Nq...
rsc.io/quote v1.5.2 h1:w5fcysjrx7yqtD/aO+QwRjYZOKnaM9Uh2b40tElTs3...
rsc.io/quote v1.5.2/go.mod h1:LzX7hefJvL54yjefDEDHNONDjII0t9xZLPX...
rsc.io/sampler v1.3.0 h1:7uVkIFmeBqHfdjD+gZwtXXI+RODJ2Wc4O7MPEh/Q...
rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9...
$
```
`go` 命令通过 `go.sum` 文件来保证未来下载模块依赖时,依然使用的相同的内容,保证你的项目依赖的模块不会遇到恶意代码、随机异常等原因导致的异常变化。`go.mod` 和 `go.sum` 两个文件,应该都需要被版本控制系统管理起来。
## Upgrading dependencies
通过使用 Go 模块,模块版本通过语义化的标签来引用。带有语义性质的版本包含三个部分:主版本号,次版本号和补丁版本号。例如,版本 `v0.1.2` 的主版本号为 0 ,次版本号为 1 ,补丁版本号为 2 。我们先略过次版本号的更新,下一章节介绍组版本号的更新。
在 `go list -m all` 命令的输出中,我们可以看到使用了 `golang.org/x/text` 的无标签版本。我们可以将其更新为最新的带标签版本,并且测试下我们的代码还可以继续正常工作,如下所示:
```bash
$ go get golang.org/x/text
go: finding golang.org/x/text v0.3.0
go: downloading golang.org/x/text v0.3.0
go: extracting golang.org/x/text v0.3.0
$ go test
PASS
ok example.com/hello 0.013s
$
```
哇哦!一切正常。我们再来看看 `go list -m all` 命令的输出和 `go.mod` 文件的内容:
```go
$ go list -m all
example.com/hello
golang.org/x/text v0.3.0
rsc.io/quote v1.5.2
rsc.io/sampler v1.3.0
$ cat go.mod
module example.com/hello
go 1.12
require (
golang.org/x/text v0.3.0 // indirect
rsc.io/quote v1.5.2
)
$
```
`golang.org/x/text` 包已经被升级到了最新的带标签版本(`v0.3.0`)。`go.mod` 文件也自动更新为指定的 `v0.3.0` 版本。`go.mod` 文件也自动更新为指定的 `v0.3.0` 版本。注释 `indirect` 说明这个包不是当前模块的直接依赖,而是其他模块的间接依赖。更多细节可以参考 `go help modules` 命令的输出。
现在,我们可以试着更新 `rsc.io/sampler` 的次版本号。同样的,我们通过 `go get` 命令更新依赖,并且运行测试,其输出如下所示:
```bash
$ go get rsc.io/sampler
go: finding rsc.io/sampler v1.99.99
go: downloading rsc.io/sampler v1.99.99
go: extracting rsc.io/sampler v1.99.99
$ go test
--- FAIL: TestHello (0.00s)
hello_test.go:8: Hello() = "99 bottles of beer on the wall, 99 bottles of beer, ...", want "Hello, world."
FAIL
exit status 1
FAIL example.com/hello 0.014s
$
```
啊哦!测试失败了,说明 `rsc.io/sampler` 的最新版本不兼容我们的使用方式。让我们看看这个模块可以使用的所有版本号,具体操作如下所示:
```bash
$ go list -m -versions rsc.io/sampler
rsc.io/sampler v1.0.0 v1.2.0 v1.2.1 v1.3.0 v1.3.1 v1.99.99
$
```
我们已经使用了 v1.3.0 版本,而 v1.99.99 明显是不可用的,让我们试试 v1.3.1 版本吧:
```go
$ go get rsc.io/sampler@v1.3.1
go: finding rsc.io/sampler v1.3.1
go: downloading rsc.io/sampler v1.3.1
go: extracting rsc.io/sampler v1.3.1
$ go test
PASS
ok example.com/hello 0.022s
$
```
注意 `go get` 命令中,显式指定了版本号 `@v1.3.1`。通常,`go get` 命令的参数需要使用显式指定版本,默认为 `@latest`,对应就是前面所述的「最新」版本。
## Adding a dependency on a new major version
让我们在包中添加一个新的函数: `func Proverb` 通过调用 `quote.Concurrency` 返回 Go 并发谚语,这是由模块 `rsc.io/quote/v3` 提供的。首先我们修改 `hello.go` 文件来添加新函数:
```go
package hello
import (
"rsc.io/quote"
quoteV3 "rsc.io/quote/v3"
)
func Hello() string {
return quote.Hello()
}
func Proverb() string {
return quoteV3.Concurrency()
}
```
然后我们添加测试文件 `hello_test.go`:
```go
func TestProverb(t *testing.T) {
want := "Concurrency is not parallelism."
if got := Proverb(); got != want {
t.Errorf("Proverb() = %q, want %q", got, want)
}
}
```
然后测试我们的代码:
```bash
$ go test
go: finding rsc.io/quote/v3 v3.1.0
go: downloading rsc.io/quote/v3 v3.1.0
go: extracting rsc.io/quote/v3 v3.1.0
PASS
ok example.com/hello 0.024s
$
```
注意我们的模块现在同时依赖 `rsc.io/quote` 和 `rsc.io/quote/v3`:
```bash
$ go list -m rsc.io/q...
rsc.io/quote v1.5.2
rsc.io/quote/v3 v3.1.0
$
```
Go 模块的每个不同的主版本 (`v1`, `v2` 等) 使用不同的模块路径:从 `v2` 开始,该路径必须是主版本号。在示例中,`rsc.io/quote` 的 `v3` 不再是 `rsc.io/quote`: 而是由模块路径 `rsc.io/quote/v3` 标识并代替。此约定称为 [语义导入版本控制](https://research.swtch.com/vgo-import) , 它为不兼容的软件包 (具有不同主版本的软件包) 提供了不同的名称。相反,`rsc.io/quote` 的 `v1.6.0` 应该与 `v1.5.2` 向后兼容,因此它重用了模块名称 `rsc.io/quote`。(在上一节中,`rsc.io/sampler` `v1.99.99` *应该* 与 `rsc.io/sampler` `v1.3.0` 向后兼容,但是关于模块行为的错误或错误的客户端假设都可能发生。)
`go` 命令允许构建最多包含任何特定模块路径的一个版本,即每个主版本有且仅有一个:一个 `rsc.io/quote`,一个 `rsc.io/quote/v2`,一个 `rsc.io/quote/v3`,依此类推。这为模块作者提供了关于单个模块路径可能重复的明确规则:程序无法同时使用 `rsc.io/quote v1.5.2` 和 `rsc.io/quote v1.6.0`。同时,允许模块的不同主要版本 (因为它们具有不同的路径) 使模块使用者可以逐步升级到新的主版本。在此示例中,我们想使用 `rsc/quote/v3 v3.1.0` 中的 `quote.Concurrency`,但我们尚未准备好对 `rsc.io/quote v1.5.2` 的升级迁移。在大型程序或代码库中,增量迁移的能力尤为重要。
## Upgrading a dependency to a new major version
让我们完成从使用 `rsc.io/quote` 到仅使用 `rsc.io/quote/v3` 的转换。由于版本的重大更改,我们应该懂得某些 APIs 可能已不兼容的方式被删除了,重命名了,或是其他方式被改变。查看文档后,我们会看到 `Hello` 变成了 `HelloV3`:
```bash
$ go doc rsc.io/quote/v3
package quote // import "rsc.io/quote"
Package quote collects pithy sayings.
func Concurrency() string
func GlassV3() string
func GoV3() string
func HelloV3() string
func OptV3() string
$
```
(输出中还存在一个[已知错误](https://golang.org/issue/30778);显示导入路径被错误地删除了 `/v3`。)
我们可以修改 `hello.go` 文件中使用的 `quote.Hello()` 来使用 `quoteV3.HelloV3()`:
```go
package hello
import quoteV3 "rsc.io/quote/v3"
func Hello() string {
return quoteV3.HelloV3()
}
func Proverb() string {
return quoteV3.Concurrency()
}
```
就这点而言,不需要任何重命名的导入,所以我们应该撤消该操作:
```go
package hello
import "rsc.io/quote/v3"
func Hello() string {
return quote.HelloV3()
}
func Proverb() string {
return quote.Concurrency()
}
```
让我们重新运行测试测试来确保代码一如既往地正常:
```bash
$ go test
PASS
ok example.com/hello 0.014s
```
## Removing unused dependencies
我们已经删除了 `rsc.io/quote` 的所有使用,但它仍然显示在 `go list -m all` 和我们的 `go.mod` 文件中:
```go
$ go list -m all
example.com/hello
golang.org/x/text v0.3.0
rsc.io/quote v1.5.2
rsc.io/quote/v3 v3.1.0
rsc.io/sampler v1.3.1
$ cat go.mod
module example.com/hello
go 1.12
require (
golang.org/x/text v0.3.0 // indirect
rsc.io/quote v1.5.2
rsc.io/quote/v3 v3.0.0
rsc.io/sampler v1.3.1 // indirect
)
$
```
为什么?因为像 `go build` 或 `go test` 一样,构建一个包可以很容易地判断什么时候缺少了什么,什么时候需要添加什么,而不是什么时候可以安全地删除什么。只有在检查模块中的所有包以及这些包的所有可能的生成标记组合之后,才能删除依赖项。普通的生成命令不会加载此信息,因此无法安全地删除依赖项。
用 `go mod tidy` 命令来清除这些未使用的依赖:
```bash
$ go mod tidy
$ go list -m all
example.com/hello
golang.org/x/text v0.3.0
rsc.io/quote/v3 v3.1.0
rsc.io/sampler v1.3.1
$ cat go.mod
module example.com/hello
go 1.12
require (
golang.org/x/text v0.3.0 // indirect
rsc.io/quote/v3 v3.1.0
rsc.io/sampler v1.3.1 // indirect
)
$ go test
PASS
ok example.com/hello 0.020s
$
```
## Conclusion
Go 模块是 Go 中依赖管理的未来。模块功能现在在所有支持的 Go 版本 (这里的所有是指,Go 1.11 和 Go 1.12) 中都可用。
下面介绍了这些使用 Go 模块的工作流:
- `go mod init` 创建一个新模块,会初始化一个 `go.mod` 并有其描述。
- `go build`, `go test`, 以及其他包生成命令根据需要向 `go.mod` 添加新的依赖项。
- `go list -m all` 打印当前模块的依赖。
- `go get` 更改依赖项的所需版本 (或添加一个新的依赖项)。
- `go mod tidy` 移除未使用的依赖。
我们鼓励你在本地开发中开始使用模块,并将 `go.mod` 和 `go.sum` 文件添加到你的项目中。为了提供反馈并帮助塑造 Go 中依赖关系管理的未来,请向我们发送 [错误报告](https://golang.org/issue/new) 或 [体验报告](https://golang.org/wiki/ExperienceReports)。
感谢您对改进模块的所有反馈和帮助。
|
Java
|
UTF-8
| 29,920
| 1.726563
| 2
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
/*
* ArchE
* Copyright (c) 2012 Carnegie Mellon University.
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following acknowledgments and disclaimers.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. All advertising materials for third-party software mentioning features or
* use of this software must display the following disclaimer:
*
* “Neither Carnegie Mellon University nor its Software Engineering Institute
* have reviewed or endorsed this software”
*
* 4. The names “Carnegie Mellon University,” and/or “Software Engineering
* Institute" shall not be used to endorse or promote products derived from
* this software without prior written permission. For written permission,
* please contact permission@sei.cmu.edu.
*
* 5. Redistributions of any form whatsoever must retain the following
* acknowledgment:
*
* Copyright 2012 Carnegie Mellon University.
*
* This material is based upon work funded and supported by the United States
* Department of Defense under Contract No. FA8721-05-C-0003 with Carnegie
* Mellon University for the operation of the Software Engineering Institute, a
* federally funded research and development center.
*
* NO WARRANTY
*
* THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING INSTITUTE MATERIAL
* IS FURNISHED ON AN “AS-IS” BASIS. CARNEGIE MELLON UNIVERSITY MAKES NO
* WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, AS TO ANY MATTER
* INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR PURPOSE OR
* MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE MATERIAL.
* CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND WITH
* RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT.
*/
package edu.cmu.sei.arche.external.execution;
/**
* A base class for executing a RF command, sent by RFInteractionAgent, on the current reasoning framework.
* This is an implementation for RFCommandListener interface that is separated from the implementation of
* an external reasoning framework. In this way, we can hide all the details for the execution of a RF command
* from a reasoning framework developer.
*
* [TODO: Need to rewrite the following paragraph]
* To deal with the ArchE DB, we follows the pattern "transaction per request"
* If a request on the execution of a RF command arrives, the execution must start
* with opening a DB transaction, and then, ends with either 'commit' or 'rollback'
* to complete the transaction.
*
* @author Hyunwoo Kim
*/
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;
import edu.cmu.sei.arche.ArchEException;
import edu.cmu.sei.arche.external.communication.RFAnalyze;
import edu.cmu.sei.arche.external.communication.RFAnalyzeAndSuggest;
import edu.cmu.sei.arche.external.communication.RFApplySuggestedTactic;
import edu.cmu.sei.arche.external.communication.RFApplyTactics;
import edu.cmu.sei.arche.external.communication.RFCommand;
import edu.cmu.sei.arche.external.communication.RFCommandListener;
import edu.cmu.sei.arche.external.communication.RFDescribeTactic;
import edu.cmu.sei.arche.external.data.ArchEArchitecture;
import edu.cmu.sei.arche.external.data.ArchEDataProvider;
import edu.cmu.sei.arche.external.data.ArchEObject;
import edu.cmu.sei.arche.external.data.ArchERequirementModel;
import edu.cmu.sei.arche.external.data.ArchEScenario;
import edu.cmu.sei.arche.external.data.ArchEVersion;
import edu.cmu.sei.arche.external.reasoningframework.ArchEAnalysisResult;
import edu.cmu.sei.arche.external.reasoningframework.ArchEEvaluationResult;
import edu.cmu.sei.arche.external.reasoningframework.ArchEReasoningFramework;
import edu.cmu.sei.arche.external.reasoningframework.ArchETryTacticResult;
import edu.cmu.sei.arche.external.reasoningframework.ArchEUserQuestion;
public class ReasoningFrameworkExecutor implements RFCommandListener{
private static final int NO_CHECK_RF_DEPENDENCIES = 0;
private static final int CHECK_RF_DEPENDENCIES = 1;
private static final int NO_INIT_VIEW = 0;
private static final int INIT_VIEW = 1;
private static boolean isArchitectureChanged;
/* Target reasoning framework instance for this class */
private ArchEReasoningFramework reasoningFramework = null;
private boolean isLearning; // Flag for learning mode (optional feature)
public ReasoningFrameworkExecutor(ArchEReasoningFramework rf){
// Set the current reasoning framework
reasoningFramework = rf;
isLearning = false;
}
//////////////////////////////////////////////////////////////
// Implementation of RFCommandListener
/**
* This is a command for requesting a specific reasoning framework to apply a
* tactic to the current architecture in order to refine it.
* The tactic must come from a user question that was given to
* the user of ArchE and the user agreed to apply.
* The expected result is to have the refined version of the current
* architecture in the database.
*
* @param command The command instance to be executed
*/
public void applyTactics(RFApplyTactics command) {
try {
isArchitectureChanged = false;
// Get a version info. with the architecture name from DB
ArchEVersion currentVersion = reasoningFramework.getDataProvider()
.getVersion(command.getArchitectureName());
// The version must already exist in DB.
if(currentVersion == null){
throw new ArchEException("Warning: " + command.getArchitectureName() + " does not exist in DB.");
}
// Get current requirement model from DB
ArchERequirementModel requirementModel = reasoningFramework.getDataProvider()
.restoreRequirementModel(currentVersion);
// Get current architecture from DB
ArchEArchitecture architecture = getArchitecture(
currentVersion,requirementModel,INIT_VIEW,NO_CHECK_RF_DEPENDENCIES);
if(IsCanceled(command))
return;
// Get a list of AskQuestion (UserQuestion)
List<ArchEUserQuestion> userQuestions = new ArrayList<ArchEUserQuestion> ();
List<RawArchEUserQuestion> rawUserQuestions = command.getListOfAskQuestion();
for(Iterator<RawArchEUserQuestion> it=rawUserQuestions.iterator(); it.hasNext();){
RawArchEUserQuestion rawUserQuestion = it.next();
ArchEUserQuestion userQuestion =
reasoningFramework.restoreUserQuestion(rawUserQuestion.getID());
synchronizeUserQuestion(rawUserQuestion,userQuestion);
userQuestions.add(userQuestion);
}
boolean applied = false;
// For each UserQuestion, apply a corresponding tactic
// The current architecture will be refined by applying tactic(s).
for(int i=0; i<userQuestions.size(); i++){
applied |= reasoningFramework.applyTacticByUserQuestion(architecture, userQuestions.get(i));
if(IsCanceled(command))
return;
}
// If applied, save the refined architecture to DB
if(applied == true || isArchitectureChanged){
reasoningFramework.getDataProvider().saveArchitecture(architecture);
}
} catch (ArchEException e) {
e.printStackTrace();
}
}
/**
* This is a command for requesting a reasoning framework to analyze the current architecture
* for scenarios of interest and to suggest new tactics if some scenarios are not fulfilled.
* The reasoning framework has to return the analysis results and the tactics,
* if suggested, to ArchE. Also, it might update the current architecture in the ArchE
* database by checking the responsibility structure consistency and by initializing
* its view based on the responsibility structure.
*
* @param command The command instance to be executed
*/
public List<ArchEAnalysisResult> analyzeAndSuggest(RFAnalyzeAndSuggest command,
/* out */ List<RawArchETryTacticResult> outRawTactics) {
ArrayList<ArchEAnalysisResult> resultList = new ArrayList<ArchEAnalysisResult>();
try {
isArchitectureChanged = false;
// Get a version info. with the architecture name from DB
ArchEVersion currentVersion = reasoningFramework.getDataProvider()
.getVersion(command.getArchitectureName());
if(IsCanceled(command))
return resultList;
// The version must already exist in DB.
if(currentVersion == null){
throw new ArchEException("Warning: " + command.getArchitectureName() + " does not exist in DB.");
}
// Get current interesting requirement model from DB
ArchERequirementModel requirementModel = reasoningFramework.getDataProvider()
.restoreRequirementModel(currentVersion);
if(IsCanceled(command))
return resultList;
// Get current architecture from DB
ArchEArchitecture architecture = getArchitecture(
currentVersion,requirementModel,INIT_VIEW,CHECK_RF_DEPENDENCIES);
if(IsCanceled(command))
return resultList;
if(!isLearning){
reasoningFramework.beginLearning();
isLearning = true;
}
// Get scenarios related to the current reasoning framework
reasoningFramework.clearRepositoryForSuggestedTactics();
ArrayList<ArchETryTacticResult> outTactics = new ArrayList<ArchETryTacticResult>();
for(Iterator<ArchEScenario> it = requirementModel
.getScenariosByReasoningFramework(reasoningFramework).iterator(); it.hasNext();) {
ArchEScenario scenario = (ArchEScenario)(it.next());
ArchEAnalysisResult result =
reasoningFramework.analyzeAndSuggest(architecture, scenario, outTactics);
resultList.add(result);
if(IsCanceled(command))
return resultList;
}
// Note that tactics proposals with the same name and parameters are eliminated from the list
outTactics = filterDuplicateTacticEntries(outTactics);
// Update the analysis values, so that they are available for the next round
reasoningFramework.clearRepositoryForAnalysisResults();
ArchEAnalysisResult resultItem = null;
for (Iterator<ArchEAnalysisResult> newResults = resultList.iterator(); newResults.hasNext();) {
resultItem = newResults.next();
reasoningFramework.saveAnalysisResult(resultItem.getOwner(), resultItem);
}
ArchETryTacticResult tactic = null;
for (Iterator<ArchETryTacticResult> itTactics = outTactics.iterator(); itTactics.hasNext();) {
tactic = (ArchETryTacticResult)(itTactics.next());
RawArchETryTacticResult rawTacticResult = transformToRawTryTacticResult(tactic);
reasoningFramework.saveSuggestedTactic(rawTacticResult.getTacticID(), tactic);
outRawTactics.add(rawTacticResult);
}
if(IsCanceled(command))
return resultList;
// If changed, save the refined architecture to DB
if(isArchitectureChanged == true){
reasoningFramework.getDataProvider().saveArchitecture(architecture);
}
} catch (ArchEException e) {
e.printStackTrace();
}
return (resultList);
}
private static ArrayList<ArchETryTacticResult> filterDuplicateTacticEntries(
ArrayList<ArchETryTacticResult> modifTactics) {
// This comparator is defined below as an internal class
Comparator<ArchETryTacticResult> tryTacticComparator = new TryTacticResultComparator();
TreeSet<ArchETryTacticResult> filtered = new TreeSet<ArchETryTacticResult>(tryTacticComparator);
for (Iterator<ArchETryTacticResult> it = modifTactics.iterator(); it.hasNext();)
filtered.add(it.next());
modifTactics = new ArrayList<ArchETryTacticResult>();
for (Iterator<ArchETryTacticResult> it = filtered.iterator(); it.hasNext();)
modifTactics.add(it.next());
return (modifTactics);
}
private static ArrayList<ArchEUserQuestion> filterDuplicateQuestionEntries(
ArrayList<ArchEUserQuestion> warnings) {
// This comparator is defined below as an internal class
Comparator<ArchEUserQuestion> userQuestionComparator = new ArchEUserQuestionComparator();
TreeSet<ArchEUserQuestion> filtered = new TreeSet<ArchEUserQuestion>(userQuestionComparator);
for (Iterator<ArchEUserQuestion> it = warnings.iterator(); it.hasNext();)
filtered.add(it.next());
warnings = new ArrayList<ArchEUserQuestion>();
for (Iterator<ArchEUserQuestion> it = filtered.iterator(); it.hasNext();)
warnings.add(it.next());
return (warnings);
}
static class TryTacticResultComparator implements Comparator<ArchETryTacticResult> {
public TryTacticResultComparator() {
}
public int compare(ArchETryTacticResult o1, ArchETryTacticResult o2) {
int result = 1;
if (o1.getTacticName().equals(o2.getTacticName())) {
List at1 = o1.getAt();
List at2 = o2.getAt();
if (at1.size() > at2.size())
result = 1;
else if (at1.size() < at2.size())
result = -1;
else { // They have the same number of parameters
boolean allEquals = true;
for(int i = 0; (i < at1.size()) && allEquals; i++) {
if (!at1.get(i).equals(at2.get(i)))
allEquals = false;
}
if (allEquals)
result = 0;
}
}
else
result = (o1.getTacticName().compareTo(o2.getTacticName()));
return (result);
}
}
static class ArchEUserQuestionComparator implements Comparator<ArchEUserQuestion> {
public ArchEUserQuestionComparator() {
}
public int compare(ArchEUserQuestion o1, ArchEUserQuestion o2) {
int result = 1;
if (o1.getQuestionID().equals(o2.getQuestionID())) {
List parameters1 = o1.getParameters();
List parameters2 = o2.getParameters();
if (parameters1.size() > parameters2.size())
result = 1;
else if (parameters1.size() < parameters2.size())
result = -1;
else { // They have the same number of parameters
boolean allEquals = true;
for(int i = 0; (i < parameters1.size()) && allEquals; i++) {
if (!parameters1.get(i).equals(parameters2.get(i)))
allEquals = false;
}
if (allEquals)
result = 0;
}
}
else
result = (o1.getQuestionID().compareTo(o2.getQuestionID()));
return (result);
}
}
/**
* This is a command for requesting a reasoning framework to apply a tactic to the current
* architecture in order to create a new candidate architecture. The tactic must be one
* of the tactics that the reasoning framework suggested as a result of executing
* the AnalyzeAndSuggest command. The expected result is to have a candidate architecture
* in the database.
*
* @param command The command instance to be executed
*/
public void applySuggestedTactic(RFApplySuggestedTactic command) {
try {
// Get a version info. with the architecture name from DB
ArchEVersion currentVersion = reasoningFramework.getDataProvider()
.getVersion(command.getArchitectureName());
if(IsCanceled(command))
return;
// The version must already exist in DB.
if(currentVersion == null){
throw new ArchEException("Warning: " + command.getArchitectureName() + " does not exist in DB.");
}
// Get current requirement model from DB
ArchERequirementModel requirementModel = reasoningFramework.getDataProvider()
.restoreRequirementModel(currentVersion);
if(IsCanceled(command))
return;
// Get current architecture from DB
ArchEArchitecture architecture = getArchitecture(
currentVersion,requirementModel,INIT_VIEW,NO_CHECK_RF_DEPENDENCIES);
if(IsCanceled(command))
return;
// Get a suggested tactic to apply from the repository for suggested tactics
ArchETryTacticResult suggestedTactic = reasoningFramework.restoreSuggestedTactic(
command.getApplySuggestedTactic().getTacticID());
// Apply the suggested tactic, which in turn modify the architecture
boolean applied = reasoningFramework.applySuggestedTactic(architecture, suggestedTactic);
if(IsCanceled(command))
return;
// If applied, save the refined architecture to DB
if(applied == true){
// Get a version info. with the candidate name from DB
ArchEVersion candidateVersion = reasoningFramework.getDataProvider()
.getVersion(command.getCandidateName());
// If the candidate version exists, delete it.
if(candidateVersion != null){
// Delete the existing candidate architecture from DB
reasoningFramework.getDataProvider().deleteArchitecture(candidateVersion);
}
// Create a new version with the candidate name.
ArchEVersion newCandidateVersion = reasoningFramework.getDataProvider()
.newChildVersion(currentVersion, command.getCandidateName());
// Save the requirement model as a new version
reasoningFramework.getDataProvider()
.saveRequirementModelAs(requirementModel,newCandidateVersion);
// Save the architecture as a new version
reasoningFramework.getDataProvider()
.saveArchitectureAs(architecture,newCandidateVersion);
}
} catch (ArchEException e) {
e.printStackTrace();
}
}
/**
* This is a command for requesting a reasoning framework to analyze a candidate
* architecture for scenarios of interest. The reasoning framework has to return
* the evaluation results that ArchE will use to prioritize candidate architectures.
*
* @param command The command instance to be executed
*/
public List<ArchEEvaluationResult> analyze(RFAnalyze command) {
ArrayList<ArchEEvaluationResult> evaluationResultList = new ArrayList<ArchEEvaluationResult>();
try {
// Get a version info. with the architecture name from DB
ArchEVersion candidateVersion = reasoningFramework.getDataProvider()
.getVersion(command.getCandidateName());
if(IsCanceled(command))
return evaluationResultList;
// The version must already exist in DB.
if(candidateVersion == null){
throw new ArchEException("Warning: " + command.getCandidateName() + " does not exist in DB.");
}
// Get current requirement model from DB
ArchERequirementModel requirementModel = reasoningFramework.getDataProvider()
.restoreRequirementModel(candidateVersion);
if(IsCanceled(command))
return evaluationResultList;
// Get current architecture from DB
ArchEArchitecture architecture = getArchitecture(
candidateVersion,requirementModel,INIT_VIEW,CHECK_RF_DEPENDENCIES);
if(IsCanceled(command))
return evaluationResultList;
if(!isLearning){
reasoningFramework.beginLearning();
isLearning = true;
}
for(Iterator<ArchEScenario> it = requirementModel
.getScenariosByReasoningFramework(reasoningFramework).iterator(); it.hasNext();) {
ArchEScenario scenario = (ArchEScenario)(it.next());
ArchEEvaluationResult result =
reasoningFramework.analyze(architecture, scenario);
evaluationResultList.add(result);
if(IsCanceled(command))
return evaluationResultList;
}
} catch (ArchEException e) {
e.printStackTrace();
}
return (evaluationResultList);
}
/**
* This is a command for requesting a reasoning framework to provide ArchE with
* user-friendly questions that describe tactics or any other recommendations.
*
* @param command The command to be executed
*/
public List<RawArchEUserQuestion> describeTactics(RFDescribeTactic command) {
List<RawArchEUserQuestion> rawUserQuestions = new ArrayList<RawArchEUserQuestion>();
// Get a list of DescribeTacticToUser
List<ArchEDescribeTacticToUser> listOfDescribeTacticToUser = command.getListOfDescribeTacticToUser();
try {
// Get a version info. with the architecture name from DB
ArchEVersion currentVersion = reasoningFramework.getDataProvider()
.getVersion(command.getArchitectureName());
if(IsCanceled(command))
return rawUserQuestions;
// The version must already exist in DB.
if(currentVersion == null){
throw new ArchEException("Warning: " + command.getArchitectureName() + " does not exist in DB.");
}
// Get current requirement model from DB
ArchERequirementModel requirementModel = reasoningFramework.getDataProvider()
.restoreRequirementModel(currentVersion);
if(IsCanceled(command))
return rawUserQuestions;
// Get current architecture from DB
ArchEArchitecture architecture = getArchitecture(
currentVersion,requirementModel,NO_INIT_VIEW,NO_CHECK_RF_DEPENDENCIES);
if(IsCanceled(command))
return rawUserQuestions;
reasoningFramework.clearRepositoryForUserQuestions();
// For any tactic to describe, execute describetTactic to get a relevant user question
for(Iterator<ArchEDescribeTacticToUser> it = listOfDescribeTacticToUser.iterator(); it.hasNext();){
ArchEDescribeTacticToUser describeTacticToUser = it.next();
ArchETryTacticResult tactic = reasoningFramework.restoreSuggestedTactic(
describeTacticToUser.getTacticID());
ArchEUserQuestion userQuestion =
reasoningFramework.describeTactic(tactic);
userQuestion.setQuestionGroup(describeTacticToUser.getQuestionGroupID());
userQuestion.setReasoningFramework(reasoningFramework.getID());
userQuestion.setPriority(describeTacticToUser.getRelevance());
userQuestion.setSearchStep(describeTacticToUser.getSearchStep());
RawArchEUserQuestion rawUserQuestion = transformToRawUserQuestion(userQuestion);
if(rawUserQuestion != null){
reasoningFramework.saveUserQuestion(rawUserQuestion.getID(), userQuestion);
rawUserQuestions.add(rawUserQuestion);
}
if(IsCanceled(command))
return rawUserQuestions;
}
// Get other user questions that are not related to tactics
List<ArchEUserQuestion> otherQuestions =
reasoningFramework.describeOtherThanTactic(requirementModel,architecture);
if(otherQuestions != null){
// Note that questions with the same name and parameters are eliminated from the list
otherQuestions = filterDuplicateQuestionEntries((ArrayList<ArchEUserQuestion>)otherQuestions);
for(Iterator<ArchEUserQuestion> it = otherQuestions.iterator(); it.hasNext();){
ArchEUserQuestion userQuestion = it.next();
userQuestion.setQuestionGroup("others");
userQuestion.setReasoningFramework(reasoningFramework.getID());
userQuestion.setPriority(0);
userQuestion.setSearchStep(0);
RawArchEUserQuestion rawUserQuestion = transformToRawUserQuestion(userQuestion);
if(rawUserQuestion != null){
reasoningFramework.saveUserQuestion(rawUserQuestion.getID(), userQuestion);
rawUserQuestions.add(rawUserQuestion);
}
}
}
// Get questions related to "learning"
List<ArchEUserQuestion> learnQuestions =
reasoningFramework.describeWhatLearned();
if(learnQuestions != null){
for(Iterator<ArchEUserQuestion> it = learnQuestions.iterator(); it.hasNext();){
ArchEUserQuestion userQuestion = it.next();
userQuestion.setQuestionGroup("learning");
userQuestion.setReasoningFramework(reasoningFramework.getID());
userQuestion.setPriority(0);
userQuestion.setSearchStep(0);
RawArchEUserQuestion rawUserQuestion = transformToRawUserQuestion(userQuestion);
if(rawUserQuestion != null){
reasoningFramework.saveUserQuestion(rawUserQuestion.getID(), userQuestion);
rawUserQuestions.add(rawUserQuestion);
}
}
}
reasoningFramework.clearAnalysisStatus();
reasoningFramework.clearResponsibilityStructureStatus();
} catch (ArchEException e) {
e.printStackTrace();
}
return rawUserQuestions;
}
//////////////////////////////////////////////////////////////
// local methods
private ArchEArchitecture getArchitecture(ArchEVersion version,ArchERequirementModel requirementModel, int initView, int checkRFDependencies) throws ArchEException{
// This code should rely on the dataProvider to get the architecture from the database
// If the design structure doesn�t exist within the architecture, it should be created
ArchEDataProvider dataProvider = reasoningFramework.getDataProvider();
ArchEArchitecture architecture = dataProvider.restoreArchitecture(version);
// If architecture already exists,
if(architecture != null){
if(needsToCheckRFDependencies(checkRFDependencies)){
// Check RF dependencies
isArchitectureChanged |= reasoningFramework.checkRFDependencies(requirementModel, architecture.getResponsibilityStructure());
}
if(needsToInitializeView(initView) && architecture.getView() != null){
// Initialize a view of the architecture based on its responsibility structure
// if the view exists
isArchitectureChanged |= reasoningFramework.initializeView(architecture.getView(),architecture.getResponsibilityStructure(),requirementModel);
}
}
else
throw new ArchEException("Failed to get an architecture in DB: its name is " + version.getVersionName());
return (architecture);
}
///////////////////////////////////////////////////////////////////////
// Local utility methods
/*
* To check whether to need to check RF dependencies or not
*/
private boolean needsToCheckRFDependencies(int checkRFDependencies) {
if(checkRFDependencies == CHECK_RF_DEPENDENCIES)
return true;
else
return false;
}
/*
* To check whether to need to initialize a view or not
*/
private boolean needsToInitializeView(int initView) {
if(initView == INIT_VIEW)
return true;
else
return false;
}
/*
* To check whether this command is canceled by the ArchE or not
*/
private boolean IsCanceled(RFCommand command) {
return (command.getRFInteractionAgent().isCanceled());
}
private RawArchETryTacticResult transformToRawTryTacticResult(ArchETryTacticResult tryTacticResult){
RawArchETryTacticResult rawTryTacticResult = new RawArchETryTacticResult();
rawTryTacticResult.setTacticID("t" + tryTacticResult.hashCode());
rawTryTacticResult.setReasoningFramework(tryTacticResult.getReasoningFramework());
rawTryTacticResult.setScenario(tryTacticResult.getScenario().getFactId());
rawTryTacticResult.setTacticName(tryTacticResult.getTacticName());
rawTryTacticResult.setTacticDescription(tryTacticResult.getTacticDescription());
return rawTryTacticResult;
}
private RawArchEUserQuestion transformToRawUserQuestion(ArchEUserQuestion userQuestion){
if(userQuestion == null)
return null;
RawArchEUserQuestion rawUserQuestion = new RawArchEUserQuestion();
rawUserQuestion.setID("q" + userQuestion.hashCode());
rawUserQuestion.setQuestionID(userQuestion.getQuestionID());
rawUserQuestion.setReasoningFramework(userQuestion.getReasoningFramework());
rawUserQuestion.setQuestionGroup(userQuestion.getQuestionGroup());
rawUserQuestion.setPriority(userQuestion.getPriority());
rawUserQuestion.setSearchStep(userQuestion.getSearchStep());
ArchEObject parent = userQuestion.getParent();
if(parent != null)
rawUserQuestion.setParent(parent.getFactId());
if(userQuestion.getAffectedFacts() != null)
rawUserQuestion.setAffectedFacts(
transformToStringList(userQuestion.getAffectedFacts().iterator()));
if(userQuestion.getParameters() != null)
rawUserQuestion.setParameters(
transformToStringList(userQuestion.getParameters().iterator()));
if(userQuestion.getDefaults() != null)
rawUserQuestion.setDefaults(
transformToStringList(userQuestion.getDefaults().iterator()));
if(userQuestion.getOptions() != null)
rawUserQuestion.setOptions(
transformToStringList(userQuestion.getOptions().iterator()));
return rawUserQuestion;
}
private List<String> transformToStringList(Iterator iter){
List<String> stringList = new ArrayList<String>();
while(iter.hasNext()){
Object item = iter.next();
if(item instanceof ArchEObject)
stringList.add(((ArchEObject)item).getFactId());
else if(item instanceof String)
stringList.add((String)item);
else if(item instanceof Double)
stringList.add(((Double)item).toString());
else if(item instanceof Integer)
stringList.add(((Integer)item).toString());
}
return stringList;
}
private void synchronizeUserQuestion(RawArchEUserQuestion newUserQuestion, ArchEUserQuestion oldUserQuestion){
// synchronize parent if applicable
if(oldUserQuestion.getParent() != null){
String newID = newUserQuestion.getParent();
String oldID = oldUserQuestion.getParent().getFactId();
if(newID != null && oldID != null && !newID.equals(oldID))
oldUserQuestion.getParent().setFactId(newID);
}
// synchronize list parameters
synchronize(newUserQuestion.getAffectedFacts(), oldUserQuestion.getAffectedFacts());
synchronize(newUserQuestion.getParameters(), oldUserQuestion.getParameters());
synchronize(newUserQuestion.getOptions(), oldUserQuestion.getOptions());
synchronize(newUserQuestion.getDefaults(), oldUserQuestion.getDefaults());
// get answers
oldUserQuestion.setAnswers(newUserQuestion.getAnswers());
}
private void synchronize(List<String> newList, List oldList){
if(newList == null || oldList == null)
return;
Iterator<String> itNew=newList.iterator() ;
Iterator itOld = oldList.iterator();
while(itOld.hasNext()){
Object itemOld = itOld.next();
String newID = itNew.next();
if(itemOld != null && itemOld instanceof ArchEObject){
String oldID = ((ArchEObject)itemOld).getFactId();
if(newID != null && !newID.equals(oldID))
((ArchEObject)itemOld).setFactId(newID);
}
}
}
}
|
C
|
UTF-8
| 799
| 3.25
| 3
|
[] |
no_license
|
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
int *a,n,i,key,c=0,low,high,mid;
//clrscr();
printf("Enter numbers you want to add in array");
scanf("%d",&n);
a=(int *)malloc(sizeof(int) * n);
printf("\n enter %d elements in array",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n Enter element you want to search");
scanf("%d",&key);
printf("\n applying binary search .....");
low=0;
high=n;
while(low<=high)
{
mid=(low + high )/2;
if(key==a[mid])
{
c=1;
printf("\n Element is at position %d",mid);
break;
}
else if(key<a[mid])
{
high = mid - 1;
}
else if(key>a[mid])
{
low = mid + 1;
}
}
if(c==0){
printf("\n element not found");
}
}
|
C
|
UTF-8
| 1,818
| 3.09375
| 3
|
[] |
no_license
|
/*
* hw2harness.h
*
* I WILL OVERWRITE YOUR COPY OF THIS FILE WITH MY OWN. ANY CHANGES YOU MAKE WILL NOT BE VISIBLE DURING GRADING.
*/
#ifndef HW2HARNESS_H
#define HW2HARNESS_H
/*
PROBLEM NOTES:
The problem that these functions generate/verify is a linear gradient with 0 on the left side and 1 on the right side. The returned b
follows this gradient.
Note that this problem doesn't converge very quickly, and in fact you may need to change your upper iteration limit in your CG solver.
Instead of limiting to sqrt(n), try 5*sqrt(n).
For larger problems you may also run into accuracy limits. If you want to verify correctly on large problems (k > 400 or so), then reduce
the norm of the residual requirement by an order of magnitude or two (add two '0' after the decimal point).
I will actually check your residual during grading, but this problem is nice because it has a nice closed form solution.
*/
/*
Returns a single element of vector b. You may call this on any node you wish, in whatever order.
You should call this function n times.
arguments:
index - the index of the element you want. Zero based (note that Matlab is 1 based). In other words, the first element has index 0, the second index 1, etc.
int_k - k
returns:
b[index]
*/
double cs240_getB(int index, int int_n);
/*
Verifies the correctness of the CG computed on the model problem with b as returned by cs240_getB().
cs240_verify() should be called once at the end of the program.
arguments:
x - the entire vector x. If this doesn't exist on one processor because of your data layout, then you have to assemble it on one processor.
k - k
elapsedTime - The difference in time as given by MPI_Wtime() (on processor 0) between the start of CG calculation and the end.
*/
int cs240_verify(double* x, int k, double elapsedTime);
#endif
|
Java
|
UTF-8
| 1,212
| 2.65625
| 3
|
[] |
no_license
|
package com.common.bean;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* 定义全局BaseController类使用推荐的 SLF4j 作日志处理
* 其他 Controller 并继承实现*/
public class BaseController {
protected final Logger loger = LoggerFactory.getLogger(getClass());
//trace級別日志
protected void trace(String msg){
loger.trace(msg);
}
//debug級別日志
protected void debug(String msg){
loger.debug(msg);
}
//info級別日志
protected void info(String msg){
loger.info(msg);
}
//warn級別日志
protected void warn(String msg){
loger.warn(msg);
}
//error級別日志
protected void error(String msg){
loger.error(msg);
}
public static ResultData quickReturn(boolean ok){
if(ok ) {
return ResultData.success();
}else {
return ResultData.fail();
}
}
public static ResultData quickReturn(int row){
return quickReturn(row > 0);
}
public static ResultData quickReturn(List list){
if( list != null && list.size() >0 ) {
return ResultData.success().setData(list);
}else {
return ResultData.fail().setData(list);
}
}
}
|
C++
|
UTF-8
| 3,505
| 3.078125
| 3
|
[] |
no_license
|
#include "BinQueue.h"
Readers::BinaryQueue::BinaryQueue ()
{
}
void Readers::BinaryQueue::pushBuffer (ByteBuffer& data)
{
locker.lock ();
container.insert (container.end (), data.begin (), data.end ());
//for (ByteBuffer::iterator ref = data.begin (); ref != data.end (); ++ ref)
// container.push_back (*ref);
locker.unlock ();
}
void Readers::BinaryQueue::pushBuffer (const byte *data, const size_t size)
{
char *begin = (char *) data,
*end = begin + size;
locker.lock ();
container.insert (container.end (), begin, end);
//for (size_t i = 0; i < size; ++ i)
// container.push_back (data [i]);
locker.unlock ();
}
size_t Readers::BinaryQueue::pull (byte *buffer, const size_t size, const bool needLock)
{
size_t actualSize = container.size () >= size ? size : container.size ();
if (needLock)
locker.lock ();
memset (buffer, 0, size);
for (size_t i = 0; i < actualSize; ++ i)
{
buffer [i] = container.front ();
container.pop_front ();
}
if (needLock)
locker.unlock ();
return actualSize;
}
size_t Readers::BinaryQueue::pull (char *buffer, const size_t bufSize, const char *finishAfterChars, const char *finishBeforeChars, const bool ignoreUnfinished)
{
size_t actualSize = container.size () >= bufSize ? bufSize : container.size (),
queueSize = container.size (),
start,
count;
bool finishFound,
noCharsPassed;
locker.lock ();
if (container.empty())
{
locker.unlock (); return 0;
}
//memset (buffer, 0, bufSize);
for (finishFound = false, count = start = 0, noCharsPassed = true; !finishFound && count < queueSize && (count - start) < bufSize; ++ count)
{
char curChar;
try
{
curChar = (char) container.at (count);
}
catch (std::out_of_range)
{
curChar = '\0';
}
if (curChar)
{
if (strchr (finishAfterChars, curChar) != 0)
{
if (noCharsPassed)
{
++ start;
}
else
{
finishFound = true;
// Skip all "concluding" chars (like \n after \r)
for (size_t index = count + 1; index < container.size () && strchr (finishAfterChars, container [index]) != 0; ++ index)
count = index;
}
}
else if (strchr (finishBeforeChars, curChar) != 0)
{
if (noCharsPassed)
{
noCharsPassed = false;
}
else
{
-- count;
finishFound = true;
}
}
else
{
noCharsPassed = false;
}
}
}
if (count > 0)
{
size_t lastElement = count - start;
if (lastElement < bufSize)
buffer [lastElement] = '\0';
for (size_t i = 0, j = 0; i < count; ++i)
{
if (start == 0)
buffer [j++] = (char) container.at (i);
else
-- start;
//container.pop_front ();
}
container.erase (container.begin (), container.begin () + (count - 1));
}
locker.unlock ();
return count;
}
|
Python
|
UTF-8
| 532
| 3.0625
| 3
|
[] |
no_license
|
from .column import Column
class Table:
def __init__(self, path='/tmp'):
self.columnlist = {}
# self.row_keys = set()
self.path = path
def put(self, col, key, value):
if col not in self.columnlist:
newcol = Column(col, self.path)
self.columnlist[col] = newcol
self.columnlist[col].add(key, value)
def get(self, col, key):
if col in self.columnlist:
return self.columnlist[col].get(key)
else:
return None
|
Python
|
UTF-8
| 2,384
| 3.359375
| 3
|
[] |
no_license
|
import matplotlib.pyplot as pyplot
products = {4: [], 7: [], 29: []}
alphas = [1, 1.5, 2, 5]
def get_file_name(ALPHA, attack_type="", attack_length=0):
fn = "output/"
if attack_length > 0:
fn += attack_type + "_" + str(attack_length) + "_"
return fn +"Alpha_" + str(ALPHA) + "_Products.txt"
def get_product_data(fn, product_ids, avg=False):
product_data = {}
with open(fn) as data:
for line in data:
vals = line.split(" ");
product_id = int(vals[0])
if(product_id in product_ids):
if avg:
product_data[product_id] = float(vals[2].replace("(", "").replace(")", ""))
else:
product_data[product_id] = float(vals[1])
return product_data
avgs = []
for ALPHA in alphas:
fn = get_file_name(ALPHA);
if ALPHA == alphas[0]:
#IF this is the FIRST alpha value
#first get AVERAGE value
avgs = get_product_data(fn, products, True)
read_data = get_product_data(fn, products)
for product in read_data:
products[product].append(read_data[product])
for (key, ratings) in products.items():
#pyplot.axhline(y=avgs[key], color='r', linestyle='-')
#pyplot.bar(alphas, ratings)
print(key)
data = ratings + [avgs[key]]
pyplot.bar(range(len(data)), data, align='center')
xticks = map(lambda x: "$\\alpha$ = " + str(x), alphas)
pyplot.xticks(range(len(data) + 1), (xticks + ["Mean"]))
#pyplot.xlabel("$\\alpha$ Value")
pyplot.ylabel("Product Rating")
pyplot.ylim(ymin=1)
pyplot.show()
def plot_attack(attack_type, product_id, loc="upper right"):
alpha_attack = {}
for ALPHA in alphas:
alpha_attack[ALPHA] = []
avg_attack = []
attack_lengths = [0, 5, 10, 15, 20, 25]
for attack in attack_lengths:
fn = get_file_name(1, attack_type, attack)
avg_attack.append(get_product_data(fn, [product_id], True)[product_id])
for ALPHA in alphas:
fn = get_file_name(ALPHA, attack_type, attack)
products = get_product_data(fn, [product_id])
alpha_attack[ALPHA].append(products[product_id])
#pyplot.title("Effect of " + attack_type + " Attacks (varying sizes)")
legend = ["Arithmetic Mean"]
pyplot.plot(attack_lengths, avg_attack)
for ALPHA in alphas:
legend.append(r'$\alpha$ = ' + str(ALPHA))
pyplot.plot(attack_lengths, alpha_attack[ALPHA])
pyplot.legend(legend, loc=loc)
pyplot.xlabel("Attack Size")
pyplot.ylabel("Product Rating")
pyplot.show()
plot_attack("Promote", 4, "lower right")
plot_attack("Slander", 29)
|
C++
|
UTF-8
| 3,322
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
#include "saveMatlabMat.h"
/* template <typename T>
bool SaveMatlabMat(T *src, string savePath, string matrixName, int cols, int rows)
{
// tanspose befoee being saved
int datasize = cols * rows;
double *Final = new double[datasize]; //convert to double precision
memset(Final, 0, datasize * sizeof(double));
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
Final[j * rows + i] = double(src[i * cols + j]);
}
}
mxArray *pWriteArray = NULL; //matlab mat form
MATFile *pmatFile = NULL; //.mat file
pmatFile = matOpen(savePath.c_str(), "u");
if (pmatFile == nullptr)
pmatFile = matOpen(savePath.c_str(), "w");
if (pmatFile == nullptr)
{
printf("mat save path is error");
return false;
}
pWriteArray = mxCreateDoubleMatrix(rows, cols, mxREAL);
memcpy((void *)(mxGetPr(pWriteArray)), (void *)Final, sizeof(double) * datasize);
matPutVariable(pmatFile, matrixName.c_str(), pWriteArray);
matClose(pmatFile); //close file
mxDestroyArray(pWriteArray); //release resource
delete[] Final; //release resource
Final = nullptr;
return true;
} */
bool savemat(MatrixXd var, std::string file_name, std::string var_name)
{
size_t dims[2];
dims[0] = var.rows();
dims[1] = var.cols();
mat_t *mat;
mat = Mat_CreateVer(file_name.c_str(), NULL, MAT_FT_DEFAULT);
if (!mat)
{
return false;
}
matvar_t *matvar;
matvar = Mat_VarCreate(var_name.c_str(), MAT_C_DOUBLE, MAT_T_DOUBLE, 2, dims, var.data(), 0);
Mat_VarWrite(mat, matvar, MAT_COMPRESSION_NONE);
Mat_VarFree(matvar);
Mat_Close(mat);
return true;
}
bool saveVec(VectorXf var, std::string file_name, std::string var_name)
{
size_t dims[2];
dims[0] = var.rows();
dims[1] = 1;
mat_t *mat;
mat = Mat_Open(file_name.c_str(), MAT_ACC_RDWR);
// if (!mat)
// {
// mat = Mat_CreateVer(file_name.c_str(), NULL, MAT_FT_DEFAULT);
// if (!mat)
// return false;
// }
mat = Mat_CreateVer(file_name.c_str(), NULL, MAT_FT_DEFAULT);
if (!mat)
return false;
matvar_t *matvar;
matvar = Mat_VarCreate(var_name.c_str(), MAT_C_SINGLE, MAT_T_SINGLE, 2, dims, var.data(), 0);
Mat_VarWrite(mat, matvar, MAT_COMPRESSION_NONE);
Mat_VarFree(matvar);
Mat_Close(mat);
return true;
}
bool readMatFromFile(const char *file, Eigen::MatrixXd &mat, const char *name)
{
mat_t *matfp;
matvar_t *matvar;
matfp = Mat_Open(file, MAT_ACC_RDONLY);
if (NULL == matfp)
{
fprintf(stderr, "Error opening MAT file %s\n", file);
return false;
}
matvar = Mat_VarRead(matfp, name);
if (matvar->rank != 2 || matvar->class_type != MAT_C_DOUBLE)
{
return false;
}
// printf("mat size: %ld, %ld\n", matvar->dims[0], matvar->dims[1]);
mat.resize(matvar->dims[0], matvar->dims[1]);
std::memcpy(mat.data(), (double *)matvar->data, sizeof(double) * mat.size());
/* for (int c = 0; c < matvar->dims[1]; c++)
{
for (int r = 0; r < matvar->dims[0]; r++)
{
mat(r, c) = ((double *)matvar->data)[r * matvar->dims[1] + c];
}
} */
Mat_Close(matfp);
return true;
}
|
Shell
|
UTF-8
| 502
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
#!/bin/bash
#
# Description : Install and optimize database instance
# Author : Jose Cerrejon Gonzalez (ulysess@gmail_dot._com)
# Version : 0.3 (14/May/14)
#
#
clear
# MySQL
echo -e "Installing MySQL+PHP5 conn..."
sudo apt-get install -y mysql-server php5-mysql mysql-client
echo -e "Optimizing..."
sudo mv /etc/mysql/my.cnf /etc/mysql/my.cnf.bak
sudo cp /usr/share/doc/mysql-server-5.5/examples/my-small.cnf /etc/mysql/my.cnf
# query_cache_size = 8M
sudo service mysql restart
read -p "Done!. Press [Enter] to continue..."
|
Ruby
|
UTF-8
| 1,661
| 2.921875
| 3
|
[] |
no_license
|
require 'net/ldap'
module Auth
# The DN class is responsible for constructing a DN given a key piece of
# information, i.e. an email address or a login alias. Conversely, when
# given a valid DN, it should parse and make available useful information
# from the DN.
class DN
def dn() raise NotImplementedError end
def mail() raise NotImplementedError end
def o() raise NotImplementedError end
def initialize(data) raise NotImplementedError end
# In charge of determining if a particular entry has rights as a phonebook
# admin. A phonebook admin can generally edit the entries of others.
def phonebook_admin?() raise NotImplementedError end
end
def self.ldap_connection() Net::LDAP.new(SETTINGS['ldap']) end
def self.ldap_connection_as_user
ldap = self.ldap_connection
ldap.auth(DN.new(PhonebookApp.username).dn, PhonebookApp.password)
ldap
end
# Actually checks credentials using the LDAP server.
def self.authorized?(username, password)
return false if not username or not password
ldap = self.ldap_connection
ldap.auth(DN.new(username).dn, password)
ldap.bind # bind returns a boolean
end
end
class PhonebookApp
class LDAPAuth < Rack::Auth::Basic
def realm() 'LDAP - Valid User Required' end
end
def self.username() @@username end
def self.password() @@password end
use LDAPAuth do |username, password|
# Class variables are used because this block's scope is tied to the
# PhonebookApp class but routes are tied to instances of the class.
@@username, @@password = username, password
Auth.authorized?(username, password)
end
end
|
C
|
UTF-8
| 947
| 2.96875
| 3
|
[
"MIT"
] |
permissive
|
#ifndef __LIST__
#define __LIST__
#include "heap.c"
#define typedef_TypedList(Type) \
typedef struct { \
Heap *heap; \
Type *items; \
ULong count; \
} Type##List; \
\
Boolean addTo##Type##List(Type##List *list, Type value) { \
if (!growList(list->heap, (Any**)&list->items, &list->count, sizeof(Type))) { \
return false; \
} \
list->items[list->count++] = value; \
return true; \
} \
\
Type##List create##Type##List(Heap *heap) { \
return (Type##List) { \
heap, \
.items = NULL, \
.count = 0, \
}; \
}
#define destroyList(list) \
deallocFromHeap(list.heap, list.items)
Boolean growList(Heap *heap, Any **items, ULong *count, ULong itemSize) {
Any *realloc = reallocFromHeap(heap, *items, *count * itemSize + itemSize);
if (realloc == NULL) {
return false;
}
*items = realloc;
return true;
}
typedef_TypedList(Byte);
typedef_TypedList(ULong);
#endif
|
Python
|
UTF-8
| 2,151
| 2.765625
| 3
|
[] |
no_license
|
import os
import re
import random
def strQ2B(ustring):
ss = []
for s in ustring:
rstring = ""
for uchar in s:
inside_code = ord(uchar)
if inside_code == 12288:
inside_code = 32
elif (inside_code >= 65281 and inside_code <= 65374):
inside_code -= 65248
rstring += chr(inside_code)
ss.append(rstring)
return ''.join(ss)
def HPchar2int(char_dict)->dict:
'''
In HPchar2int_v2, adding a token to represent as new line
'''
char2int = {}
with open(char_dict,'r',encoding = 'utf-8') as f:
for i,line in enumerate(f.readlines()):
char2int[line.rstrip()] = i + 1
char2int['[UNK]'] = len(char2int)
char2int['[PAD]'] = 0
char2int['[CLS]'] = len(char2int)
char2int['[NL]'] = len(char2int)
return char2int
def load_corpus(data_root,char_dict):
char2int = HPchar2int(char_dict)
sents = []
data_list = os.listdir(data_root)
temp = []
for file in data_list:
path = os.path.join(data_root,file)
s = 0
with open(path,'r',encoding = 'utf-8') as f:
for line in f.readlines():
if s == 0:
s += 1
continue
line = line.rstrip()
line = re.sub(' ','',line)
line = strQ2B(line)
sents.append(line)
results = []
temp = []
while len(sents)>0:
sent = sents[0]
if len(sent) > 500:
temp = [list(map(char2int.get,x))+[char2int['[NL]']] for x in temp]
temp = sum(temp,[])
results.append(temp)
temp = []
sent = list(map(char2int.get,sent)) + [char2int['[NL]']]
results.append(sent)
sents = sents[1:]
temp_len = len(''.join(temp)) + (len(temp)) if temp else 0
if (temp_len + len(sent)) < 500:
temp.append(sent)
rand_number = random.random()
if rand_number > 0.6:
temp = [list(map(char2int.get,x))+[char2int['[NL]']] for x in temp]
temp = sum(temp,[])
results.append(temp)
temp = []
sents = sents[1:]
else:
temp = [list(map(char2int.get,x))+[char2int['[NL]']] for x in temp]
temp = sum(temp,[])
results.append(temp)
temp = []
return results
|
Markdown
|
UTF-8
| 4,270
| 3.0625
| 3
|
[
"MIT"
] |
permissive
|
# Assignment 2 (Group)
Explore 2 dataset that given then finding descriptive statistics and summary result in form of sentences/paragraph at least 5 topics.
### Answer
1.) หาค่าเฉลี่ย,min,max ของอายุใน survey table
```{R}
library(MASS)
min(survey$Age)
max(survey$Age)
mean(survey$Age)
```
Descriptive statistics Statement
```{R}
เรียกใช้ library ของ MASS
หา Min ของ Survey โดยการเขียน min(survey$Age)
หา Max ของ Survey โดยการเขียน max(survey$Age)
หา Mean ของ Survey โดยการเรียน mean(survey$Age)
survey$Age เพื่อบอกว่าเราใช้ข้อมูลชุดไหนอยู่และตามด้วย $ เพื่อเรียก Colum ที่เราจะหา
```
2.) จงหาว่าค่าเฉลี่ยของความกว้างของมือด้านใดที่กว้างกว่ากัน ระหว่าง writing hand กับ non-writing hand
```{R}
library(MASS)
mean(survey$Wr.Hnd,na.rm = TRUE)#18.66907
mean(survey$NW.Hnd,na.rm = TRUE)#18.58263
#wr.hand > nw.hand
```
Descriptive statistics Statement
```{R}
ใช้คำสั่ง mean ในการหาค่าเฉลี่ยของ wr.hand และ nw.hand แล้วนำมาลบกัน
ป.ล ใช้ na.rm = true เพื่อเอาค่า NA ออกไปจากการคิดเลข
```
3.) หา column ที่2 row ที่3 ของ survey table
```{R}
library(MASS)
survey[2,4] #[1] Left,Levels: Left Right
```
Descriptive statistics Statement
```{R}
ใช้คำสั่ง ชื่อตาราง[column,row] เพื่อเลือกตำแหน่งของข้อมูลที่เราต้องการได้
```
4.) หาความถี่ survey ของเพศแต่ละเพศ
```{R}
summary(factor(survey$Sex))
```
Descriptive statistics Statement
```{R}
เรียกใช้คำสั่ง summary ให้หาค่าความถีโดยใช้คำ factor ส่วนของ เพศโดยเลือกใช้คำสั่ง factor
เนื่องจากข้อมูลของเพศเป็นข้อมูลเลือกคุณภาพจึงเหมาะกับการใช้ factor
```
5.) จงหาว่าค่าเฉลี่ยของน้ำหนักหัวใจของแมวเพศใดมีค่ามากกว่ากัน
```{R}
View(cats)
table(cats[1:47,1])
table(cats[48:144,1])
mean(cats[1:47,3]) #เพศเมีย 9.202128
mean(cats[48:144,3]) #เพศผู้ 11.32268
#ค่าเฉลี่ยน้ำหนักหัวใจเพศผู้มากกว่าเพศเมีย
```
Descriptive statistics Statement
```{R}
จากโจทย์จะทำการเรียกดูตาราง cats ก่อนเพื่ออ่านการเรียงลำดับเพศของแมว
และสังเกตได้ว่าตารางจะเรียงให้เพศเมียขึ้้นก่อนเพศผู้
โดยเพศเมียจะอยู่ 47 ลำดับแรก และเพศผู้จะอยู่ลำดับที่ 48-144
และทำการตรวจให้แน่ใจอีกครั้งด้วยคำสั่ง table พบว่าเป็นจริง
จากนั้นจึงใช้คำสั่ง mean หาค่าตามตำแหน่ง
```
### Team: บะหมี่ต้องใส่ชาม
1. ชื่อ จักริน นามสกุล ไชยบุบผา StudentID: 63130500009
2. ชื่อ ชนันพร นามสกุล ผ่องศรี StudentID: 63130500014
3. ชื่อ ชานนท์ นามสกุล รักดี StudentID: 63130500020
4. ชื่อ นราวิชญ์ นามสกุล คำภูษา StudentID: 63130500065
|
Markdown
|
UTF-8
| 595
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
# get-port-cli
> Get an available port
## Install
```sh
npm install --global get-port-cli
```
## Usage
```
$ get-port --help
Usage
$ get-port <preferred-ports>…
Options
--host, -h The host on which port resolution should be performed. Can be either an IPv4 or IPv6 address.
Examples
$ get-port
51402
$ get-port 91929192 2324 732842342
2324
$ get-port 80
9090
$ get-port --host=127.0.0.1
55740
$ get-port 3000 3002 --host=127.0.0.1
3002
```
## Related
- [get-port](https://github.com/sindresorhus/get-port) - API for this module
|
Java
|
UTF-8
| 1,106
| 1.65625
| 2
|
[] |
no_license
|
package com.aoscia.base.api;
import com.aoscia.base.dto.FireLedgerDto;
import com.aosica.common.bean.RequestResult;
import com.aosica.common.bean.RequestResultPage;
import com.github.pagehelper.Page;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@RequestMapping("fireLedger")
public interface FireLedgerServiceApi {
@RequestMapping(value = "selectList", method = RequestMethod.POST)
RequestResultPage<Page<FireLedgerDto>> selectList(@RequestBody FireLedgerDto dto);
@RequestMapping(value = "saveAndUpdate", method = RequestMethod.POST)
RequestResult saveAndUpdate(@RequestBody FireLedgerDto dto);
@RequestMapping(value = "/selectDetailById", method = RequestMethod.GET)
RequestResult selectDetailById(@RequestParam(value = "id") String id);
@RequestMapping(value = "/remove", method = RequestMethod.GET)
RequestResult remove(@RequestParam(value = "id") String id);
}
|
Java
|
UTF-8
| 1,477
| 3.140625
| 3
|
[] |
no_license
|
package pl.sda.collection.service;
import pl.sda.collection.model.Book;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class BookService {
private List<Book> collections;
public BookService() {
this.collections = new ArrayList<>();
}
public void addNewBook(Book book) {
this.collections.add(book);
}
public List<Book> getAllBooks() {
return this.collections;
}
public Book findBookByTitleAndAuthor(String title, String author) {
for (Book book : this.collections) {
if (book.getTitle().equals(title) && book.getAuthor().equals(author)) {
return book;
}
}
return null;
}
public Boolean removeBook(Book book) {
return this.collections.remove(book);
}
//to nie ma prawa zadziałać na liście
// public void removeBookByTitle(String title) {
// this.collections.listIterator()
// for (Book booktmp: this.collections)
// if (title.equals(booktmp.getTitle())){
// this.collections.remove(booktmp);
// }
// }
public void removeBookByTitle(String title) {
Iterator<Book> iteratorTmp = this.collections.iterator();
while (iteratorTmp.hasNext()) {
if (iteratorTmp.next().getTitle().equals(title)) {
iteratorTmp.remove();
}
}
}
}
|
C++
|
UTF-8
| 2,107
| 3.640625
| 4
|
[] |
no_license
|
//#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
double AverageScore(double Total, int NumScores);
void selectionSort(double array[], int size);
void showArray(double array[], int size);
int main()
{
double *scores, // To dynamically allocate an array of scores
total = 0.0; // Accumulator
int numScores, // Number of Test Scores
count; // Counter variable
cout << "How many Test scores do you want ";
cout << "to average? ";
cin >> numScores;
scores = new double[numScores];
cout << "Enter your Test scores.\n";
for (count = 0; count < numScores; count++)
{
cout << "Test " << (count + 1) << ": ";
cin >> scores[count];
}
for (count = 0; count < numScores; count++)
{
total += scores[count];
}
cout << "You entered the following scores: \n";
showArray(scores,numScores);
selectionSort(scores,numScores);
cout << "The following scores will be averaged: \n";
showArray(scores,numScores);
cout << fixed << showpoint << setprecision(2);
cout << "Your average test score is: " << AverageScore(total,numScores) << endl;
delete [] scores; //Release the momory
scores = 0; // Make scores point to null.
system("PAUSE");
return 0;
}
double AverageScore(double Total, int NumScores)
{
return Total / NumScores;
}
void selectionSort(double array[], int size)
{
int startScan, minIndex, minValue;
for (startScan = 0; startScan < (size - 1); startScan++)
{
minIndex = startScan;
minValue = array[startScan];
for(int index = startScan + 1; index < size; index++)
{
if (array[index] < minValue)
{
minValue = array[index];
minIndex = index;
}
}
array[minIndex] = array[startScan];
array[startScan] = minValue;
}
}
void showArray(double array[], int size)
{
for (int count = 0; count < size; count++)
cout << array[count] << " ";
cout << endl;
}
|
Python
|
UTF-8
| 4,591
| 3.171875
| 3
|
[
"MIT"
] |
permissive
|
import numpy as np
class Perceptron(object):
'''
Implements a simple Perceptron network using sequential training
'''
def __init__(self, input_size, class_size, eta):
'''
Args:
eta (int): learning rate
input_size (int): length of input, assumes shape = (input_size, )
class_size (int): number of classes
'''
self.input_dim = input_size
self.class_dim = class_size
self.weights = np.random.uniform(low=-0.5, high=0.5, size=(input_size + 1, class_size))
self.confusion_matrix = np.zeros((class_size, class_size))
self.accuracy = 0
self.eta = eta
self.bias = 1
#tolerance of 0.001 %
self.tolerance = 0.00001
def _add_bias(self, input_data):
'''
Inserts self.bias column along inputs at x0
Returns:
np.array: Biased input_data, i.e. [[x1,x2,...,xn], ... ] => [[1,x1,x2,...,xn], ...]
'''
return np.concatenate((self.bias * np.ones((input_data.shape[0], 1)), input_data), axis=1)
def predict(self, data):
'''
Args:
data (np.array): shape(N, input_dim)
Returns:
np.array: perceptron output vector for data, shape(1, class_dim)
'''
return np.dot(data, self.weights)
def run_training(self, dataset, epochs):
'''TODO: set up algorithm for data collection
Wrapper that runs the training regime specified by the project
Args:
dataset (dict): Contains the necessary training/test data and labels
i.e. {'train_data': (np.array), 'train_label': (np.array), ... }
epochs (int): number of times to update the weight matrix according to sequential PLA
Returns:
dict: data describing the performance of the perceptron
'''
#for scoping issues w/ return :(
train_confusion_matrix, test_confusion_matrix = None, None
epoch_accuracy = dict()
#initial accuracy check with anthony?
for epoch in range(epochs):
train_confusion_matrix = self.train(dataset['train_data'], dataset['train_labels'])
test_confusion_matrix = self.test(dataset['test_data'], dataset['test_labels'])
epoch_accuracy[epoch] = {
'train': np.trace(train_confusion_matrix) / np.sum(train_confusion_matrix),
'test': np.trace(test_confusion_matrix) / np.sum(test_confusion_matrix)
}
if epoch > 1 and epoch_accuracy[epoch]['test'] < epoch_accuracy[epoch - 1]['test'] + self.tolerance:
break
return {
'accuracy' : epoch_accuracy,
'confusion_matrix': test_confusion_matrix.tolist()
}
def train(self, input_data, input_labels):
'''
Runs training regime according to sequential update PLA for one epoch
Args:
data (np.array): shape (N, input_dim)
labels (np.array): shape (N, class_dim)
Returns:
dict: dictionary of the accuracy for each epoch, i.e. { epoch_num: %accuracy, ... }
np.array: confusion matrix for the training set of shape (class_dim, class_dim)
'''
input_data = self._add_bias(input_data)
confusion_matrix = np.zeros((self.class_dim, self.class_dim))
for n in range(input_data.shape[0]):
_input, _target = input_data[n].reshape(1, self.input_dim+1), input_labels[n].reshape(1, self.class_dim)
_output = self.predict(_input)
_prediction, _label = np.argmax(_output), np.argmax(_target)
confusion_matrix[_prediction][_label] += 1
if _prediction != _label:
_activations = np.where(_output > 0, 1, 0)
self.weights -= self.eta*np.dot(_input.T, _activations - _target)
return confusion_matrix
def test(self, test_data, test_labels):
'''
Returns:
(np.array): a confusion matrix for the test data of shape(class_dim, class_dim)
'''
test_data = self._add_bias(test_data)
confusion_matrix = np.zeros((self.class_dim, self.class_dim))
for n in range(test_data.shape[0]):
_input, _target = test_data[n].reshape(1, self.input_dim+1), test_labels[n].reshape(1, self.class_dim)
_output = self.predict(_input)
_prediction, _label = np.argmax(_output), np.argmax(_target)
confusion_matrix[_prediction][_label] += 1
return confusion_matrix
|
Markdown
|
UTF-8
| 680
| 2.59375
| 3
|
[] |
no_license
|
# Java-Org-Managers
[](https://travis-ci.org/HauptJ/Java-Org-Managers)
A simple Java program that calculates a fictitious departments allocation based on the number of managers, developers and qa staff.
This was written to meet the requirements of [ECS's](https://ecstech.com/) coding challenge.
### Dependencies
- A supported JDK
- oraclejdk8
- oraclejdk9
- oraclejdk11
- openjdk8
- openjdk10
- openjdk11
- Apache Ant (Recommended)
### Instructions
- **compile the program:** ```ant compile```
- **build the jar file:** ```ant jar```
- **run the program:** ```ant run```
|
Java
|
UTF-8
| 1,289
| 2.140625
| 2
|
[] |
no_license
|
package com.wxq.developtools;
import com.wxq.commonlibrary.base.BaseView;
import com.wxq.commonlibrary.base.RxPresenter;
/**
* Created by wxq on 2018/6/28.
*
* //p成拿到view成數據
*/
public class MvpMainPresent extends RxPresenter<MvpMainContract.View> implements MvpMainContract.Presenter {
public MvpMainPresent(MvpMainContract.View view) {
super(view);
}
@Override
public void getData(int count) {
mView.showToast(count*3+"wawawawaa");
mView.showRx();
}
@Override
public void initEventAndData() {
// 、、倒计时
// CountDownTimer countDownTimer=new CountDownTimer(10*1000, 2000) {
// @Override
// public void onTick(long l) {
//
//
// }
//
// @Override
// public void onFinish() {
//
// }
// };
// countDownTimer.start();
// CountDownTimerUtils.countDown(10, 1, new CountDownTimerUtils.CountDownListener() {
// @Override
// public void countDownfinish() {
// mView.showToast("倒计时结束");
// }
//
// @Override
// public void currentProcess(int time) {
// mView.showToast(time+"");
// }
// });
}
}
|
C++
|
UTF-8
| 1,284
| 3.671875
| 4
|
[] |
no_license
|
/*
LeetCode: longest valid parentheses
https://leetcode.com/problems/longest-valid-parentheses/
*/
// WA: wrong understanding
// a well-formed parenthese pair doesn't mean we must
// have continous '(' and ')'
// meaning they are not interruptted
class Solution {
public:
int longestValidParentheses(string s) {
vector<int> dp(s.length()+1, 0);
int res = 0;
for(int i=2; i<=s.length(); i++) {
dp[i] = res;
if(s[i-1] == ')' && s[i-2] == '(') {
dp[i] = max(dp[i], dp[i-2]+2);
res = max(dp[i], res);
}
}
return dp[s.length()];
}
};
// WA: wrong understanding again
// longest means substring, not subsequence
// this solution is cute though
int longestValidParentheses(string s) {
int len = s.length();
vector<int> dp(len+1, 0);
int left = 0;
int right = 0;
for(int i=1; i<=len; i++) {
dp[i] = dp[i-1];
if(s[i-1] == '(') {
left++;
}
// right pathese
else if(left > right) {
right++;
dp[i] += 2;
}
}
return dp[len];
}
|
Java
|
UTF-8
| 2,051
| 3.71875
| 4
|
[] |
no_license
|
import java.util.*;
class findMax{
public static class Node{
int data = 0;
Node left = null;
Node right = null;
Node(int data){
this.data = data;
}
}
public static Node constructBST(ArrayList<Integer> arr,int si,int ei){
if(si>ei) return null;
int mid = (si + ei ) >> 1;
Node node = new Node(arr.get(mid));
node.left = constructBST(arr,si,mid - 1);
node.right = constructBST(arr,mid + 1, ei);
return node;
}
public static void display(Node node){
if(node==null) return;
StringBuilder sb = new StringBuilder();
sb.append(node.left!=null?node.left.data+"" : ".");
sb.append(" <- " + node.data + " -> ");
sb.append(node.right!=null?node.right.data+"" : ".");
System.out.println(sb.toString());
display(node.left);
display(node.right);
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>();
int a[]={1,2,3,5,9,12,19,21,25};
for(int i = 0; i <a.length; i++) arr.add(a[i]);
Node root = constructBST(arr,0,arr.size()-1);
display(root);
System.out.println(findMaxElement(root,1,25));
}
static int maxNode=0;
public static int findMaxElement(Node node, int val1,int val2){
Node lca=findLca(node,val1,val2);
lcaToNodePath(lca,val1);
lcaToNodePath(lca,val2);
return maxNode;
}
public static Node findLca(Node node,int val1,int val2){
if(node==null) return null;
if(val1<node.data&&val2<node.data) return findLca(node.left,val1,val2);
else if(val1>node.data&&val2>node.data) return findLca(node.right,val1,val2);
else return node;
}
public static void lcaToNodePath(Node node,int val){
if(node==null||node.data==val) return;
maxNode=Math.max(maxNode,node.data);
if(val<node.data) lcaToNodePath(node.left,val);
else lcaToNodePath(node.right,val);
}
}
|
Java
|
UTF-8
| 288
| 2.484375
| 2
|
[] |
no_license
|
package com.cheny.algs4.wk4_priority_queue;
/**
* <p>MaxPQ</p>
*
* @author of1610 chenyong
* @version 1.0
* @since 1.0
*/
public interface MaxPQ<Key extends Comparable<Key>> {
void insert(Key key);
Key delMax();
boolean isEmpty();
Key max();
int size();
}
|
Markdown
|
UTF-8
| 2,548
| 2.8125
| 3
|
[] |
no_license
|
[[File:Electrochemical_element_with_salt_bridge.png|thumb]]。]]
'''鹽橋''' (Salt bridge) 在[[化學|化學]]上是指一種[[實驗|實驗]]裝置,用以連接[[伽凡尼電池|賈凡尼電池]](伏打電池,一種[[電化電池|電化電池]])的[[氧化|氧化]]半電池和[[還原|還原]]半電池。鹽橋通常分為兩類:玻璃管型和[[濾紙|濾紙]]型。
==玻璃管型鹽橋==
此型鹽橋由U型管和填滿管內的相對[[惰性|惰性]][[電解質|電解質]]組成。電解質通常使用饱和[[氯化鉀|氯化鉀]](KCl)或硝酸铵(NH<sub>4</sub>NO<sub>3</sub>)。瓊脂經常用以使電解質膠凝(gelification)。<ref name="physchemjlu">杨永华 等,《物理化学》,高等教育出版社,2012,北京</ref><ref name="Fujishima">藤岛昭 等著,陈震 等译,《电化学测定方法》,北京大学出版社,1995,北京</ref>
玻璃管型鹽橋[[電導率|導電度]]大部分取決於電解質溶液的[[濃度|濃度]]。未飽和前增加濃度可增加導電度。過飽和的電解質和管徑狹窄可能降低導電度。
===玻璃管型盐桥的作用===
當离子自賈法尼電池(原电池)的一個半電池流向另一個,因为正负极会相应的积累相反的电荷,(注意不是由于正负离子扩散速度不同,造成[[電荷|電荷]]差異)。若未使用鹽橋,此電荷差異將附加到电池的总体电动势上,从而降低电池电势。此电动势被称作[[液接电势|液接电势]]。使用盐桥后,原本两半电池中电解质溶液的液相接界就变为盐桥与电解质溶液的接界。由于盐桥中离子活度很大,离子扩散以盐桥中的离子为主;又因为盐桥中两种离子的扩散速度相近,故液接电势得以减小,在一般精度要求下,可以认为消除了液接电势。<ref name="physchemjlu" />
==濾紙型鹽橋==
此型鹽橋由浸潤過适当電解質的濾紙組成。因為濾紙本身已提供可傳導的固體介質,故不需要膠凝的媒介。
濾紙型鹽橋導電度取決於多個因素:電解質溶液的濃度、濾紙的構造及濾紙的吸附能力。一般而言,濾紙結構愈平滑、吸附能力愈高,則導電度愈大。
置於两個半電池間的多孔碟或其它多孔障壁可以取代滤纸型鹽橋,它們的用途基本相同——仅作为两半池之间导通媒介。
==参考资料==
<references />
{{電池}}
[[Category:電化學|Category:電化學]]
[[Category:實驗室設備|Category:實驗室設備]]
|
Java
|
UTF-8
| 569
| 2.375
| 2
|
[] |
no_license
|
import java.io.*;
import java.net.*;
public class ServerSSTachTen {
public final static int defaultPort = 2017;
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
System.out.println("server start ...");
ServerSocket ss = new ServerSocket(defaultPort);
while(true){
Socket s = ss.accept();
System.out.println("chap nhan ket noi tu client thu:");
RPTachTen rp = new RPTachTen(s);
rp.start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
Python
|
UTF-8
| 4,186
| 2.5625
| 3
|
[] |
no_license
|
import numpy as np
from itertools import combinations, permutations
from group_actions.group_utiliies import permutation_parity
class WedgeMaker:
def __init__(self, power):
self.power = power
get_wedge_matrix_mapping = {
2: self._get_wedge_matrix_dim_2,
3: self._get_wedge_matrix_dim_3
}
if self.power in get_wedge_matrix_mapping:
get_wedge_matrix = get_wedge_matrix_mapping[self.power]
else:
get_wedge_matrix = self._get_wedge_matrix_dim_k
self._get_wedge_matrix = get_wedge_matrix
def get_wedge_matrix(self, matrix):
return self._get_wedge_matrix(matrix)
def _get_wedge_matrix_dim_2(self, matrix):
basis_indices = self.get_wedge_basis_indices(matrix.shape[0])
result = []
for indices in basis_indices:
vectors = [matrix[i, :] for i in indices]
wedge_vector = self._get_wedge2(vectors, basis_indices)
result.append(wedge_vector)
return np.transpose(np.asarray(result))
@staticmethod
def _get_wedge2(vectors, basis_indices) -> np.ndarray:
result = []
for indices in basis_indices:
temp_additive = vectors[0][indices[0]] * vectors[1][indices[1]] \
- vectors[0][indices[1]] * vectors[1][indices[0]]
result.append(temp_additive)
return np.asarray(result)
def _get_wedge_matrix_dim_3(self, matrix):
basis_indices = self.get_wedge_basis_indices(matrix.shape[0])
result = []
for indices in basis_indices:
vectors = [matrix[i, :] for i in indices]
wedge_vector = self._get_wedge3(vectors, basis_indices)
result.append(wedge_vector)
return np.transpose(np.asarray(result))
@staticmethod
def _get_wedge3(vectors, basis_indices) -> np.ndarray:
result = []
for indices in basis_indices:
temp_additive = + vectors[0][indices[0]] * vectors[1][indices[1]] * vectors[2][indices[2]] \
+ vectors[0][indices[1]] * vectors[1][indices[2]] * vectors[2][indices[0]] \
+ vectors[0][indices[2]] * vectors[1][indices[0]] * vectors[2][indices[1]] \
- vectors[0][indices[0]] * vectors[1][indices[2]] * vectors[2][indices[1]] \
- vectors[0][indices[2]] * vectors[1][indices[1]] * vectors[2][indices[0]] \
- vectors[0][indices[1]] * vectors[1][indices[0]] * vectors[2][indices[2]]
result.append(temp_additive)
return np.asarray(result)
def _get_wedge_matrix_dim_k(self, matrix):
basis_indices = self.get_wedge_basis_indices(matrix.shape[0])
result = [[np.linalg.det(matrix[self._get_minor_indices(indices2, indices)])
for indices2 in basis_indices] for indices in basis_indices]
return np.asarray(result)
def get_wedge_basis_indices(self, dimension):
return list(combinations(range(dimension), self.power))
@staticmethod
def _get_minor_indices(indices, indices2):
return np.ix_(indices, indices2)
def _call_from_base_call(self, matrix):
basis_indices = self.get_wedge_basis_indices(matrix.shape[0])
result = []
for indices in basis_indices:
vectors = [matrix[i, :] for i in indices]
wedge_vector = self._get_wedge(vectors, basis_indices)
result.append(wedge_vector)
return np.transpose(np.asarray(result))
@staticmethod
def _get_wedge(vectors, basis_indices) -> np.ndarray:
result = []
for indices in basis_indices:
temp_additive = 0
indices_enumeration = range(len(indices))
for indices_permutation in permutations(indices_enumeration):
temp = permutation_parity(indices_permutation)
temp = temp
for i in range(len(vectors)):
temp *= vectors[i][indices[indices_permutation[i]]]
temp_additive += temp
result.append(temp_additive)
return np.asarray(result)
|
Java
|
UTF-8
| 1,379
| 2.671875
| 3
|
[] |
no_license
|
package com.jfbian.utils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.commons.io.FileUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/**
* @ClassName: JsonFileUtil
* @Description:解析.json文件工具类
* @author: bianjianfeng
* @date: 2020-04-27 20:00:27
*/
public class JsonFileUtil {
/**
* 读取文件数据为JSONObject
* @return JSONObject
* @throws IOException
*/
public static JSONObject readJsonObjectData(String fileFullPath) {
File file = new File(fileFullPath);
JSONObject parseObject = null;
try {
parseObject = JSONObject.parseObject(FileUtils.readFileToString(file, Charset.forName("utf-8")));
} catch (IOException e) {
e.printStackTrace();
}
return parseObject;
}
/**
* 读取文件数据为JSONArray
* @return JSONArray
* @throws IOException
*/
public static JSONArray readJsonArrayData(String fileFullPath) {
File file = new File(fileFullPath);
JSONArray parseArray = null;
try {
parseArray = JSONArray.parseArray(FileUtils.readFileToString(file, Charset.forName("utf-8")));
} catch (IOException e) {
e.printStackTrace();
}
return parseArray;
}
}
|
C#
|
UTF-8
| 408
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
using System;
namespace Al500CSharp {
/*prog imp3
imprima 11Aprendendo Algoritmo!!!";
imprima "\nCom Anita e Guto";
fimprog */
public class Algoritmo13 {
private void Logic () {
string[] imprima = { "Aprendendo Algoritmo!!!", "\nCom Anita Lopes e Guto Garcia." };
Console.WriteLine ($"\n{imprima[0]+imprima[1]}");
}
public void Run () => Logic ();
}
}
|
PHP
|
UTF-8
| 331
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace FFMpeg\Tests\Coordinate;
use FFMpeg\Tests\TestCase;
use FFMpeg\Coordinate\Point;
class PointTest extends TestCase
{
public function testGetters()
{
$point = new Point(4, 25);
$this->assertEquals(4, $point->getX());
$this->assertEquals(25, $point->getY());
}
}
|
C++
|
UTF-8
| 2,296
| 2.6875
| 3
|
[] |
no_license
|
class Solution {
public:
int numberOfPatterns(int m, int n) {
int ans = 0;
vector<bool> visited(9, false);
for (int i=0; i<3; ++i) {
for (int j=0; j<3; ++j) {
dfs(i, j, 0, m, n, visited, ans);
}
}
return ans;
}
void dfs(int i, int j, int used, int m, int n, vector<bool>& visited, int& ans) {
if (i > 2 || i < 0 || j > 2 || j < 0) return;
if (used >= n) return;
int index = i*3 + j;
if (!visited[index]) {
visited[index] = true;
++used;
if (used >= m && used <= n) ++ans;
// one move
dfs(i-1, j, used, m, n, visited, ans);
dfs(i+1, j, used, m, n, visited, ans);
dfs(i, j-1, used, m, n, visited, ans);
dfs(i, j+1, used, m, n, visited, ans);
dfs(i-1, j-1, used, m, n, visited, ans);
dfs(i-1, j+1, used, m, n, visited, ans);
dfs(i+1, j-1, used, m, n, visited, ans);
dfs(i+1, j+1, used, m, n, visited, ans);
// jump
dfs(i+1, j+2, used, m, n, visited, ans);
dfs(i+2, j+1, used, m, n, visited, ans);
dfs(i-1, j-2, used, m, n, visited, ans);
dfs(i-2, j-1, used, m, n, visited, ans);
dfs(i-1, j+2, used, m, n, visited, ans);
dfs(i-2, j+1, used, m, n, visited, ans);
dfs(i+1, j-2, used, m, n, visited, ans);
dfs(i+2, j-1, used, m, n, visited, ans);
// line move
if (j == 0 && visited[i*3 + j+1]) dfs(i, j+2, used, m, n, visited, ans);
if (i == 0 && visited[(i+1)*3 + j]) dfs(i+2, j, used, m, n, visited, ans);
if (j == 2 && visited[i*3 + j-1]) dfs(i, j-2, used, m, n, visited, ans);
if (i == 2 && visited[(i-1)*3 + j]) dfs(i-2, j, used, m, n, visited, ans);
if (i == 0 && j == 0 && visited[4]) dfs(i+2, j+2, used, m, n, visited, ans);
if (i == 2 && j == 2 && visited[4]) dfs(i-2, j-2, used, m, n, visited, ans);
if (i == 0 && j == 2 && visited[4]) dfs(i+2, j-2, used, m, n, visited, ans);
if (i == 2 && j == 0 && visited[4]) dfs(i-2, j+2, used, m, n, visited, ans);
visited[index] = false;
}
}
};
|
Go
|
UTF-8
| 2,659
| 3.09375
| 3
|
[] |
no_license
|
//批量发送http请求
package multiHttp
import (
"strings"
"io"
"bufio"
"os"
"net/http"
"io/ioutil"
"net/url"
)
/* GET 请求
* uri http地址
*/
func Get(uri string) string{
rep,err := http.Get(uri)
if err != nil{
return "404"
}
defer rep.Body.Close()
body,err := ioutil.ReadAll(rep.Body)
if err != nil{
return "400"
}
return string(body)
}
/* POST 请求
* uri http地址
* param POST参数
*/
func Post(uri string,param map[string]string) string{
query := url.Values{}
for key,val := range param{
query.Set(key,val)
}
rep, err := http.PostForm(uri,query)
if err != nil {
return "404"
}
defer rep.Body.Close()
body, err := ioutil.ReadAll(rep.Body)
if err != nil {
return "400"
}
return string(body)
}
/* 解析文件成map切片用于post
* fpath 文件路径
*/
func ParamFile(fpath string) []map[string]string{
file,err := os.Open(fpath)
if err != nil{
panic("文件不存在")
}
defer file.Close()
rd := bufio.NewReader(file)
paret := make([]map[string]string,0)
for{
//line,err := rd.ReadString('\n') //读取行,如果文件末尾没有空行,最后一行不返回
line,_,err := rd.ReadLine()
if err != nil || err == io.EOF{
break
}
lnstr := string(line)
lnarr := strings.Split(lnstr," ")
quarr := make([]string,0)
for _,val := range lnarr{
v := strings.TrimSpace(val)
if len(v) > 0{
quarr = append(quarr,v)
}
}
if len(quarr)%2 != 0{
panic("参数数量异常内容:"+lnstr)
}
qumap := make(map[string]string)
for i := 0;i < len(quarr)/2;i++{
qumap[quarr[i*2]] = quarr[i*2+1]
}
paret = append(paret,qumap)
}
return paret
}
/* 解析文件成string切片用于get
* fpath 文件路径
*/
func ParamLine(fpath string) []string{
file,err := os.Open(fpath)
if err != nil{
panic("文件不存在")
}
defer file.Close()
rd := bufio.NewReader(file)
paret := make([]string,0)
for{
//line,err := rd.ReadString('\n') //读取行,如果文件末尾没有空行,最后一行不返回
line,_,err := rd.ReadLine()
if err != nil || err == io.EOF{
break
}
qstr := strings.TrimSpace(string(line))
paret = append(paret,qstr)
}
return paret
}
|
C++
|
UTF-8
| 1,254
| 2.71875
| 3
|
[
"BSL-1.0"
] |
permissive
|
//-----------------------------------------------------------------------------
// constant expression table library
//-----------------------------------------------------------------------------
//
// Copyright (c) 2013
// Joshua Napoli <jnapoli@alum.mit.edu>
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef __ARRAY_EQUAL_PREDICATE_HPP__
#define __ARRAY_EQUAL_PREDICATE_HPP__
#include <array>
template<typename T0, std::size_t N0, typename T1, std::size_t N1>
class array_equal_predicate
{
public:
typedef bool result_type;
constexpr array_equal_predicate(const std::array<T0,N0>&, const std::array<T1,N1>&) {}
constexpr bool operator()() { return false; }
};
template<typename T0, typename T1, std::size_t N>
class array_equal_predicate<T0,N,T1,N>
{
public:
typedef bool result_type;
constexpr array_equal_predicate(const std::array<T0,N>& a0, const std::array<T1,N>& a1)
: a0_(a0)
, a1_(a1)
{}
constexpr bool operator()(std::size_t index = 0)
{
return index == N || ( a0_[index] == a1_[index] && (*this)(index+1) );
}
private:
const std::array<T0,N>& a0_;
const std::array<T1,N>& a1_;
};
#endif
|
Java
|
UTF-8
| 1,440
| 3.140625
| 3
|
[] |
no_license
|
package com.easystudy.error;
public class ReturnValue<T> {
private Integer error; // 错误
private String description; // 错误描述
private T value; // 返回值【当error为ERROR_NO_SUCCESS才有可能返回值-判断值是否为空】
// 成功不带返回值
public ReturnValue(){
this.error = ErrorCode.ERROR_SUCCESS.getError();
this.description = "success";
}
// 成功带返回值
public ReturnValue(T value){
if(null == value){
this.error = ErrorCode.ERROR_SERVER_ERROR.getError();
this.description = "the result is null";
} else {
this.error = ErrorCode.ERROR_SUCCESS.getError();
this.description = "success";
this.value = value;
}
}
// 返回错误
public ReturnValue(ErrorCode error){
this.error = error.getError();
this.description = error.getDescription();
}
// 返回错误--对错误描述进行更改
public ReturnValue(ErrorCode error, String description){
this.error = error.getError();
this.description = description;
}
public Integer getError() {
return error;
}
public void setError(Integer error) {
this.error = error;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}
|
C#
|
UTF-8
| 1,010
| 2.625
| 3
|
[] |
no_license
|
using DentalOffice.BLL.Interfaces;
using DentalOffice.DAL.Interfaces;
using DentalOffice.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DentalOffice.BLL
{
public class PatientsLogic : IPatientsLogic
{
private readonly IPatientsDao _patientsDao;
public PatientsLogic(IPatientsDao patientsDao)
{
_patientsDao = patientsDao;
}
public Patient Add(Patient patient)
{
return _patientsDao.Add(patient);
}
public void DeleteById(int id)
{
_patientsDao.DeleteById(id);
}
public IEnumerable<Patient> GetAll()
{
return _patientsDao.GetAll();
}
public Patient GetById(int id)
{
return _patientsDao.GetById(id);
}
public void Update(Patient patient)
{
_patientsDao.Update(patient);
}
}
}
|
PHP
|
UTF-8
| 1,223
| 3.21875
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace Essential\Http;
class Request
{
private static $request;
private $method;
private $uri;
/**
* Request constructor.
*/
public function __construct()
{
$this->method = $_SERVER['REQUEST_METHOD'];
$this->uri = $_SERVER['REQUEST_URI'];
$this->setRequestAttributes();
self::$request = $this;
}
/**
Check request method
*
* @param $method
* @return bool
*/
public function isMethod($method){
return $this->method == $method ? true : false;
}
/**
*
*/
public function setRequestAttributes()
{
foreach ($_REQUEST as $key => $value) {
$this->$key = $value;
}
}
/**
* @return mixed
*/
public function all()
{
return $_REQUEST;
}
/**
* Get current request
*
* @return $this
*/
public static function getCurrent()
{
if (is_null(self::$request)) {
self::$request = new self();
}
return self::$request;
}
/**
* Get request uri
*
* @return mixed
*/
public function uri()
{
return $this->uri;
}
}
|
Java
|
UTF-8
| 4,052
| 3.109375
| 3
|
[] |
no_license
|
package com.example.project4;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.inputmethod.InputMethodManager;
public class MainActivity extends AppCompatActivity
{
// Initialize variables for the EditText inputs and the Calculate button
EditText weight, heightFt, heightIn;
Button calculate;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Variables receive the values from the corresponding objects in the application
weight = (EditText)findViewById(R.id.inPounds);
heightFt = (EditText)findViewById(R.id.inFt);
heightIn = (EditText)findViewById(R.id.inIn);
calculate = (Button)findViewById(R.id.btnCalculate);
// Creates an event for when the user presses the 'Calculate' button
calculate.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// Hides the virtual keyboard when the 'Calculate' button is pressed
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(heightIn.getWindowToken(), 0);
// Goes to the function that calculates the inputted weight and height
bmiCalculate(v);
}
});
}
// Performs all of the calculations and displays the output for the user's BMI
public void bmiCalculate(View view)
{
// Initialize string and boolean variables to determine if the inputs for the weight and
// height are ONLY numerical values
String strWeight = weight.getText().toString();
String strFt = heightFt.getText().toString();
String strIn = heightIn.getText().toString();
boolean weightCheck = TextUtils.isDigitsOnly(weight.getText());
boolean heightFtCheck = TextUtils.isDigitsOnly(heightFt.getText());
boolean heightInCheck = TextUtils.isDigitsOnly(heightIn.getText());
// Calculates if all of the
if (!strWeight.matches("") && !strFt.matches("") && !strIn.matches("") &&
weightCheck && heightFtCheck && heightInCheck) {
TextView BMILevel = (TextView) findViewById(R.id.txtBMI);
TextView BMIStatus = (TextView) findViewById(R.id.txtBMIStatus);
// Initializes the string input of the weight and height in English measurements as floats
float weightLbs = Float.parseFloat(strWeight);
float heightInch = (Float.parseFloat(strFt) * 12) + Float.parseFloat(strIn);
// Calculates the BMI by multiplying the inputted weight in pounds by 703 before dividing
// by the square of the inputted height in inches
float BMI = ((weightLbs * 703) / (heightInch * heightInch));
// Calls a function to return a string for the BMI status to explain the user's weight status
// in more layman terms
String bmiStatus = interpretBMI(BMI);
// Edits the TextView objects in the application to display the numerical BMI and the
// status of said BMI in layman's terms
BMILevel.setText("BMI: " + BMI);
BMIStatus.setText("Status: " + bmiStatus);
}
}
// Returns as string of the status of the person's BMI based on their BMI level
private String interpretBMI(float bmiValue)
{
if (bmiValue < 18.5)
{
return "Underweight";
}
else if (bmiValue < 25)
{
return "Normal";
}
else if (bmiValue < 30)
{
return "Overweight";
}
else
return "Obese";
}
}
|
Rust
|
UTF-8
| 1,204
| 3
| 3
|
[] |
no_license
|
use std::collections::VecDeque;
use proconio::input;
fn main() {
input! {
n: usize,
}
let mut roads = vec![vec![]; n + 1];
for _ in 0..n - 1 {
input! {
a:usize,
b:usize,
}
roads[a].push(b);
roads[b].push(a);
}
let (last, _) = search(1, &roads);
let (_, depth) = search(last, &roads);
println!("{}", depth + 1);
}
fn search(start: usize, roads: &Vec<Vec<usize>>) -> (usize, i32) {
let mut stack = VecDeque::<usize>::new();
let mut visited = vec![false; roads.len()];
let mut last = 0_usize;
let mut depth = 0;
visited[start] = true;
for r in roads[start].iter() {
stack.push_back(*r);
}
while !stack.is_empty() {
let size = stack.len();
for _ in 0..size {
let from = stack.pop_front().unwrap();
if visited[from] {
continue;
}
visited[from] = true;
last = from;
for r in roads[from].iter() {
if !visited[*r] {
stack.push_back(*r);
}
}
}
depth += 1;
}
return (last, depth);
}
|
Java
|
UTF-8
| 791
| 3
| 3
|
[] |
no_license
|
import java.io.PrintWriter;
import java.util.Scanner;
public class problem_165 {
public static void main(String[] args) {
Scanner e = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out,false);
int num;
do
{
Boolean ban = true;
String Stnum = e.nextLine();
num = Integer.parseInt(Stnum);
if(num<0)
break;
for(int i=0; i<Stnum.length(); i++)
{
int n = (int)Stnum.charAt(i);
if(n%2==0) {
} else
ban = false;
}
if(ban)
pw.println("SI");
else
pw.println("NO");
}while(num>=0);
pw.close();
}
}
|
JavaScript
|
UTF-8
| 2,596
| 4.75
| 5
|
[] |
no_license
|
const args = process.argv.slice(2);
const word = args[0].toLowerCase(); // ensures we start with a word that is lowercase
let result = '';
for (let i = 0; i < word.length; i++) {
if (i % 2 === 0) {
// if it is an even letter (even from the code perspective,
// remember js/computers start counting at 0 not 1)
// Then we will keep it the same, which is lower case
result += word[i];
} else {
// Otherwise, we will make the letter upper case
result += word[i].toUpperCase();
}
}
console.log(result);
// STRETCH
/*
const args = process.argv.slice(2);
const sentence = args.join(' '); // this joins our strings into a sentence
const words = sentence.toLowerCase(); // ensures we start with a word that is lowercase
let result = '';
for (let i = 0; i < words.length; i++) {
if (i % 2 === 0) {
// if it is an even letter (even from the code perspective,
// remember js/computers start counting at 0 not 1)
// Then we will keep it the same, which is lower case
result += words[i];
} else {
// Otherwise, we will make the letter upper case
result += words[i].toUpperCase();
}
}
console.log(result);
*/
/*
Another solution
// Get the word from the arguments
// we are using `let` here because we will be reassigning the `word` variable later
let word = args[0];
// take our word, and change all letters to be in lower case
word = word.toLowerCase();
// the `split` string method changes the string into an array
// it will split the string into an array by matching against its string argument
// For example:
// "hello there, everyone".split(' ')
// will return
// ['hello', 'there,', 'everyone']
word = word.split('');
// in our example, `word.split('')` will give each characer within the word-string
// its own index
// For example:
// "hi max".split('')
// will return
// ['h', 'i', ' ', 'm', 'a', 'x']
// Next, we loop over everycharacter in the word
for (let i = 0; i < word.length; i++) {
// if the index of that character is even, we will change it to uppercase
if (i % 2 !== 0) {
word[i] = word[i].toUpperCase();
}
}
// the array method `join` will join an array together into a string
// It will use the string sequence that it was passed as an argument as
// the string to "join" on
// For example:
// ['h', 'i', ' ', 'm', 'a', 'x'].join('-!-')
// will return
// 'h-!-i-!- -!-m-!-a-!-x'
word = word.join('');
// using the '' (empty string) as the joining string will put the letters back together
// For example:
// ['h', 'i', ' ', 'm', 'a', 'x'].join('')
// will return
// 'hi max'
console.log(word);
*/
|
PHP
|
UTF-8
| 532
| 3.625
| 4
|
[] |
no_license
|
<?php
/**
* author:lhj
* email:416703504@qq.com
* create: 2020/3/20 9:36
**/
class Solution
{
/**
* @param Integer[] $arr
* @param Integer $k
* @return Integer[]
*/
function getLeastNumbers($arr, $k)
{
$minArr = [];
while (count($minArr) < $k) {
$min = min($arr);
$minArr[] =$min;
$key = array_search($min, $arr);
unset($arr[$key]);
}
return $minArr;
}
}
$s = new Solution();
$s->getLeastNumbers([4,5,1,6,2,7,3,8],4);
|
Markdown
|
UTF-8
| 413
| 2.625
| 3
|
[] |
no_license
|
# hello-world
Git Hub's Hello World project
Hello World!
My name is Christopher Stevens. I live in Tempe, AZ.
I am a software developer looking to expand my experience and skill set.
I am primarily a python programmer, but also have coded in java, javascript, html, css, xml and for my last job, I made Magic.
Looking forward to lots of work being added here. Thanks GitHub for this opportunity.
Christopher Stevens
Software Developer
|
Java
|
UTF-8
| 384
| 2.203125
| 2
|
[] |
no_license
|
package com.niit.demoDAO;
import java.util.List;
import com.niit.demomodel.product;
public interface productDAO {
public void persist(product p);
public product getId (int productid);
public boolean update(product p);
public product findById(int productid);
public List<product> getAllproduct();
public boolean delete(product p);
}
|
SQL
|
UTF-8
| 9,639
| 2.796875
| 3
|
[] |
no_license
|
/*
Navicat Premium Data Transfer
Source Server : cars
Source Server Type : MySQL
Source Server Version : 80011
Source Host : localhost:3306
Source Schema : cars
Target Server Type : MySQL
Target Server Version : 80011
File Encoding : 65001
Date: 19/07/2018 08:40:31
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for customer
-- ----------------------------
DROP TABLE IF EXISTS `customer`;
CREATE TABLE `customer` (
`customer_id` char(16) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`customer_name` varchar(60) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`customer_vip` varchar(1) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`customer_IdCard` varchar(60) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`customer_tel` varchar(60) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`customer_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of customer
-- ----------------------------
INSERT INTO `customer` VALUES ('00464FC39DB3BAA6', 'Uriah Raphael', '1', '230623000000000000 ', '15300568069');
INSERT INTO `customer` VALUES ('010A4049A285303E', 'Chasel Michelson', '0', '130626000000000000 ', '15902947783');
INSERT INTO `customer` VALUES ('04504F40A71CD0E8', 'Hunter Oscar', '0', '320321000000000000 ', '13505675988');
INSERT INTO `customer` VALUES ('07214D18BB594EBC', 'Hulda Winifred', '1', '440785000000000000 ', '13907261954');
INSERT INTO `customer` VALUES ('07F745908A094CE3', 'Scott Wilhelmina', '0', '511402000000000000 ', '13502038459');
INSERT INTO `customer` VALUES ('0B294261A5EA44D3', 'Bing Lucas', '1', '440500000000000000 ', '15504005756');
INSERT INTO `customer` VALUES ('0DA04FFBA5423A4A', 'Wanda Jennings', '1', '511325000000000000 ', '15908221486');
INSERT INTO `customer` VALUES ('0E5944E285EDDE2D', 'Geraldine Fowler', '1', '451102000000000000 ', '13300924892');
INSERT INTO `customer` VALUES ('12CF46FBA5577CE0', 'Rudolf North', '1', '350125000000000000 ', '15706593865');
INSERT INTO `customer` VALUES ('1660462D9EB4B954', 'Rupert Louisa', '1', '330104000000000000 ', '13808250006');
INSERT INTO `customer` VALUES ('1B7D4869B99192A0', 'Nora Wyld(e)', '1', '220203000000000000 ', '15506305688');
INSERT INTO `customer` VALUES ('1CD541A9BB4EE196', 'Josephine Smedley', '1', '530500000000000000 ', '13605392364');
INSERT INTO `customer` VALUES ('1D774680B01C1ECA', 'Elmer Bryce', '0', '451027000000000000 ', '15008861138');
INSERT INTO `customer` VALUES ('1E84438A83FC319B', 'Elliot Katte', '1', '420200000000000000 ', '13608320901');
INSERT INTO `customer` VALUES ('22A8422E8708F738', 'Tracy Black', '1', '370923000000000000 ', '13806978216');
INSERT INTO `customer` VALUES ('22B143C6A1DBECE2', 'Atwood Woolley', '1', '222404000000000000 ', '13207252654');
INSERT INTO `customer` VALUES ('23DC4850B474428D', 'Judy Samuel', '1', '450000000000000000 ', '13506554957');
INSERT INTO `customer` VALUES ('24734EF599499848', 'George Rhys', '1', '341125000000000000 ', '15007201983');
INSERT INTO `customer` VALUES ('2AAF4F2785C00383', 'Sheila Jerome', '1', '620621000000000000 ', '15108416919');
INSERT INTO `customer` VALUES ('2C1B4D739EB224F3', 'Natalie Abraham', '0', '510304000000000000 ', '13100103401');
INSERT INTO `customer` VALUES ('2F1F438ABE4D592A', 'Nathaniel Motley', '1', '450126000000000000 ', '15907620212');
INSERT INTO `customer` VALUES ('2F884CB5A0E0F823', 'Ryan Joan', '0', '420500000000000000 ', '13305182449');
INSERT INTO `customer` VALUES ('32394E39BBBD0D79', 'Frank Bruce', '0', '411324000000000000 ', '13406638874');
INSERT INTO `customer` VALUES ('32574A1B86FA61F7', 'Olga Sharp', '1', '654323000000000000 ', '13707553443');
INSERT INTO `customer` VALUES ('351642C0AAADF511', 'Steward Kelvin', '1', '532501000000000000 ', '13108818735');
INSERT INTO `customer` VALUES ('382343FE8503558B', 'Gregary Steinbeck', '1', '370681000000000000 ', '15906974971');
INSERT INTO `customer` VALUES ('38F54B69872F8430', 'Tyrone London', '1', '500234000000000000 ', '13307251071');
INSERT INTO `customer` VALUES ('398F451190E87FF5', 'Joyce Kennedy', '1', '330322000000000000 ', '13504060013');
INSERT INTO `customer` VALUES ('3C7744FDAFCF58A3', 'Angelo DuBois', '1', '360000000000000000 ', '13702088040');
INSERT INTO `customer` VALUES ('45124D2E9EBB3247', 'Yvonne Eden', '1', '330100000000000000 ', '13600077152');
INSERT INTO `customer` VALUES ('469D4ACC89C5166C', 'Trista Occam', '1', '622921000000000000 ', '15608741143');
INSERT INTO `customer` VALUES ('51AF4C4AB19932C7', 'Lynn Attlee', '1', '310109000000000000 ', '15206015745');
INSERT INTO `customer` VALUES ('52F340CBA4739DFD', 'Neil Hardy', '0', '130529000000000000 ', '13008350023');
INSERT INTO `customer` VALUES ('5B0E4C7FB5865E1E', 'Norton Dalton', '0', '370113000000000000 ', '13300526552');
INSERT INTO `customer` VALUES ('62044F17A046E4D7', 'Matt Paul', '1', '321203000000000000 ', '15702374636');
INSERT INTO `customer` VALUES ('62F645A8A4468DA6', 'Walter Margery', '1', '630104000000000000 ', '15108652139');
INSERT INTO `customer` VALUES ('67AF435392ECF3A6', 'Mike Sophy', '1', '440825000000000000 ', '15908785163');
INSERT INTO `customer` VALUES ('725F45EC9A5BF690', 'Beryl Johnston(e)', '0', '542427000000000000 ', '13108734263');
INSERT INTO `customer` VALUES ('754F46A6A5E59AF8', 'Salome Twain', '1', '140624000000000000 ', '15602028686');
INSERT INTO `customer` VALUES ('80E9487D8AAADBC5', 'Vita Nixon', '0', '120106000000000000 ', '13708485541');
INSERT INTO `customer` VALUES ('832342B8B99E8F48', 'Marjorie Walpole', '1', '211403000000000000 ', '15203577216');
INSERT INTO `customer` VALUES ('84934D4791E79B24', 'Aries Jonathan', '1', '350784000000000000 ', '13400392168');
INSERT INTO `customer` VALUES ('85C34948BCEDDA54', 'Aldrich Grantham', '0', '360803000000000000 ', '15008402038');
INSERT INTO `customer` VALUES ('895844EE8C24029F', 'Pag Sandy', '0', '61072620080124768X', '13406092938');
INSERT INTO `customer` VALUES ('898F4BFBB0EA12AC', 'Bard Maurice', '0', '320205000000000000 ', '15005511956');
INSERT INTO `customer` VALUES ('8D484E69A055A1A6', 'Adelaide Chamberlain', '1', '542123000000000000 ', '15105828100');
INSERT INTO `customer` VALUES ('905B433199104922', 'Janet Nancy', '1', '440222000000000000 ', '13401925809');
INSERT INTO `customer` VALUES ('92CF4FCD9A3C21B2', 'Blair Max', '0', '141130000000000000 ', '13508701295');
INSERT INTO `customer` VALUES ('9341471DAD633B50', 'Fitch Tommy', '1', '450221000000000000 ', '15701361865');
INSERT INTO `customer` VALUES ('94CC4A02B84978A7', 'Adam Frederick', '1', '652101000000000000 ', '15104259012');
INSERT INTO `customer` VALUES ('94DC490098E289A7', 'Phoebe Fanny', '1', '420525000000000000 ', '15202528962');
INSERT INTO `customer` VALUES ('9639494E811CA18B', 'Sid Simpson', '0', '623000000000000000 ', '13103775668');
INSERT INTO `customer` VALUES ('9B8443D59AAD2F2B', 'Fay Childe', '1', '340322000000000000 ', '13806138513');
INSERT INTO `customer` VALUES ('9E354113879B6500', 'Jo Hornby', '1', '230183000000000000 ', '13702259055');
INSERT INTO `customer` VALUES ('A0E74B81BB1CB8FE', 'Lydia Thodore', '1', '370983000000000000 ', '13506324685');
INSERT INTO `customer` VALUES ('A1444F51A47821F5', 'Rachel Walker', '1', '610103000000000000 ', '15203078806');
INSERT INTO `customer` VALUES ('A953446E811BDC36', 'Louis Ellis', '1', '130430000000000000 ', '15900813393');
INSERT INTO `customer` VALUES ('AC0B4C5EA436304C', 'Ella Hodge', '1', '131003000000000000 ', '13805061938');
INSERT INTO `customer` VALUES ('AE564250A6B82042', 'Ed Kell(e)y', '1', '440903000000000000 ', '13805716436');
INSERT INTO `customer` VALUES ('AF7E428B91052709', 'Wayne Hart', '1', '34182119880914019X', '13208680827');
INSERT INTO `customer` VALUES ('B34840A3BB6C674D', 'Prima Stevenson', '1', '350627000000000000 ', '15100088008');
INSERT INTO `customer` VALUES ('B46943E7A4CCEDEB', 'Catherine Hudson', '0', '440703000000000000 ', '13205591396');
INSERT INTO `customer` VALUES ('B66645AC9290FC92', 'Susanna Thorndike', '1', '420822000000000000 ', '15508006496');
INSERT INTO `customer` VALUES ('B7694C0B87600A96', 'Bella Carrie', '1', '450302000000000000 ', '13308431408');
INSERT INTO `customer` VALUES ('C11B46789706D7C2', 'Bruno Reed', '0', '610331000000000000 ', '15301206696');
INSERT INTO `customer` VALUES ('C678444DA174C138', 'Conrad Thackeray', '1', '411424000000000000 ', '13200557350');
INSERT INTO `customer` VALUES ('CA6249099516C247', 'Elva Church', '0', '622901000000000000 ', '15700077848');
INSERT INTO `customer` VALUES ('CB4A4381B346AD61', 'Ivan Vincent', '1', '44530219890820767X', '13306195857');
INSERT INTO `customer` VALUES ('D56949EB89A605C1', 'Dora Robbins', '1', '140881000000000000 ', '13503152904');
INSERT INTO `customer` VALUES ('D71E422196392FBE', 'Alice Gray', '0', '320705000000000000 ', '13901532816');
INSERT INTO `customer` VALUES ('D92442BBA9A1ABC5', 'Cornelius Walter', '1', '530622000000000000 ', '13302672452');
INSERT INTO `customer` VALUES ('D9EF4313A5BC991F', 'Eleanore Crichton', '0', '542400000000000000 ', '13306332736');
INSERT INTO `customer` VALUES ('DBC14714A0116BA6', 'Bernie Vaughan', '0', '51333119950521208X', '13002417890');
INSERT INTO `customer` VALUES ('E2E449898CF960EA', 'Zachary Jordan', '1', '420704000000000000 ', '13803982683');
INSERT INTO `customer` VALUES ('E68B4C7E81C73C9C', 'Gemma Lindberg(h)', '0', '522727000000000000 ', '15208184622');
INSERT INTO `customer` VALUES ('EC24421BAFACEA72', 'Baldwin Lincoln', '1', '522301000000000000 ', '15104248957');
INSERT INTO `customer` VALUES ('F1BF494F9B2A42B6', 'Michell Sassoon', '0', '440115000000000000 ', '13306765435');
INSERT INTO `customer` VALUES ('F71A43199BA04984', 'Tiffany More', '0', '650201000000000000 ', '13008021127');
INSERT INTO `customer` VALUES ('FEBF4CE48E070BB7', 'Angela Billy', '0', '441423000000000000 ', '15104183598');
SET FOREIGN_KEY_CHECKS = 1;
|
Java
|
UTF-8
| 7,799
| 2.109375
| 2
|
[] |
no_license
|
package com.mahdi.sandogh.model.installmentloan.service;
import com.mahdi.sandogh.model.account.Account;
import com.mahdi.sandogh.model.account.service.AccountService;
import com.mahdi.sandogh.model.installmentloan.InstallmentLoan;
import com.mahdi.sandogh.model.installmentloan.dto.InstallmentLoanDto;
import com.mahdi.sandogh.model.installmentloan.dto.InstallmentLoanForm;
import com.mahdi.sandogh.model.installmentloan.dto.ListInstallmentLoanDto;
import com.mahdi.sandogh.model.installmentloan.dto.ResponseIL;
import com.mahdi.sandogh.model.installmentloan.repository.InstallmentLoanRepo;
import com.mahdi.sandogh.model.loan.Loan;
import com.mahdi.sandogh.model.loan.service.LoanService;
import com.mahdi.sandogh.utils.AppConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
@Service
public class InstallmentLoanService {
@Autowired
private InstallmentLoanRepo installmentLoanRepo;
@Autowired
private AccountService accountService;
@Autowired
private LoanService loanService;
public ResponseIL create(InstallmentLoanForm form) {
Optional<Loan> loan = loanService.findById(form.getLoanId());
Optional<Account> account = accountService.findById(form.getAccountId());
if (loan.isPresent() && account.isPresent()) {
InstallmentLoan installmentLoan = new InstallmentLoan();
installmentLoan.setAmountInstallment(form.getAmountInstallment());
installmentLoan.setNumberLoan(form.getNumberLoan());
installmentLoan.setDescription(form.getDescription());
installmentLoan.setCreateBy(form.getCreateBy());
installmentLoan.setAccount(account.get());
installmentLoan.setLoan(loan.get());
installmentLoanRepo.save(installmentLoan);
return ResponseIL.Builder.aResponseIL()
.withMessage(AppConstants.KEY_CREATE_INSTALLMENT_LOAN)
.withStatus(200)
.build();
}
return ResponseIL.Builder.aResponseIL()
.withMessage(AppConstants.KEY_NOT_FOUND_LOAN)
.withStatus(201)
.build();
}
public ResponseIL update(InstallmentLoanForm form) {
Optional<InstallmentLoan> installmentLoan = installmentLoanRepo.findById((form.getInstallmentLoanId()));
if (installmentLoan.isPresent()) {
installmentLoan.get().setAmountInstallment(form.getAmountInstallment());
installmentLoan.get().setNumberLoan(form.getNumberLoan());
installmentLoan.get().setDescription(form.getDescription());
installmentLoan.get().setCreateBy(form.getCreateBy());
// installmentLoan.get().setAccount(installmentLoan.get().getAccount());
// installmentLoan.get().setLoan(installmentLoan.get().getLoan());
installmentLoanRepo.save(installmentLoan.get());
return ResponseIL.Builder.aResponseIL()
.withMessage(AppConstants.KEY_UPDATE_INSTALLMENT_LOAN)
.withStatus(200)
.build();
}
return ResponseIL.Builder.aResponseIL()
.withMessage(AppConstants.KEY_NOT_FOUND_LOAN)
.withStatus(201)
.build();
}
public Optional<InstallmentLoan> findById(Long installmentLoanId) {
Optional<InstallmentLoan> installmentLoan = installmentLoanRepo.findById((installmentLoanId));
if (installmentLoan.isPresent())
return Optional.ofNullable(installmentLoan.get());
else
return Optional.empty();
}
/**
* لیست اقساطی که تا به حال این عضو پرداخت کرده
* @param accountNumber
* @return
*/
public Optional<ListInstallmentLoanDto> findDtoByAccountNumber(String accountNumber) {
Optional<Account> account = accountService.findByAccountNumber(accountNumber);
if (account.isPresent()) {
ListInstallmentLoanDto lilDTO = new ListInstallmentLoanDto();
lilDTO.setStatus(HttpStatus.OK.value());
lilDTO.setMessage(AppConstants.KEY_SUCESSE);
List<InstallmentLoanDto> dtoList = new ArrayList<>();
for (InstallmentLoan installmentLoan : account.get().getInstallmentLoans()) {
InstallmentLoanDto ilDTO = new InstallmentLoanDto();
ilDTO.setInstallmentLoanId(installmentLoan.getId());
ilDTO.setAmountInstallment(installmentLoan.getAmountInstallment());
ilDTO.setNumberLoan(installmentLoan.getNumberLoan());
ilDTO.setDescription(installmentLoan.getDescription());
ilDTO.setCreateBy(installmentLoan.getCreateBy());
ilDTO.setAccountId(installmentLoan.getAccount().getId());
ilDTO.setLoanId(installmentLoan.getLoan().getId());
dtoList.add(ilDTO);
}
lilDTO.setData(dtoList);
return Optional.ofNullable(lilDTO);
}
return Optional.empty();
}
public Optional<ListInstallmentLoanDto> findDtoById(Long installmentLoanId) {
Optional<InstallmentLoan> installmentLoan = installmentLoanRepo.findById((installmentLoanId));
if (installmentLoan.isPresent()) {
ListInstallmentLoanDto lilDTO = new ListInstallmentLoanDto();
lilDTO.setStatus(HttpStatus.OK.value());
lilDTO.setMessage(AppConstants.KEY_SUCESSE);
InstallmentLoanDto ilDTO = new InstallmentLoanDto();
ilDTO.setInstallmentLoanId(installmentLoan.get().getId());
ilDTO.setAmountInstallment(installmentLoan.get().getAmountInstallment());
ilDTO.setNumberLoan(installmentLoan.get().getNumberLoan());
ilDTO.setAccountId(installmentLoan.get().getAccount().getId());
ilDTO.setLoanId(installmentLoan.get().getLoan().getId());
ilDTO.setDescription(installmentLoan.get().getDescription());
ilDTO.setCreateBy(installmentLoan.get().getCreateBy());
lilDTO.setData(Arrays.asList(ilDTO));
return Optional.ofNullable(lilDTO);
}
return Optional.empty();
}
/**
* لیست اقساط براساس شماره وام
* @param loanId
* @return
*/
public Optional<ListInstallmentLoanDto> findAllDtoILLoan(Integer loanId) {
Optional<Loan> list = loanService.findById(loanId);
if (list.isPresent()) {
ListInstallmentLoanDto lilDTO = new ListInstallmentLoanDto();
lilDTO.setStatus(HttpStatus.OK.value());
lilDTO.setMessage(AppConstants.KEY_SUCESSE);
List<InstallmentLoanDto> dtoList = new ArrayList<>();
for (InstallmentLoan installmentLoan : list.get().getInstallmentLoans()) {
InstallmentLoanDto ilDTO = new InstallmentLoanDto();
ilDTO.setInstallmentLoanId(installmentLoan.getId());
ilDTO.setAmountInstallment(installmentLoan.getAmountInstallment());
ilDTO.setNumberLoan(installmentLoan.getNumberLoan());
ilDTO.setAccountId(installmentLoan.getAccount().getId());
ilDTO.setLoanId(installmentLoan.getLoan().getId());
ilDTO.setDescription(installmentLoan.getDescription());
ilDTO.setCreateBy(installmentLoan.getCreateBy());
dtoList.add(ilDTO);
}
lilDTO.setData(dtoList);
return Optional.ofNullable(lilDTO);
}
return Optional.empty();
}
}
|
C
|
UTF-8
| 8,393
| 2.875
| 3
|
[] |
no_license
|
/************************************************************************************
***
*** Copyright 2017 Dell(18588220928@163.com), All Rights Reserved.
***
*** File Author: Dell, Sat Jun 17 11:18:51 CST 2017
***
************************************************************************************/
#include "seam.h"
#define SEAM_LINE_THRESHOLD 2
// a: -1, b: 0, c: 1
static int __abc_index(double a, double b, double c)
{
if (a < b)
return (a < c)? -1 : 1;
// a >= b
return (b < c)? 0 : 1;
}
// a: -1, b: 0
static int __ab_index(double a, double b)
{
return (a < b)? -1 : 0;
}
// b: 0, c: 1
static int __bc_index(double b, double c)
{
return (b < c)? 0 : 1;
}
// Dynamic programming
int *seam_program(MATRIX *mat, int debug)
{
int i, j, index, besti, *C;
double a, b, c, min;
MATRIX *t, *loc; // location for best way
CHECK_MATRIX(mat);
t = matrix_create(mat->m, mat->n); CHECK_MATRIX(t);
loc = matrix_create(mat->m, mat->n); CHECK_MATRIX(loc);
C = (int *)calloc((size_t)mat->n, sizeof(int)); // CHECK_POINT(C);
// Step 1. First column
for (i = 0; i < mat->m; i++)
t->me[i][0] = mat->me[i][0];
// Step 2. t[][j], j >= 2, Second and next columns
for (j = 1; j < mat->n; j++) {
// a) top row, i == 0
i = 0;
b = t->me[i][j - 1] + mat->me[i][j];
c = t->me[i + 1][j - 1] + mat->me[i][j];
index = __bc_index(b, c);
if (index == 0) { // b solution
t->me[i][j] = b;
loc->me[i][j] = i;
}
else { // c solution
t->me[i][j] = c;
loc->me[i][j] = i + 1;
}
// b) midle rows
for (i = 1; i < mat->m - 1; i++) {
a = t->me[i - 1][j - 1] + mat->me[i][j];
b = t->me[i][j - 1] + mat->me[i][j];
c = t->me[i + 1][j - 1] + mat->me[i][j];
index = __abc_index(a, b, c);
if (index == -1) { // a
t->me[i][j] = a;
loc->me[i][j] = i - 1;
}
else if (index == 0) { // b
t->me[i][j] = b;
loc->me[i][j] = i;
}
else { // c
t->me[i][j] = c;
loc->me[i][j] = i + 1;
}
}
// c) bottom row, i == mat->m - 1
i = mat->m - 1;
a = t->me[i - 1][j - 1] + mat->me[i][j];
b = t->me[i][j - 1] + mat->me[i][j];
index = __ab_index(a, b);
if (index == -1) {
t->me[i][j] = a;
loc->me[i][j] = i - 1;
}
else {
t->me[i][j] = b;
loc->me[i][j] = i;
}
}
// Step 3. Check Last row to find best way
besti = 0;
min = t->me[0][t->n - 1];
for (i = 1; i < mat->m; i++) {
if (min > t->me[i][t->n - 1]) {
min = t->me[i][t->n - 1];
besti = i;
}
}
if (debug) {
// printf("Seam Raw Matrix:\n");
// matrix_print(mat, "%lf");
// printf("Time Cost Matrix:\n");
// matrix_print(t, "%lf");
printf("Last Best Path: %d, Min Cost Time: %lf\n", besti, min);
}
// Set best curve to C
i = besti;
C[mat->n - 1] = i;
for (j = mat->n - 1; j >= 1; j--) {
i = (int)loc->me[i][j];
C[j - 1] = i;
}
if (debug) {
for (j = 0; j < mat->n - 1; j++)
printf("%d ", C[j]);
printf("\n");
}
matrix_destroy(loc);
matrix_destroy(t);
return C;
}
// Seam a, b and return best seam line
// -- make sure rect_a, rect_b size is same
// mode: 0-3
int *seam_bestpath(IMAGE *image_a, RECT *rect_a, IMAGE *image_b, RECT *rect_b, int mode)
{
MATRIX *mat; // seam matrix
IMAGE *mask;
double d, r2, x2, slope, bias;
int i, j, a, b, c, *line; // seam line;
CHECK_IMAGE(image_a);
CHECK_IMAGE(image_b);
mat = matrix_create(rect_a->h, rect_a->w); CHECK_MATRIX(mat);
mask = image_create(rect_a->h, rect_a->w); CHECK_IMAGE(mask);
switch(mode) {
case 0: // A, Center = (h, w)
matrix_foreach(mat,i,j) {
// r2 = (i - rect_a->h)*(i - rect_a->h) + (j - rect_a->w)*(j - rect_a->w);
r2 = 1.0f;
a = (image_a->ie[i + rect_a->r][j + rect_a->c].r - image_b->ie[i + rect_b->r][j + rect_b->c].r);
b = (image_a->ie[i + rect_a->r][j + rect_a->c].g - image_b->ie[i + rect_b->r][j + rect_b->c].g);
c = (image_a->ie[i + rect_a->r][j + rect_a->c].b - image_b->ie[i + rect_b->r][j + rect_b->c].b);
x2 = a*a + b*b + c*c;
mat->me[i][j] = r2*x2;
}
break;
case 1: // B, Center = (h, 0)
matrix_foreach(mat,i,j) {
// r2 = (i - rect_a->h)*(i - rect_a->h) + j*j;
r2 = 1.0f;
a = (image_a->ie[i + rect_a->r][j + rect_a->c].r - image_b->ie[i + rect_b->r][j + rect_b->c].r);
b = (image_a->ie[i + rect_a->r][j + rect_a->c].g - image_b->ie[i + rect_b->r][j + rect_b->c].g);
c = (image_a->ie[i + rect_a->r][j + rect_a->c].b - image_b->ie[i + rect_b->r][j + rect_b->c].b);
x2 = a*a + b*b + c*c;
mat->me[i][j] = r2*x2;
}
break;
case 2: // C, Center = (0, w)
matrix_foreach(mat,i,j) {
// r2 = i * i + (j - rect_a->w)*(j - rect_a->w);
r2 = 1.0f;
a = (image_a->ie[i + rect_a->r][j + rect_a->c].r - image_b->ie[i + rect_b->r][j + rect_b->c].r);
b = (image_a->ie[i + rect_a->r][j + rect_a->c].g - image_b->ie[i + rect_b->r][j + rect_b->c].g);
c = (image_a->ie[i + rect_a->r][j + rect_a->c].b - image_b->ie[i + rect_b->r][j + rect_b->c].b);
x2 = a*a + b*b + c*c;
mat->me[i][j] = r2*x2;
}
break;
case 3: // D, Center = (0, 0)
matrix_foreach(mat,i,j) {
// r2 = i*i + j*j;
r2 = 1.0f;
a = (image_a->ie[i + rect_a->r][j + rect_a->c].r - image_b->ie[i + rect_b->r][j + rect_b->c].r);
b = (image_a->ie[i + rect_a->r][j + rect_a->c].g - image_b->ie[i + rect_b->r][j + rect_b->c].g);
c = (image_a->ie[i + rect_a->r][j + rect_a->c].b - image_b->ie[i + rect_b->r][j + rect_b->c].b);
x2 = a*a + b*b + c*c;
mat->me[i][j] = r2*x2;
}
break;
default:
break;
}
line = seam_program(mat, 0);
if (line == NULL) {
syslog_error("Find best seam line.");
matrix_destroy(mat);
return NULL;
}
// Need to line correct ?
// ... (r1, c1) -- (r2, c2) --> k = (r2 - r1)/(c2-c1), b = r2 - k*c2;
switch(mode) {
case 0: // A, Center = (h, w)
b = mat->m - 1 - line[mat->n - 1];
if (b >= SEAM_LINE_THRESHOLD) {
a = MAX((mat->n - b), 0); c = line[a];
slope = mat->m - 1; slope -= c; slope /= b; bias = mat->m - 1 - slope*(mat->n - 1);
for (j = a; j < mat->n - 1; j++) {
d = slope*j + bias;
line[j] = CLAMP((int)d, 0, (mat->m - 1));
}
}
break;
case 1: // B, Center = (h, 0)
b = mat->m - 1 - line[0];
if (b >= SEAM_LINE_THRESHOLD) {
a = MIN((mat->n - 1), b); c = line[a];
slope = c; slope -= (mat->m - 1); slope /= b;
bias = mat->m - 1;
for (j = 0; j < a; j++) {
d = slope*j + bias;
line[j] = CLAMP((int)d, 0, (mat->m - 1));
}
}
break;
case 2: // C, Center = (0, w)
b = line[mat->n - 1];
if (b >= SEAM_LINE_THRESHOLD) {
a = MAX((mat->n - b), 0); c = line[a];
slope = -1.0f*c/b; bias = -slope*(mat->n - 1);
for (j = a; j < mat->n - 1; j++) {
d = slope*j + bias;
line[j] = CLAMP((int)d, 0, (mat->m - 1));
}
}
break;
case 3: // D, Center = (0, 0)
b = line[0];
if (b >= SEAM_LINE_THRESHOLD) {
a = MIN((mat->n - 1), b); c = line[a];
slope = 1.0f*c/b; bias = 0.0f;
for (j = 0; j < a; j++) {
d = slope*j + bias;
line[j] = CLAMP((int)d, 0, (mat->m - 1));
}
}
break;
default:
break;
}
matrix_destroy(mat);
return line;
}
// Seam a, b and save result to mask
// -- make sure rect_a, rect_b size is same
// mode: 0-3
IMAGE *seam_bestmask(IMAGE *image_a, RECT *rect_a, IMAGE *image_b, RECT *rect_b, int mode)
{
IMAGE *mask;
int i, j, *line; // seam line;
CHECK_IMAGE(image_a);
CHECK_IMAGE(image_b);
line = seam_bestpath(image_a, rect_a, image_b, rect_b, mode);
if (! line)
return NULL;
mask = image_create(rect_a->h, rect_a->w); CHECK_IMAGE(mask);
if (mode == 0 || mode == 1) {
// Border Up: a, Down: b
for (j = 0; j < rect_b->w; j++) {
for (i = 0; i < rect_b->h; i++) {
if (i <= line[j])
mask->ie[i][j].r = mask->ie[i][j].g = mask->ie[i][j].b = 255;
else
mask->ie[i][j].r = mask->ie[i][j].g = mask->ie[i][j].b = 0;
}
}
}
else {
// Border Up: b, Down: a
for (j = 0; j < rect_b->w; j++) {
for (i = 0; i < rect_b->h; i++) {
if (i >= line[j])
mask->ie[i][j].r = mask->ie[i][j].g = mask->ie[i][j].b = 255;
else
mask->ie[i][j].r = mask->ie[i][j].g = mask->ie[i][j].b = 0;
}
}
}
free(line);
return mask;
}
int seam_test()
{
int j;
MATRIX *mat = matrix_create(4, 5);
check_matrix(mat);
matrix_pattern(mat, "rand");
int *C = seam_program(mat, 1);
if (C) {
printf("Best Path: ");
for (j = 0; j < mat->n; j++)
printf("%d ", C[j]);
printf("\n");
free(C);
}
matrix_destroy(mat);
return RET_OK;
}
|
Java
|
ISO-8859-1
| 1,827
| 3.25
| 3
|
[] |
no_license
|
package ar.edu.ort.tp1.parcial1.clases;
public abstract class Mascota implements Animal {
private static final String MSG_COM_FELIZ = "He comido demasiado";
private static final String MSG_COM_HAMBRIENTO = "Muchas gracias tena hambre";
private static final String MSG_COM_ENFERMO = "No tena mucha hambre, pero gracias";
private static final int CIEN = 100;
private String nombre;
private int peso;
private Estado estado;
private boolean vacuna;
public Mascota(String nombre, int peso, boolean vacuna, Estado estado) {
this.nombre = nombre;
this.peso = peso;
this.setVacuna(vacuna);
this.setEstado(estado);
}
public void comer(double comida) {
System.out.println("comio");
}
public void comer(double comida, double multiplicador) {
switch (estado) {
case HAMBRIENTO:
System.out.println(MSG_COM_FELIZ);
setEstado(estado.FELIZ);
this.peso = (int) (this.peso + comida * multiplicador);
actualizarPeso(multiplicador);
break;
case FELIZ:
System.out.println(MSG_COM_HAMBRIENTO);
setEstado(estado.ENFERMO);
this.peso = (int) (this.peso + comida * multiplicador);
actualizarPeso(multiplicador);
break;
case ENFERMO:
System.out.println(MSG_COM_ENFERMO);
setEstado(estado.ENFERMO);
this.peso = (int) (this.peso + comida * multiplicador);
actualizarPeso(multiplicador);
default:
break;
}
}
public String getNombre() {
return nombre;
}
public void actualizarPeso(double porcentaje) {
this.peso += peso * porcentaje / CIEN;
}
public boolean isVacuna() {
return vacuna;
}
public void setVacuna(boolean vacuna) {
this.vacuna = vacuna;
}
public Estado getEstado() {
return estado;
}
public void setEstado(Estado estado) {
this.estado = estado;
}
}
|
Markdown
|
UTF-8
| 1,086
| 2.84375
| 3
|
[] |
no_license
|
# Conception
## Cahier de charge
**Un étudiant peut passer zéro au plusieurs examens.**<br/>
**Un examen peut être passé par zéro ou plusieurs étudiants et en indiquant la date d’examen et la note obtenue initialiser à zéro.**<br/>
**Un examen est composé d’un ou plusieurs questionnaires.** <br/>
**Un examen contient un titre et un commentaire et sa date de création, avec le barème et les enseignants qui l’ont créé.**<br/>
**Les questionnaires peuvent appartenir à plusieurs examens.**<br/>
**Un questionnaire contient un titre une description et sa date de création, avec une liste des questions.**<br/>
**Chaque question est composée de l’énoncés et les choix avec les corrigés (les réponses correctes) et les points attribués.** <br/>
**Un questionnaire est créé par un enseignant et l’examen peut être créé que par un enseignant.**<br/>
**Un enseignant peut créer des classes et chaque étudiant peut inscrire aux classes.<br/>**
## Diagrammes de classes

|
C++
|
UTF-8
| 1,623
| 3.0625
| 3
|
[
"MIT"
] |
permissive
|
/* Class for generating cubic splines for smooth interpolation of int values in any 3D colorspace that I have implemented so far.
Uses the Newton algorithm and then horner evaluation for efficient computation */
#ifndef Interpolator_H
#define Interpolator_H
class Interpolator {
private:
// coefficients of the splines. 5 cubic splines for each color entry
double a[5][3], b[5][3], c[5][3], d[5][3];
// The tridiagonal matrix that will be used
double helperMatrixR[30], helperMatrixG[30], helperMatrixB[30];
// x values of the input (colormap)
double xVal[6];
// y value of the input (colormap; 0 = R, 1 = G, 2 = B)
double yVal[6][3];
// interpolated colorvalues
double R, G, B;
public:
static constexpr unsigned int MAX_CONTROL_POINTS = 6;
Interpolator () = default;
// Since this is now Baseclass for rgbCanvas
virtual ~Interpolator () = default;
void setxVal (unsigned int n, double val[]);
void setyValR (unsigned int n, double val[]);
void setyValG (unsigned int n, double val[]);
void setyValB (unsigned int n, double val[]);
void setMAX_CONTROL_POINTS(unsigned int MCP);
double getR ();
double getG ();
double getB ();
unsigned int getMAX_CONTROL_POINTS ();
// Order the data into a tridiagonal matrix
void prepareTridiagMatrix (unsigned int n);
// usual gaussian elimination
void gaussianElimination (unsigned int n, unsigned int m, double matrix[], double vector[]);
// calculate the coefficients
void findSplineCoeffs (unsigned int n);
// evaluate the polynomial for a certain parameter
void hornerEvaluation (unsigned int n, double parameter);
};
#endif
|
C++
|
GB18030
| 3,166
| 2.546875
| 3
|
[] |
no_license
|
#include "gl_gameserver_pch.h"
#include "game_contact_listener.h"
#include "debug_render.h"
#include "gl_gameserver.h"
GameContactListener::GameContactListener(GlGameServer* gs) :
m_GameServer(gs)
{
m_pointCount = 0;
}
void GameContactListener::BeginContact(b2Contact* contact)
{
B2_NOT_USED(contact);
}
void GameContactListener::EndContact(b2Contact* contact)
{
B2_NOT_USED(contact);
}
void GameContactListener::PreSolve(b2Contact* contact, const b2Manifold* oldManifold)
{
const b2Manifold* manifold = contact->GetManifold();
if (manifold->pointCount == 0)
{
return; // ûײ
}
// ײӦfixture
b2Fixture* fixtureA = contact->GetFixtureA();
b2Fixture* fixtureB = contact->GetFixtureB();
// ȡײ״̬
b2PointState state1[b2_maxManifoldPoints], state2[b2_maxManifoldPoints];
b2GetPointStates(state1, state2, oldManifold, manifold);
b2WorldManifold worldManifold;
contact->GetWorldManifold(&worldManifold);
for (int32 i = 0; i < manifold->pointCount && m_pointCount < k_maxContactPoints; ++i)
{
ContactPoint* cp = m_points + m_pointCount;
cp->fixtureA = fixtureA;
cp->fixtureB = fixtureB;
cp->position = worldManifold.points[i];
cp->normal = worldManifold.normal;
cp->state = state2[i];
++m_pointCount;
}
}
void GameContactListener::PostSolve(b2Contact* contact, const b2ContactImpulse* impulse)
{
B2_NOT_USED(contact);
B2_NOT_USED(impulse);
}
void GameContactListener::Reset()
{
m_pointCount = 0;
}
void GameContactListener::DrawContactPoints(Settings* settings)
{
DebugDraw* pDraw = m_GameServer->GetDebugDraw();
if(!pDraw)
return;
const float32 k_axisScale = 0.3f;
for (int32 i = 0; i < m_pointCount; ++i)
{
ContactPoint* point = m_points + i;
if (point->state == b2_addState)
{
// Add
pDraw->DrawPoint(point->position, 10.0f, b2Color(0.3f, 0.95f, 0.3f)); // ײ
}
else if (point->state == b2_persistState)
{
// Persist
pDraw->DrawPoint(point->position, 5.0f, b2Color(0.3f, 0.3f, 0.95f)); // ʾײ
}
// ʾײnormal
if (settings->drawContactNormals == 1)
{
b2Vec2 p1 = point->position;
b2Vec2 p2 = p1 + k_axisScale * point->normal;
pDraw->DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.9f));
}
else if (settings->drawContactForces == 1)
{
//b2Vec2 p1 = point->position;
//b2Vec2 p2 = p1 + k_forceScale * point->normalForce * point->normal;
//m_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f));
}
if (settings->drawFrictionForces == 1)
{
//b2Vec2 tangent = b2Cross(point->normal, 1.0f);
//b2Vec2 p1 = point->position;
//b2Vec2 p2 = p1 + k_forceScale * point->tangentForce * tangent;
//m_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f));
}
}
}
|
C#
|
UTF-8
| 2,876
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace IDevman.SAPConnector.Data.Model
{
/// <summary>
/// Purchase request model
/// </summary>
public class OPRQ
{
/// <summary>
/// Gets document entry
/// </summary>
public int DocEntry { get; set; }
/// <summary>
/// Gets document number
/// </summary>
public int DocNum { get; set; }
/// <summary>
/// Gets user name
/// </summary>
public string ReqName { get; set; }
/// <summary>
/// Gets requester type
/// 12 -> User
/// 171 -> Employee
/// </summary>
public int ReqType { get; set; }
/// <summary>
/// Gets posting date
/// </summary>
public DateTime DocDate { get; set; }
/// <summary>
/// Gets due date
/// </summary>
public DateTime DocDueDate { get; set; }
/// <summary>
/// Gets document date
/// </summary>
public DateTime TaxDate { get; set; }
/// <summary>
/// Gets required date
/// </summary>
public DateTime ReqDate { get; set; }
/// <summary>
/// Gets purchase comments
/// </summary>
public string Comments { get; set; }
/// <summary>
/// Purchase order items related
/// </summary>
public List<PRQ1> Items { get; } = new List<PRQ1>();
/// <summary>
/// Check object equality
/// </summary>
/// <param name="obj">To compare</param>
/// <returns>if is equal</returns>
public override bool Equals(Object obj)
{
if ((obj == null) || !GetType().Equals(obj.GetType()))
{
return false;
}
else
{
OPRQ b = (OPRQ)obj;
return
EqualityComparer<DateTime>.Default.Equals(DocDate, b.DocDate) &&
EqualityComparer<DateTime>.Default.Equals(DocDueDate, b.DocDueDate) &&
EqualityComparer<int>.Default.Equals(DocEntry, b.DocEntry) &&
EqualityComparer<int>.Default.Equals(DocNum, b.DocNum) &&
EqualityComparer<DateTime>.Default.Equals(ReqDate, b.ReqDate) &&
EqualityComparer<string>.Default.Equals(ReqName, b.ReqName) &&
((Items == null && b.Items == null) || Items.SequenceEqual(b.Items));
}
}
/// <summary>
/// Generates hash code
/// </summary>
/// <returns>hash code</returns>
public override int GetHashCode()
{
var hashCode = 2126638501;
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(ReqName);
hashCode = hashCode * -1521134295 + ReqType.GetHashCode();
hashCode = hashCode * -1521134295 + DocEntry.GetHashCode();
hashCode = hashCode * -1521134295 + DocNum.GetHashCode();
hashCode = hashCode * -1521134295 + DocDate.GetHashCode();
hashCode = hashCode * -1521134295 + DocDueDate.GetHashCode();
hashCode = hashCode * -1521134295 + TaxDate.GetHashCode();
hashCode = hashCode * -1521134295 + ReqDate.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<List<PRQ1>>.Default.GetHashCode(Items);
return hashCode;
}
}
}
|
Java
|
UTF-8
| 1,979
| 2.328125
| 2
|
[] |
no_license
|
package cz.skywall.circularnumberpicker.test;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import cz.skywall.circularnumberpicker.CircularNumberPickerView;
import cz.skywall.circularnumberpicker.OnNumberSelectedListener;
public class TestActivity extends Activity implements OnNumberSelectedListener {
CircularNumberPickerView mCircle_1;
CircularNumberPickerView mCircle_2;
CircularNumberPickerView mCircle_3;
CircularNumberPickerView mCircle_4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
mCircle_1 = (CircularNumberPickerView) findViewById(R.id.circle_1);
mCircle_2 = (CircularNumberPickerView) findViewById(R.id.circle_2);
mCircle_3 = (CircularNumberPickerView) findViewById(R.id.circle_3);
mCircle_4 = (CircularNumberPickerView) findViewById(R.id.circle_4);
mCircle_1.setFontSize(40);
mCircle_1.setSnap(true);
mCircle_1.angleCentering(true);
mCircle_1.setCircleStrokeColor(Color.LTGRAY);
mCircle_1.setSelectedItem(10);
mCircle_1.setListener(this);
mCircle_2.setFontSize(60);
mCircle_2.setSnap(true);
mCircle_2.angleCentering(false);
mCircle_2.setSelectedItem(10);
mCircle_2.setListener(this);
mCircle_3.setFontSize(60);
mCircle_3.setSnap(false);
mCircle_3.angleCentering(true);
mCircle_3.setPointerFillColor(Color.BLUE);
mCircle_3.setPointerStrokeColor(Color.BLUE);
mCircle_3.setFontColor(Color.BLUE);
mCircle_3.setSelectedItem(10);
mCircle_3.setListener(this);
mCircle_4.setFontSize(60);
mCircle_4.setSnap(false);
mCircle_4.angleCentering(false);
mCircle_4.setPointerStrokeColor(Color.RED);
mCircle_4.setFontColor(Color.RED);
mCircle_4.setSelectedItem(10);
mCircle_4.setListener(this);
}
@Override
public void onNumberSelected(View view, int value) {
Log.d("TestActivity", String.valueOf(value));
}
}
|
Swift
|
UTF-8
| 10,002
| 3.03125
| 3
|
[] |
no_license
|
//
// Menu.swift
// Resume
//
// Created by Ian MacCallum on 8/4/15.
// Copyright © 2015 Ian MacCallum. All rights reserved.
//
import UIKit
import Foundation
//MARK: Typealiases
typealias Block = () -> ()
typealias SuccessBlock = Bool -> ()
//MARK: Menu Node
class MenuNode: NSObject {
let title: String
let imageName: String?
init(title: String, imageName: String?) {
self.title = title
self.imageName = imageName
super.init()
}
func image() -> UIImage? {
guard let imageName = imageName else { return nil }
return UIImage(named: imageName)
}
}
//MARK: Delegate Protocol
@objc protocol MenuDelegate {
func menu(menu: Menu, didUpdateWithPercent percent: CGFloat)
func menu(menu: Menu, shouldSnapToItemIndex index: Int)
func menu(menu: Menu, didDismissWithIndex index: Int)
}
//MARK: - Data Source Protocol
@objc protocol MenuDataSource {
optional func sizeForIndicatorViewForMenu(menu: Menu) -> CGSize
func presentingViewForMenu(menu: Menu) -> UIView
func numberOfItemsInMenu(menu: Menu) -> Int
func menu(menu: Menu, nodeForItemAtIndex index: Int) -> MenuNode
}
// MARK: - Menu Indicator State
enum MenuState {
case Hidden, Visible, Tracking, Animating
}
//MARK: - Menu
class Menu: NSObject {
private var currentIndex: Int = -1 { didSet { if oldValue != currentIndex { didChangeIndex(currentIndex) } } }
private var presentingView: UIView { return dataSource.presentingViewForMenu(self) }
private var itemCount: Int { return dataSource.numberOfItemsInMenu(self) }
private let dataSource: MenuDataSource
weak var delegate: MenuDelegate?
private var menuTopEdgeConstraint: NSLayoutConstraint?
private var indicatorView: MenuIndicatorView!
private var panOriginalCenterY: CGFloat = 0
private var menuOriginalY: CGFloat = 0
private var menuView: UIView!
private var tracking = false
init(dataSource: MenuDataSource) {
self.dataSource = dataSource
super.init()
addIndicator()
}
private func addIndicator() {
// Instantiate Indicator
indicatorView = MenuIndicatorView(size: CGSizeMake(48, 48), shapeColor: UIColor.whiteColor())
let minimum = presentingView.frame.height / CGFloat(2 * itemCount)
indicatorView.updateCenterY(minimum)
indicatorView.addInView(presentingView)
presentingView.bringSubviewToFront(indicatorView)
// Handle Gestures
let panGesture = UIPanGestureRecognizer(target: self, action: "handlePan:")
indicatorView.addGestureRecognizer(panGesture)
let tapGesture = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
indicatorView.addGestureRecognizer(tapGesture)
// Update Contraints
presentingView.translatesAutoresizingMaskIntoConstraints = false
presentingView.needsUpdateConstraints()
showIndicator()
}
// Handle Gestures
func handleTap(sender: UIGestureRecognizer){
}
func handlePan(sender: UIPanGestureRecognizer) {
let dy = sender.translationInView(presentingView).y
let y = panOriginalCenterY + dy
let h = presentingView.frame.height
let minimum = h / CGFloat(2 * itemCount)
let maximum = CGFloat(2 * itemCount - 1) * minimum
let percent = (y - minimum) / (maximum - minimum)
let index = indexForPercent(percent)
if sender.state == .Began {
panOriginalCenterY = sender.locationInView(presentingView).y - sender.locationInView(indicatorView).y + indicatorView.frame.height / 2
tracking = true
} else if sender.state == .Changed {
currentIndex = index
indicatorView.updateCenterY(y)
delegate?.menu(self, didUpdateWithPercent: percent)
} else if sender.state == .Ended || sender.state == .Cancelled {
tracking = false
delegate?.menu(self, shouldSnapToItemIndex: index)
} else {
tracking = false
}
}
func shouldSnapToItemIndex(index: Int) {
}
func didChangeIndex(index: Int) {
let image = dataSource.menu(self, nodeForItemAtIndex: index).image()
indicatorView.updateImage(image)
}
func indexForPercent(percent: CGFloat) -> Int {
let page = max(min(1, percent), 0)
return Int(round(page * CGFloat(itemCount - 1)))
}
func handleScroll<T: UIScrollView>(sender: T?) {
guard !tracking, let sender = sender else { return }
let percent = sender.contentOffset.y / (sender.contentSize.height - sender.frame.height)
let minimum = presentingView.frame.height / CGFloat(2 * itemCount)
let maximum = CGFloat(2 * itemCount - 1) * minimum
let offset = minimum + percent * (maximum - minimum)
let index = indexForPercent(percent)
indicatorView.updateCenterY(offset)
currentIndex = index
}
func showIndicator(animated: Bool = false) {
indicatorView.show(animated)
}
func hideIndicator(animated: Bool = false) {
indicatorView.hide(animated)
}
// MARK: - Constraints
private func getEqualConstraint(item: AnyObject, toItem: AnyObject, attribute: NSLayoutAttribute) -> NSLayoutConstraint{
return NSLayoutConstraint(item: item, attribute: attribute, relatedBy: .Equal, toItem: toItem, attribute: attribute, multiplier: 1, constant: 0)
}
}
//MARK: - IndicatorView Class
class MenuIndicatorView: UIView {
private var edgeConstraint: NSLayoutConstraint?
private var topConstraint: NSLayoutConstraint?
private var state: MenuState = .Hidden
private let imageView = UIImageView()
private var shapeColor: UIColor
private var size: CGSize
init(size:CGSize, shapeColor: UIColor) {
self.size = size
self.shapeColor = shapeColor
super.init(frame: CGRectMake(0, 0, size.width, size.height))
self.translatesAutoresizingMaskIntoConstraints = false
self.backgroundColor = UIColor.clearColor()
// let diamond = ShapeLayer(type: .Diamond, inTileRect: bounds, size: .M, color: UIColor.whiteColor())
// layer.addSublayer(diamond)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(frame: CGRect) {
super.drawRect(frame)
}
//MARK: - Indicator methods
func addInView(hostView:UIView) {
hostView.addSubview(self)
hostView.bringSubviewToFront(self)
frame = CGRect(x: 64, y: 64, width: 64, height: 64)
topConstraint = NSLayoutConstraint(item: self, attribute: .Top, relatedBy: .Equal, toItem: hostView, attribute: .Top, multiplier: 1, constant: 0)
//hide the indicator, will appear from the outside of the screen
edgeConstraint = NSLayoutConstraint(item: self, attribute: .Trailing, relatedBy: .Equal, toItem: hostView, attribute: .Trailing, multiplier: 1, constant: 0)
hostView.addConstraints([
edgeConstraint!,
NSLayoutConstraint(item: self, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: size.width),
NSLayoutConstraint(item: self, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: size.height),
topConstraint!
])
hostView.layoutIfNeeded()
//add Icon imageView
imageView.contentMode = UIViewContentMode.ScaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false
addSubview(imageView)
//constraints for imageView
self.addConstraints([
NSLayoutConstraint(item: imageView, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1, constant: 10),
NSLayoutConstraint(item: imageView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 24),
NSLayoutConstraint(item: imageView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 24),
NSLayoutConstraint(item: imageView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0),
])
imageView.layoutIfNeeded()
}
func updateCenterY(y: CGFloat) {
let adjustedY = y - size.height / 2
topConstraint?.constant = adjustedY
superview?.layoutIfNeeded()
}
///Hides the indicator
func hide(animated: Bool) {
state = .Animating
animateX(frame.width, duration: animated ? 0.2 : 0) { success in
self.hidden = true
self.state = .Hidden
}
}
///Shows the indicator
func show(animated: Bool){
state = .Animating
self.hidden = false
animateX(0, duration: animated ? 0.2 : 0) { success in
self.state = .Visible
}
}
func animateX(constant: CGFloat, duration: NSTimeInterval, completion: SuccessBlock? = nil) {
edgeConstraint?.constant = constant
UIView.animateWithDuration(duration, delay: 0, options: .CurveEaseOut, animations: {
self.superview?.layoutIfNeeded()
}) { success in
completion?(success)
}
}
func updateImage(image: UIImage?) {
let transition = CATransition()
transition.duration = 0.2
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
transition.type = kCATransitionFade
imageView.layer.addAnimation(transition, forKey: nil)
imageView.image = image
}
}
|
TypeScript
|
UTF-8
| 3,286
| 2.640625
| 3
|
[] |
no_license
|
import { Request } from "express"
import asyncHandler from "express-async-handler"
import Question, { QuestionSchema } from "../models/questionModel"
import { UserSchema } from "../models/userModel"
interface UserRequest extends Request {
user: UserSchema
}
// SECTION: Get all questions
// @route: GET /api/questions/all
// @access: Private
export const getQuestions = asyncHandler(async (req, res) => {
const pageSize = 5
const page = Number(req.query.page) || 1
const keyword = req.query.keyword
? {
question: { $regex: `${req.query.keyword}`, $options: "i" },
}
: {}
const count = await Question.countDocuments(keyword)
const questions = await Question.find(keyword)
.sort({ upVotes: -1, downVotes: -1 })
.limit(pageSize)
.skip(pageSize * (page - 1))
return res.json({ questions, page, pageCount: Math.ceil(count / pageSize) })
})
// SECTION: Get question by id
// @route: GET /api/questions
// @access: Private
export const getQuestionById = asyncHandler(async (req, res) => {
const question = await Question.findById(req.params.id).populate(
"user",
"username name"
)
return res.json(question)
})
// SECTION: Get a random question
// @route: GET /api/questions
// @access: Private
export const getRandomQuestion = asyncHandler(async (req, res) => {
const questions = await Question.aggregate([{ $sample: { size: 1 } }])
const question = await Question.findById(questions[0]._id).populate(
"user",
"username name"
)
return res.json(question)
})
// SECTION: Add a question
// @route: PUT /api/questions
// @access: Private
export const addQuestion = asyncHandler(async (req: UserRequest, res) => {
const user = req.user
const { question } = req.body
const newQuestion = await Question.create({ user: user._id, question })
console.log(newQuestion)
req.user.questions.push(newQuestion._id)
await req.user.save()
return res.status(201).json(newQuestion)
})
// SECTION: Delete a question
// @route: DELETE /api/questions
// @access: Private
export const deleteQuestion = asyncHandler(async (req: UserRequest, res) => {
const user = req.user
const question = await Question.findById(req.params.id)
if (!question) {
res.status(404).json({ message: "No question found" })
return
}
if (question.user.toString() !== user._id.toString() && !user.isAdmin) {
res.status(401).json({ message: "You cannot delete this question" })
return
}
question.remove()
return res.json({ message: "Question deleted" })
})
// SECTION: Add vote
// @route: PUT /api/questions/vote
// @access: Private
export const addVote = asyncHandler(async (req: UserRequest, res) => {
const { id, vote } = req.body
const question = await Question.findById(id).populate("user", "username name")
if (!question) {
res.status(401).json({ message: "No matching questions" })
return
}
switch (vote) {
case "UP": {
question.upVotes = question.upVotes + 1
await question.save()
res.status(201).json(question)
return
}
case "DOWN": {
question.downVotes = question.downVotes + 1
await question.save()
res.status(201).json(question)
return
}
default: {
res.status(201).json(question)
}
}
})
|
Python
|
UTF-8
| 903
| 3.125
| 3
|
[] |
no_license
|
from turntablecontrol import TurnTableControl # to control motor
from time import sleep, perf_counter # for waiting and time measure
import numpy as np # for array math
import matplotlib.pyplot as plt # for plotting
motor = TurnTableControl('/dev/tty.usbserial', tableGearRatio=1) # test motor only
data = np.zeros((100, 3)) # prepare data
# speed-up
motor.setSpeed(1000)
sleep(3)
# slow down
motor.setSpeed(1)
# start measure
startTime = perf_counter()
motor.position = 0
for iData in range(data.shape[0]):
data[iData, 1] = motor.position
data[iData, 2] = motor.rate
data[iData, 0] = perf_counter()-startTime
sleep(0.1)
motor.setSpeed(0)
# prepare figure
_, ax = plt.subplots(figsize=(10, 8))
# plot
ax.plot(data[:, 0], data[:, 1], label='position [deg]')
ax.plot(data[:, 0], data[:, 2], label='rate [deg/s]')
# annotate
ax.set_xlabel('time [s]')
ax.grid()
ax.legend()
plt.show()
|
Java
|
UTF-8
| 1,664
| 3.109375
| 3
|
[] |
no_license
|
package Kiszel.Daniel.Game;
import Kiszel.Daniel.Shapes.ListCubes;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class Window implements MouseListener {
private JFrame frame;
private Canvas canvas;
private String title;
private int width, height;
public boolean clicked;
public Window(String ti, int wi, int he){
this.title = ti;
this.width = wi;
this.height = he;
createDisplay();
}
private void createDisplay() {
frame = new JFrame(title);
frame.setSize(width, height);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
canvas = new Canvas();
canvas.setPreferredSize(new Dimension(width,height));
canvas.setMaximumSize(new Dimension(width,height));
canvas.setMinimumSize(new Dimension(width,height));
canvas.setFocusable(false);
canvas.addMouseListener(this);
frame.add(canvas);
frame.pack();
}
public Canvas getCanvas(){
return canvas;
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
clicked = true;
}
@Override
public void mouseReleased(MouseEvent e) {
clicked = false;
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
public boolean isClicked() {
return clicked;
}
}
|
Ruby
|
UTF-8
| 2,210
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
class ATSPI::Accessible
# Wraps libatspi's AtspiSelection[https://developer.gnome.org/libatspi/stable/libatspi-atspi-selection.html]
# together with parts of {Children} and {Children::Selected}
module Selectable
# @!group Attributes & States
# Checks if it can be selected. Accessibles which parent's native
# implements the {https://developer.gnome.org/libatspi/stable/AtspiAccessible.html#atspi-accessible-get-selection selection interface}
# are selectable.
#
# @return [true, false]
def selectable?
parent.children.selectable?
end
# @!endgroup
# @!group Actions
# Selects it
# @return [true, false] indicating success of the operation. +false+ if its
# parent does not implement the {https://developer.gnome.org/libatspi/stable/AtspiAccessible.html#atspi-accessible-get-selection selection interface}.
#
# @see https://developer.gnome.org/libatspi/stable/libatspi-atspi-selection.html#atspi-selection-select-child atspi_selection_select_child
def select
selectable? and parent.__send__(:native).select_child(index_in_parent)
end
# Deselects it
# @return [true, false] indicating success of the operation. +false+ if its
# parent does not implement the {https://developer.gnome.org/libatspi/stable/AtspiAccessible.html#atspi-accessible-get-selection selection interface}.
#
# @see https://developer.gnome.org/libatspi/stable/libatspi-atspi-selection.html#atspi-selection-deselect-child atspi_selection_deselect_child
def deselect
selectable? and parent.__send__(:native).deselect_child(index_in_parent)
end
# @!endgroup
# @!group Attributes & States
# Checks if it currently is selected
# @return [true, false] +false+ if its
# parent does not implement the {https://developer.gnome.org/libatspi/stable/AtspiAccessible.html#atspi-accessible-get-selection selection interface}.
#
# @see https://developer.gnome.org/libatspi/stable/libatspi-atspi-selection.html#atspi-selection-is-child-selected atspi_selection_is_child_selected
def selected?
selectable? and parent.__send__(:native).is_child_selected(index_in_parent)
end
# @!endgroup
end
end
|
TypeScript
|
UTF-8
| 2,668
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
import * as doms from "../../shared/utils/dom";
interface Point {
x: number;
y: number;
}
const hintPosition = (element: Element): Point => {
const { left, top, right, bottom } = doms.viewportRect(element);
if (element.tagName !== "AREA") {
return { x: left, y: top };
}
return {
x: (left + right) / 2,
y: (top + bottom) / 2,
};
};
export default abstract class Hint {
private hint: HTMLElement;
private tag: string;
constructor(target: HTMLElement, tag: string) {
this.tag = tag;
const doc = target.ownerDocument;
if (doc === null) {
throw new TypeError("ownerDocument is null");
}
const { x, y } = hintPosition(target);
const { scrollX, scrollY } = window;
const hint = doc.createElement("span");
hint.className = "vimvixen-hint";
hint.textContent = tag;
hint.style.left = x + scrollX + "px";
hint.style.top = y + scrollY + "px";
doc.body.append(hint);
this.hint = hint;
this.show();
}
show(): void {
this.hint.style.display = "inline";
}
hide(): void {
this.hint.style.display = "none";
}
remove(): void {
this.hint.remove();
}
getTag(): string {
return this.tag;
}
}
export class LinkHint extends Hint {
private target: HTMLAnchorElement | HTMLAreaElement;
constructor(target: HTMLAnchorElement | HTMLAreaElement, tag: string) {
super(target, tag);
this.target = target;
}
getLink(): string {
return this.target.href;
}
getLinkTarget(): string | null {
return this.target.getAttribute("target");
}
click(): void {
this.target.click();
}
}
export class InputHint extends Hint {
private target: HTMLElement;
constructor(target: HTMLElement, tag: string) {
super(target, tag);
this.target = target;
}
activate(): void {
const target = this.target;
switch (target.tagName.toLowerCase()) {
case "input":
switch ((target as HTMLInputElement).type) {
case "file":
case "checkbox":
case "radio":
case "submit":
case "reset":
case "button":
case "image":
case "color":
return target.click();
default:
return target.focus();
}
case "textarea":
return target.focus();
case "button":
case "summary":
return target.click();
default:
if (doms.isContentEditable(target)) {
return target.focus();
} else if (
target.hasAttribute("tabindex") ||
target.hasAttribute("onclick")
) {
return target.click();
}
}
}
}
|
Java
|
UTF-8
| 444
| 1.8125
| 2
|
[] |
no_license
|
package net.siekiera.mgc.dao;
import net.siekiera.mgc.model.CenyWalut;
import net.siekiera.mgc.model.Currency;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by eric on 16.05.2016.
*/
@Transactional
public interface CenyWalutDao extends CrudRepository<CenyWalut, Integer> {
List<CenyWalut> findFirstByOrderByIdDesc();
}
|
Java
|
UTF-8
| 10,461
| 2.640625
| 3
|
[] |
no_license
|
package de.toboxos.abi;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridLayout;
import javax.swing.JList;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.awt.event.ActionEvent;
import javax.imageio.ImageIO;
import javax.swing.AbstractListModel;
import javax.swing.DefaultListModel;
import java.awt.GridBagLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.JLabel;
import javax.swing.event.ListSelectionListener;
import de.toboxos.abi.cards.Card;
import de.toboxos.abi.cards.CardGenerator;
import javax.swing.event.ListSelectionEvent;
public class ChooseDeck extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JList<String> listCards;
private JList<String> listDeck;
private MyListModel<String> cardsModel;
private DefaultListModel<String> deckModel;
ChooseDeck instance = null;
private Runnable callback;
private JLabel lblCount;
private Card showCard;
private JButton btnAdd;
private JButton btnRem;
private String[] cards = new String[] {"Georg", "Axel", "General", "Arwen", "Cooper", "Flamur", "Daniel", "Emilia", "Felix", "Manu", "Felix G.", "Dubowy", "Steffen", "Franzi", "Marike", "Nils", "Sandro", "Zelenka", "Allgeier", "Taraschewski", "Forstner", "Schellmann", "Wiech", "Tornau", "Kreuzer", "Mischo"};
private int[] amount = new int[] { 3, 3, 3, 3, 2, 2, 3, 3, 3, 4, 3, 3, 2, 4, 3, 3, 2, 2, 4, 4, 3, 4, 2, 4, 2, 4};
private JLabel lblNewLabel;
private JLabel lblNewLabel_1;
private JLabel lblNewLabel_2;
private JLabel lblNewLabel_3;
private JLabel lblNewLabel_4;
private JLabel lblNewLabel_5;
private JLabel lblNewLabel_6;
private JLabel lblNewLabel_7;
private JLabel lblNewLabel_8;
@Override
public void paint(Graphics g) {
super.paint(g);
if( showCard == null ) return;
int x = listDeck.getX() - listCards.getWidth() + 20;
int width = listDeck.getX() - x - 20;
int y = 70;
showCard.drawCard((Graphics2D) g, x, y, width, showCard.getHeight(width));
}
/**
* Create the frame.
*/
public ChooseDeck() {
setResizable(false);
setTitle("Deck w\u00E4hlen");
instance = this;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 500, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new GridLayout(1, 0, 0, 0));
cardsModel = new MyListModel<String>();
for( int i = 0; i < cards.length; i++ ) {
cardsModel.addElement(cards[i] + " (" + amount[i] + ")");
}
listCards = new JList<String>();
listCards.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int index = listCards.getSelectedIndex();
showCard = CardGenerator.getCardFromName( cards[index] );
repaint();
}
});
listCards.setModel(cardsModel);
contentPane.add(listCards);
JPanel panel = new JPanel();
contentPane.add(panel);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{79, 0, 79, 0};
gbl_panel.rowHeights = new int[]{37, 205, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_panel.columnWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
btnAdd = new JButton("Add ->");
btnAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int index = listCards.getSelectedIndex();
if( amount[index] == 0 ) return;
if( deckModel.size() == 30 ) return;
amount[index]--;
deckModel.addElement(cards[index]);
cardsModel.setElement(index, cards[index] + " (" + amount[index] + ")");
lblCount.setText("" + deckModel.size() + " / 30");
repaint();
}
});
lblCount = new JLabel("0 / 30");
GridBagConstraints gbc_lblCount = new GridBagConstraints();
gbc_lblCount.insets = new Insets(0, 0, 5, 5);
gbc_lblCount.gridx = 1;
gbc_lblCount.gridy = 0;
panel.add(lblCount, gbc_lblCount);
GridBagConstraints gbc_btnAdd = new GridBagConstraints();
gbc_btnAdd.fill = GridBagConstraints.BOTH;
gbc_btnAdd.insets = new Insets(0, 0, 5, 5);
gbc_btnAdd.gridx = 1;
gbc_btnAdd.gridy = 2;
panel.add(btnAdd, gbc_btnAdd);
btnRem = new JButton("<- Remove");
btnRem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for( int i = 0; i < cards.length; i++ ) {
if( cards[i] == listDeck.getSelectedValue() ) {
amount[i]++;
cardsModel.setElement(i, cards[i] + " (" + amount[i] + ")");
break;
}
}
deckModel.removeElement( listDeck.getSelectedValue() );
lblCount.setText("" + deckModel.size() + " / 30");
repaint();
}
});
GridBagConstraints gbc_btnRem = new GridBagConstraints();
gbc_btnRem.insets = new Insets(0, 0, 5, 5);
gbc_btnRem.fill = GridBagConstraints.BOTH;
gbc_btnRem.gridx = 1;
gbc_btnRem.gridy = 3;
panel.add(btnRem, gbc_btnRem);
JButton btnFertig = new JButton("Fertig");
btnFertig.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
callback.run();
}
});
GridBagConstraints gbc_btnFertig = new GridBagConstraints();
gbc_btnFertig.insets = new Insets(0, 0, 5, 5);
gbc_btnFertig.gridx = 1;
gbc_btnFertig.gridy = 4;
panel.add(btnFertig, gbc_btnFertig);
lblNewLabel = new JLabel(" ");
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel.gridx = 1;
gbc_lblNewLabel.gridy = 5;
panel.add(lblNewLabel, gbc_lblNewLabel);
lblNewLabel_1 = new JLabel(" ");
GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
gbc_lblNewLabel_1.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_1.gridx = 1;
gbc_lblNewLabel_1.gridy = 6;
panel.add(lblNewLabel_1, gbc_lblNewLabel_1);
lblNewLabel_2 = new JLabel(" ");
GridBagConstraints gbc_lblNewLabel_2 = new GridBagConstraints();
gbc_lblNewLabel_2.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_2.gridx = 1;
gbc_lblNewLabel_2.gridy = 7;
panel.add(lblNewLabel_2, gbc_lblNewLabel_2);
lblNewLabel_3 = new JLabel(" ");
GridBagConstraints gbc_lblNewLabel_3 = new GridBagConstraints();
gbc_lblNewLabel_3.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_3.gridx = 1;
gbc_lblNewLabel_3.gridy = 8;
panel.add(lblNewLabel_3, gbc_lblNewLabel_3);
lblNewLabel_4 = new JLabel(" ");
GridBagConstraints gbc_lblNewLabel_4 = new GridBagConstraints();
gbc_lblNewLabel_4.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_4.gridx = 1;
gbc_lblNewLabel_4.gridy = 9;
panel.add(lblNewLabel_4, gbc_lblNewLabel_4);
lblNewLabel_5 = new JLabel(" ");
GridBagConstraints gbc_lblNewLabel_5 = new GridBagConstraints();
gbc_lblNewLabel_5.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_5.gridx = 1;
gbc_lblNewLabel_5.gridy = 10;
panel.add(lblNewLabel_5, gbc_lblNewLabel_5);
lblNewLabel_6 = new JLabel(" ");
GridBagConstraints gbc_lblNewLabel_6 = new GridBagConstraints();
gbc_lblNewLabel_6.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_6.gridx = 1;
gbc_lblNewLabel_6.gridy = 11;
panel.add(lblNewLabel_6, gbc_lblNewLabel_6);
lblNewLabel_7 = new JLabel(" ");
GridBagConstraints gbc_lblNewLabel_7 = new GridBagConstraints();
gbc_lblNewLabel_7.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_7.gridx = 1;
gbc_lblNewLabel_7.gridy = 12;
panel.add(lblNewLabel_7, gbc_lblNewLabel_7);
lblNewLabel_8 = new JLabel(" ");
GridBagConstraints gbc_lblNewLabel_8 = new GridBagConstraints();
gbc_lblNewLabel_8.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_8.gridx = 1;
gbc_lblNewLabel_8.gridy = 13;
panel.add(lblNewLabel_8, gbc_lblNewLabel_8);
JButton btnBilderSpeichern = new JButton("Bilder speichern");
btnBilderSpeichern.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
for( String name : Abi.allCards ) {
Card c = CardGenerator.getCardFromName(name);
BufferedImage bi = new BufferedImage(650, c.getHeight(650), BufferedImage.TYPE_INT_RGB);
c.drawCard((Graphics2D) bi.getGraphics(), 75, 75, 500, c.getHeight(500));
try {
ImageIO.write(bi, "jpg", new File(name + ".jpg"));
System.out.println("Saved " + name);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
GridBagConstraints gbc_btnBilderSpeichern = new GridBagConstraints();
gbc_btnBilderSpeichern.insets = new Insets(0, 0, 0, 5);
gbc_btnBilderSpeichern.gridx = 1;
gbc_btnBilderSpeichern.gridy = 16;
panel.add(btnBilderSpeichern, gbc_btnBilderSpeichern);
deckModel = new DefaultListModel<String>();
listDeck = new JList<String>();
listDeck.setModel(deckModel);
contentPane.add(listDeck);
}
public void setCallback(Runnable r) {
this.callback = r;
}
public List<String> getDeck() {
List<String> l = new ArrayList<>();
for( int i = 0; i < deckModel.size(); i++ ) {
l.add(deckModel.get(i));
}
return l;
}
private class MyListModel<E> extends AbstractListModel<E>{
/**
*
*/
private static final long serialVersionUID = 1L;
private List<E> elements = new ArrayList<>();
@Override
public E getElementAt(int index) {
return elements.get(index);
}
@Override
public int getSize() {
return elements.size();
}
public void setElement(int index, E element) {
elements.set(index, element);
}
public void addElement(E element) {
elements.add(element);
}
}
}
|
C++
|
UTF-8
| 1,020
| 2.78125
| 3
|
[] |
no_license
|
#ifndef DCMAET_H
#define DCMAET_H
#include <iostream>
#include <string.h>
#include <settings/MPSSystemSettings.h>
using namespace std;
class DcmAET
{
private:
string m_aet;
string m_hostname;
int m_port;
public:
DcmAET(const string& aet, const string& hostname, int port);
DcmAET(const DcmAET& aet);
DcmAET();
inline void setAet(const string& aet){this->m_aet = aet;}
inline void setHostname(const string& hostname) {this->m_hostname = hostname;}
void setPort(int port) {this->m_port = port;}
string aet() const {return this->m_aet;}
string hostname() const {return this->m_hostname;}
int port() const {return this->m_port;}
void print() const;
static bool validateAetSettingValue(char* aetSettingVal,
string& aetVal,
string& hostVal,
int& portVal);
string toString() const;
virtual ~DcmAET(){};
};
#endif // DCMAET_H
|
Markdown
|
UTF-8
| 3,141
| 2.59375
| 3
|
[
"Apache-2.0",
"CC-BY-3.0"
] |
permissive
|
---
layout: post
title: Usa Lighthouse para los presupuestos de rendimiento
authors:
- katiehempenius
description: |2-
Lighthouse ahora admite presupuestos de rendimiento. Esta función, LightWallet, se puede instalar en menos de cinco minutos y proporciona información sobre el tamaño y la cantidad de recursos de la página.
date: 2019-06-14
updated: 2020-04-03
tags:
- blog
- performance
---
[Lighthouse](https://github.com/GoogleChrome/lighthouse) ahora admite presupuestos de rendimiento. Esta función, [LightWallet](https://developers.google.com/web/tools/lighthouse/audits/budgets), se puede instalar en menos de cinco minutos y proporciona información sobre el tamaño y la cantidad de recursos de la página.
## Instalar Lighthouse
LightWallet está disponible en la versión de línea de comandos de Lighthouse v5+.
Para comenzar, instala Lighthouse:
```bash
npm install -g lighthouse
```
## Crea un presupuesto
Crea un archivo llamado `budget.json`. En este archivo, agrega el JSON a continuación:
```json
[
{
"path": "/*",
"timings": [
{
"metric": "interactive",
"budget": 3000
},
{
"metric": "first-meaningful-paint",
"budget": 1000
}
],
"resourceSizes": [
{
"resourceType": "script",
"budget": 125
},
{
"resourceType": "total",
"budget": 300
}
],
"resourceCounts": [
{
"resourceType": "third-party",
"budget": 10
}
]
}
]
```
Este archivo de ejemplo `budget.json` establece cinco presupuestos separados:
- Un presupuesto de 3000ms para Time to Interactive (TTI): Tiempo para interactuar.
- Un presupuesto de 1000 ms para First Meaningful Paint (FMP): Primera pintura significativa.
- Un presupuesto de 125 KB para la cantidad total de JavaScript en la página.
- Un presupuesto de 300 KB para el tamaño total de la página.
- Un presupuesto de 10 solicitudes por el número de consultas realizadas a orígenes de terceros.
Para obtener una lista completa de las métricas de rendimiento y los tipos de recursos admitidos, consulta la sección [Presupuestos de rendimiento](https://github.com/GoogleChrome/lighthouse/blob/master/docs/performance-budgets.md) de la documentación de Lighthouse.
## Ejecutar Lighthouse
Ejecuta Lighthouse con la bandera de `--budget-path`. Esta bandera le dice a Lighthouse la ubicación de tu archivo de presupuesto.
```bash
lighthouse https://example.com --budget-path=./budget.json
```
{% Aside %} **Nota**: No es necesario que un archivo de presupuesto se llame `budget.json`. {% endAside %}
## Ver los resultados
Si LightWallet se ha configurado correctamente, el informe Lighthouse contendrá una sección de **Presupuestos** dentro de la categoría de **Rendimiento**.
{% Img src="image/admin/FdUeI8rKZtJB3Ol624S3.png", alt="Sección de 'Presupuestos' del informe Lighthouse", width="800", height="289" %}
En la versión JSON del informe Lighthouse, los resultados de Lightwallet se pueden encontrar dentro de los hallazgos de la auditoría para la auditoría de `performance-budget`.
|
Java
|
UTF-8
| 10,354
| 2.25
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package AppDisplay;
import BiologicalPark.ClientDAOJson;
import BiologicalPark.GestorPercurso;
import BiologicalPark.InterestPoint;
import Documents.Invoice;
import Statistics.Statistics;
import Documents.Ticket;
import com.google.zxing.WriterException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
/**
* Janela de dialogo para compra de bilhetes.
* @author André Reis 170221035 e Bruno Alves 170221041
*/
public class BuyTicketDialog extends Stage {
private int quantity;
public BuyTicketDialog(Scene scene){
GestorPercurso gp = GestorPercurso.getInstance();
quantity = 1;
//Labels
Label lbl = new Label("Confirm your informations para a fatura");
lbl.setStyle( "-fx-font-weight: bold;" + "-fx-font-size: 14;" );
Label nameLbl = new Label("Name");
Label addressLbl = new Label("Address *");
Label cityLbl = new Label("City *");
Label countryLbl = new Label("Country *");
Label postalCodeLbl = new Label("PostalCode *");
Label nifLbl = new Label("NIF");
Label ticketsQuantityLbl = new Label("Number of tickets ");
//Info TextBoxes
TextField nameField = new TextField(gp.getClient().getName());
TextField addressField = new TextField(gp.getClient().getAddress());
TextField cityField = new TextField(gp.getClient().getCity());
TextField countryField = new TextField(gp.getClient().getCountry());
TextField postalCodeField = new TextField(gp.getClient().getPostalCode());
TextField nifField = new TextField(gp.getClient().getNif());
//ComboBox Quantity
ComboBox<Integer> quantityCB = new ComboBox<>(FXCollections.observableArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
quantityCB.getSelectionModel().select(0);
//Grid com info do client
GridPane clientInfoGrid = new GridPane();
clientInfoGrid.setPadding(new Insets(10));
clientInfoGrid.setHgap(10);
clientInfoGrid.setVgap(10);
clientInfoGrid.setAlignment(Pos.CENTER);
clientInfoGrid.add(nameLbl, 0, 0);
clientInfoGrid.add(addressLbl, 0, 1);
clientInfoGrid.add(cityLbl, 0, 2);
clientInfoGrid.add(countryLbl, 0, 3);
clientInfoGrid.add(postalCodeLbl, 0, 4);
clientInfoGrid.add(nifLbl, 0, 5);
clientInfoGrid.add(ticketsQuantityLbl, 0, 6);
clientInfoGrid.add(nameField, 1, 0);
clientInfoGrid.add(addressField, 1, 1);
clientInfoGrid.add(cityField, 1, 2);
clientInfoGrid.add(countryField, 1, 3);
clientInfoGrid.add(postalCodeField, 1, 4);
clientInfoGrid.add(nifField, 1, 5);
clientInfoGrid.add(quantityCB, 1, 6);
Button confirmBtn = new Button("Confirm");
//VBox principal
VBox vb = new VBox();
vb.setPadding(new Insets(10));
vb.setSpacing(10);
vb.setAlignment(Pos.CENTER);
vb.getChildren().addAll(lbl, clientInfoGrid, confirmBtn);
//Show window
setResizable(false);
initStyle(StageStyle.UTILITY);
initModality(Modality.APPLICATION_MODAL);
setIconified(false);
centerOnScreen();
setTitle("Buy ticket");
Scene dialogScene = new Scene(vb, 600, 600);
setScene(dialogScene);
show();
//ação do butão de confirmação
confirmBtn.setOnAction(e -> {
if(addressField.getText().isEmpty() || cityField.getText().isEmpty() || countryField.getText().isEmpty() || postalCodeField.getText().isEmpty()){
new MessageDialog("Please fill in the required fields");
}else{
gp.getClient().setName(nameField.getText());
gp.getClient().setAddress(addressField.getText());
gp.getClient().setCity(cityField.getText());
gp.getClient().setCountry(countryField.getText());
gp.getClient().setPostalCode(postalCodeField.getText());
gp.getClient().setNif(nifField.getText());
quantity = quantityCB.getSelectionModel().getSelectedItem();
paymentMethod(gp, dialogScene, scene);
}
});
}
private void paymentMethod(GestorPercurso gp, Scene dialogScene, Scene scene){
//Labels
Label paymentLbl = new Label("Select the payment method:");
paymentLbl.setStyle( "-fx-font-weight: bold;" + "-fx-font-size: 14;" );
//Criar butões
Image iconVisa = new Image(getClass().getResourceAsStream("icons/visa.png"), 100, 80, false, false);
Button btnVisa = new Button("", new ImageView(iconVisa));
Image iconMastercard = new Image(getClass().getResourceAsStream("icons/mastercard.png"), 100, 80, false, false);
Button btnMastercard = new Button("", new ImageView(iconMastercard));
Image iconMultibanco = new Image(getClass().getResourceAsStream("icons/multibanco.png"), 100, 80, false, false);
Button btnMultibanco = new Button("", new ImageView(iconMultibanco));
Image iconPaypal = new Image(getClass().getResourceAsStream("icons/paypal.png"), 100, 80, false, false);
Button btnPaypal = new Button("", new ImageView(iconPaypal));
Button cancelBtn = new Button("Cancel");
cancelBtn.setOnAction(e -> ((Stage) cancelBtn.getScene().getWindow()).close());
//Center grid
GridPane grid = new GridPane();
grid.setPadding(new Insets(15,15,15,15));
grid.setHgap(20);
grid.setVgap(20);
grid.setAlignment(Pos.CENTER);
grid.add(btnVisa, 0, 0);
grid.add(btnMastercard, 0, 1);
grid.add(btnMultibanco, 1, 0);
grid.add(btnPaypal, 1, 1);
//Painel principal
VBox paymentPane = new VBox();
paymentPane.setPadding(new Insets(10));
paymentPane.setSpacing(10);
paymentPane.setAlignment(Pos.CENTER);
paymentPane.getChildren().add(paymentLbl);
paymentPane.getChildren().add(grid);
paymentPane.getChildren().add(cancelBtn);
//função dos butões
btnVisa.setOnAction(e -> paymentConfirmation(gp, dialogScene, scene));
btnMastercard.setOnAction(e -> paymentConfirmation(gp, dialogScene, scene));
btnMultibanco.setOnAction(e -> paymentConfirmation(gp, dialogScene, scene));
btnPaypal.setOnAction(e -> paymentConfirmation(gp, dialogScene, scene));
dialogScene.setRoot(paymentPane);
}
private void paymentConfirmation(GestorPercurso gp, Scene dialogScene, Scene scene){
//Menssagem
Label lbl1 = new Label("O valor a pagar será de " + gp.getCost()*quantity + "€\npara o seguinte percurso:");
String targets = "";
int count = 0;
for(InterestPoint ip : gp.getPointsToPass()){
if(count != 0) targets += " - ";
if(count%5 == 0 && count != 0) targets += "\n- ";
targets += ip.toString();
count++;
}
Label lbl2 = new Label(targets);
//Confirmation buttons
Button confirmBtn = new Button("Confirm");
confirmBtn.setOnAction(e -> {
try {
File dir = new File("purchases/" + (Invoice.lastInvoiceNumb() + 1));
dir.mkdir();
List<Ticket> tickets = new ArrayList<>();
for(int i = 0; i < quantity; i++){
boolean isBikePath = false;
if(gp.getTypeRoute() == GestorPercurso.TYPE_ROUTE.CYCLING) isBikePath = true;
Ticket t = new Ticket(gp.getPointsToPass(), i+1, quantity, gp.getClient().getName(), isBikePath);
gp.getClient().buyTicket(t);
tickets.add(t);
}
Invoice invoice = new Invoice(tickets, gp.getCost(), gp.getClient());
Statistics.createStatisticsDAO().addInvoice(invoice);
ClientDAOJson savedClients = new ClientDAOJson();
savedClients.changeSavedClient(gp.getClient(), gp.getClient().getUsername());
} catch (IOException | WriterException ex) {
Logger.getLogger(BuyTicketDialog.class.getName()).log(Level.SEVERE, null, ex);
}
((Stage) confirmBtn.getScene().getWindow()).close();
});
Button cancelBtn = new Button("Cancel");
cancelBtn.setOnAction(e -> ((Stage) cancelBtn.getScene().getWindow()).close());
HBox buttonsBox = new HBox();
buttonsBox.setPadding(new Insets(15, 15, 15, 15));
buttonsBox.setSpacing(10);
buttonsBox.setAlignment(Pos.CENTER);
buttonsBox.getChildren().add(confirmBtn);
buttonsBox.getChildren().add(cancelBtn);
//VBox principal
VBox confirmationPane = new VBox();
confirmationPane.setPadding(new Insets(10));
confirmationPane.setSpacing(10);
confirmationPane.setAlignment(Pos.CENTER);
confirmationPane.getChildren().add(lbl1);
confirmationPane.getChildren().add(lbl2);
confirmationPane.getChildren().add(buttonsBox);
dialogScene.setRoot(confirmationPane);
}
}
|
Java
|
UTF-8
| 1,059
| 2.96875
| 3
|
[] |
no_license
|
package com.company;
public class Dyr {
int antalBen = 7;
double kropsTemperatur = 3.4;
boolean levende = false;
String navn = "søren";
public Dyr() {
}
public Dyr(int a) {
this.antalBen = a;
}
public Dyr(int a, double kropsTemperatur, boolean x, String navn) {
this.antalBen = a;
this.kropsTemperatur = kropsTemperatur;
this.levende = x;
this.navn = navn;
}
public Dyr(int antalBen, boolean x) {
this.antalBen = antalBen;
this.levende = x;
}
public Dyr(boolean x, String navn) {
this.levende = x;
this.navn = navn;
}
public Dyr(double kropsTemperatur) {
this.kropsTemperatur = kropsTemperatur;
}
public static void main(String[] args) {
Dyr x1 = new Dyr();
Dyr x2 = new Dyr(7);
Dyr x3 = new Dyr(6 , 2.2, true, "MARTIN" );
Dyr x4 = new Dyr(12 , true);
Dyr x5 = new Dyr(true, "Seje Martin");
Dyr x6 = new Dyr(38.9);
System.out.println(x1);
}
}
|
Python
|
UTF-8
| 2,872
| 2.65625
| 3
|
[] |
no_license
|
#coding: utf-8;
from __future__ import division, print_function, unicode_literals
from future_builtins import *
from BaseEvaluator import *
from Status import *
class SquatEvaluator(BaseEvaluator):
IDEAL_PACE = 1
def __init__(self, segment_id, training):
super(SquatEvaluator, self).__init__(segment_id, training)
def countSquatIteration(self):
count = 0
isErect = True if self.training[0].kneeCosTheta < 0 else False
for b in self.training[1:]:
# print(b.kneeCosTheta)
if(isErect and b.kneeCosTheta >= 0):
isErect = False
count += 1
elif(not(isErect) and b.kneeCosTheta < 0):
isErect = True
return count
def evaluatePace(self):
count = self.countSquatIteration()
if(count > SquatEvaluator.IDEAL_PACE):
# value:1 -> fast
st = Status(self.segment_id, "pace", 1)
self.appenStatus(st)
elif(count < SquatEvaluator.IDEAL_PACE):
# value:2 -> slow
st = Status(self.segment_id, "pace", 2)
self.appenStatus(st)
def evaluateForm(self):
# select the frame where the user's hip
# locates the lowest position in the training
onWorking, lowest_pos, target = False, (0x01<<31), None
for b in self.training:
hipPos = b.getLowerPosition("Hip")
if hipPos[1] < lowest_pos and b.kneeCosTheta > 0:
onWorking, lowest_pos, target = True, hipPos[1], b
if(onWorking):
self.isValidDirection(target)
self.isValidHipPosition(target)
self.isValidKneePosition(target)
def isValidDirection(self, body):
direction = body.getDirection()
if( direction * direction == 0 ):
st = Status(self.segment_id, "form", 1)
self.appenStatus(st)
def isValidHipPosition(self, body):
hipPos = body.getLowerPosition("Hip")
kneePos = body.getAveragePosition("Knee")
anklePos = body.getUpperPosition("Ankle")
baseHeight = kneePos[1] - anklePos[1]
if( hipPos[1] < kneePos[1] - baseHeight/2):
st = Status(self.segment_id, "form", 2)
self.appenStatus(st)
elif( hipPos[1] > kneePos[1] + baseHeight/2):
st = Status(self.segment_id, "form", 3)
self.appenStatus(st)
def isValidKneePosition(self, body):
direction = body.getDirection()
hipPos = body.getAveragePosition("Hip")
kneePos = body.getAveragePosition("Knee")
anklePos = body.getAveragePosition("Ankle")
X_centerLeg = 0.75*kneePos[0] + 0.25*hipPos[0]
if(direction < 0 and X_centerLeg < anklePos[0]):
st = Status(self.segment_id, "form", 4)
self.appenStatus(st)
|
JavaScript
|
UTF-8
| 7,096
| 2.515625
| 3
|
[] |
no_license
|
Ext.define('ContactsApp.view.contacts.ContactsController', {
extend: 'Ext.app.ViewController',
alias: 'controller.contacts',
requires: [
'ContactsApp.model.Contact'
],
onAddClick: function(button, e, options){
this.createDialog();
},
onEditClick: function(button, e, options){
//The me variable makes a reference to this, which is the ContactsController class.
var me = this,
records = me.getRecordsSelected(); //Get the selected records from the Grid
if(records[0]){
me.createDialog(records[0]); //If a record was selected, we create the window passing the record
}
},
createDialog: function(record){
//We can reference the Form(window) class by calling the method getView of the ViewController class
var me = this,
view = me.getView();
me.isEdit = !!record;
me.dialog = view.add({ //Method add returns new instance of the new component
xtype: 'contactsform', //Create new window form and assign it to a variable dialog
iconCls: record ? 'fa fa-pencil' : 'fa fa-plus',
viewModel: {
data: {
windowTitle: record ? 'Edit: ' + record.get('firstName') : 'Add Contact'
}
}
});
//If there is an existing record, it uses a copy of it, and if not, it creates a new record
if(record){
me.dialog.down('form').loadRecord(record);
}
me.dialog.show();
},
onSave: function(button, e, options){
var me = this,
form = me.dialog.down('form'), //Get the form reference
isEdit = me.isEdit,
record = form.getRecord(),
values = form.getValues(),
store = me.getView().getStore();
if (isEdit) {
record.set(values);
me.onCancel(); //Method onCancel closing and destroying the window Form
Ext.Msg.alert('Message', 'Contact has been saved successfully!');
} else{
record = Ext.create('ContactsApp.model.Contact');
record.set(values);
record.setId(0);
store.add(record);
Ext.Msg.alert('Message', 'Contact has been saved successfully!');
me.onCancel();
}
store.sync();
},
validationAndSave: function() {
var me = this;
var form = me.dialog.up().down('form');
var user = Ext.create('ContactsApp.model.Contact', form.getValues());
var errors = user.validate();
if(!errors.isValid()) {
var errorMsg = "";
errors.each(function (item, index, length) {
errorMsg += ' ' + item.getMessage() + '<br/>';
});
Ext.Msg.alert("Validation Failed", errorMsg);
}
else {
this.onSave();
}
},
onReset: function() {
var me = this;
me.dialog.down('form').reset();
},
//Modern version - Mobile devices
onAddClickMobile: function(button, e, options){
this.createDialogMobile();
},
onEditClickMobile: function(button, e, options){
//The me variable makes a reference to this, which is the ContactsController class.
var me = this,
records = me.getRecordsSelected(); //Get the selected records from the Grid
if(records){
me.createDialogMobile(records); //If a record was selected, we create the window passing the record
}
},
createDialogMobile: function(record){
//We can reference the Form(window) class by calling the method getView of the ViewController class
var me = this,
view = me.getView();
me.isEdit = !!record;
me.dialog = view.add({ //Method add returns new instance of the new component
xtype: 'contactsform' //Create new window form and assign it to a variable dialog
});
//If there is an existing record, it uses a copy of it, and if not, it creates a new record
if(record){
Ext.ComponentQuery.query('contactsform')[0].setRecord(record);
}
me.dialog.show();
},
onSaveMobile: function(button, e, options){
var me = this,
form = Ext.ComponentQuery.query('contactsform')[0], //Get the form reference
isEdit = me.isEdit,
record = form.getRecord(),
values = form.getValues(),
store = me.getView().getStore();
if (isEdit) {
record.set(values);
me.onCancel(); //Method onCancel closing and destroying the window Form
} else{
record = Ext.create('ContactsApp.model.Contact');
record.set(values);
store.add(record);
Ext.Msg.alert('Message', 'Contact has been saved successfully!');
me.onCancel();
}
store.sync();
},
validationAndSaveMobile: function() {
var me = this;
var form = me.dialog.up().down('formpanel');
var user = Ext.create('ContactsApp.model.Contact', form.getValues());
var errors = user.validate();
if(!errors.isValid()) {
var errorMsg = "";
errors.each(function (item, index, length) {
errorMsg += ' ' + item.getMessage() + '<br/>';
});
Ext.Msg.alert("Validation Failed", errorMsg);
}
else {
this.onSaveMobile();
}
},
onResetMobile: function() {
Ext.ComponentQuery.query('contactsform')[0].reset();
},
//Common methods for modern and classic versions
onDeleteClick: function (button, e, options) {
var me = this,
records = me.getRecordsSelected(),
store = me.getView().getStore();
//The method checks if selected any row from the grid to be deleted
if (records){
Ext.Msg.confirm('Delete contact', 'Are you sure want to delete this contact?',
function (choice) {
if (choice === 'yes') {
//If the user click yes, the row is removed
store.remove(records);
//The store is synchronized
store.sync();
Ext.Msg.alert('Message', 'Contact has been deleted!');
}
}
)
}
},
/*
*Get a reference of the grid row,
*and by accessing its getSelection method, we can get the rows selected.
*/
getRecordsSelected: function(){
return this.getView().getSelection();
},
onCancel: function(button, e, options){
var me = this;
me.dialog = Ext.destroy(me.dialog); //Destroy window Form
},
});
|
Java
|
UTF-8
| 2,116
| 2.453125
| 2
|
[] |
no_license
|
package argo.batch;
/* Extends the metric data information by adding the extra group field
*
*/
public class MonData {
private String group;
private String service;
private String hostname;
private String metric;
private String status;
private String timestamp;
private String monHost;
private String summary;
private String message;
private String actualData;
public MonData(){
this.group="";
this.service="";
this.hostname="";
this.metric="";
this.status="";
this.timestamp="";
this.monHost="";
this.summary="";
this.message="";
this.actualData="";
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getMetric() {
return metric;
}
public void setMetric(String metric) {
this.metric = metric;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getMonHost() {
return monHost;
}
public void setMonHost(String monHost) {
this.monHost = monHost;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getActualData() {
return actualData;
}
public void setActualData(String actualData) {
this.actualData = actualData;
}
public String toString() {
return "(" + this.group + "," + this.service + "," + this.hostname + "," + this.metric + "," + this.status + ","
+ this.timestamp + "," + this.monHost + "," + this.summary + "," + this.message + "," + this.actualData + ")";
}
}
|
Swift
|
UTF-8
| 4,534
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
//
// SwiftPlaygroundsHelper.swift
// FilterPlayground
//
// Created by Leo Thomas on 11.09.17.
// Copyright © 2017 Leo Thomas. All rights reserved.
//
import Foundation
extension KernelArgumentValue {
fileprivate func swiftPlaygroundValue(with attributeName: String) -> String {
switch self {
case let .color(r, g, b, a):
return "CIColor(red: \(r), green: \(g), blue: \(b), alpha: \(a))"
case let .float(f):
return "\(f)"
case .sample:
return "CISampler(image: CIImage(image: #imageLiteral(resourceName: \"\(attributeName).png\"))!)"
case let .vec2(a, b):
return "CIVector(x: \(a), y: \(b))"
case let .vec3(a, b, c):
return "CIVector(x: \(a), y: \(b), z: \(c))"
case let .vec4(a, b, c, d):
return "CIVector(x: \(a), y: \(b), z: \(c), w: \(d))"
case .uint2:
fatalError()
}
}
}
class SwiftPlaygroundsExportHelper {
static var xcplaygroundData: Data = {
let content = """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='ios'>
<timeline fileName='timeline.xctimeline'/>
</playground>
"""
return content.data(using: .utf8)!
}()
class func swiftPlayground(with name: String, type: KernelType, kernelSource: String, arguments: [KernelArgument], inputImages: [Data]) -> URL {
let definedVariables = arguments.map { "var \($0.name): \($0.type.swiftType) = \($0.value.swiftPlaygroundValue(with: $0.name))" }.joined(separator: "\n")
let assignFilterProperties = arguments.map { "filter.\($0.name) = \($0.name)" }.joined(separator: "\n")
var inputImageAssignment = ""
if inputImages.count == 1 {
inputImageAssignment = "let image = #imageLiteral(resourceName: \"input.png\")\nfilter.input = CIImage(image: image)"
} else if inputImages.count == 2 {
inputImageAssignment = """
let fore = #imageLiteral(resourceName: \"fore.png\")
filter.fore = CIImage(image: fore)
let back = #imageLiteral(resourceName: \"back.png\")
filter.back = CIImage(image: back)
"""
}
let content = """
import UIKit
\(CIFilterExportHelper.cifilter(with: kernelSource, type: type, arguments: arguments, name: name) as String)
\(definedVariables)
let filter = \(name)()
\(inputImageAssignment)
\(assignFilterProperties)
let result = filter.outputImage
"""
var resources: [(String, Data)] = arguments
.compactMap { guard case let .sample(image) = $0.value else { return nil }
return ($0.name, image.asJPGData!) }
if inputImages.count == 1 {
resources.append(("input", inputImages[0]))
} else if inputImages.count == 2 {
resources.append(contentsOf: [
("fore", inputImages[0]),
("back", inputImages[1]),
])
}
return SwiftPlaygroundsExportHelper.swiftPlayground(with: content, resources: swiftPlaygroundResourcesFolder(with: resources))
}
class func swiftPlaygroundResourcesFolder(with files: [(String, Data)]) -> FileWrapper {
var resourceWrappers: [String: FileWrapper] = [:]
for resource in files {
resourceWrappers["\(resource.0).png"] = FileWrapper(regularFileWithContents: resource.1)
}
return FileWrapper(directoryWithFileWrappers: resourceWrappers)
}
class func swiftPlayground(with contentSource: String, resources: FileWrapper? = nil) -> URL {
let contentSourceData = contentSource.data(using: .utf8)!
let contentsFileWrapper = FileWrapper(regularFileWithContents: contentSourceData)
let xcplaygroundFileWrapper = FileWrapper(regularFileWithContents: xcplaygroundData)
var fileWrappers = [
"contents.xcplayground": xcplaygroundFileWrapper,
"Contents.swift": contentsFileWrapper,
]
if let resources = resources {
fileWrappers["Resources"] = resources
}
let fileWrapper = FileWrapper(directoryWithFileWrappers: fileWrappers)
let url = FileManager.default.temporaryDirectory.appendingPathComponent("test.playground")
try? fileWrapper.write(to: url, options: .atomic, originalContentsURL: nil)
return url
}
}
|
Java
|
UTF-8
| 1,371
| 2.125
| 2
|
[] |
no_license
|
package com.brunoeleodoro.org.recyclerviewtest;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.brunoeleodoro.org.recyclerviewtest.mvp.MVP;
import com.brunoeleodoro.org.recyclerviewtest.mvp.Presenter;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements MVP.View {
RecyclerView recyclerView;
private MVP.Presenter presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
presenter = new Presenter();
presenter.setView(this);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view_layour_recycler);
presenter.receberNoticias("");
}
@Override
public void montarLista(NoticiasAdapter adapter) {
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
recyclerView.addItemDecoration(
new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
}
}
|
Java
|
UTF-8
| 1,341
| 2.234375
| 2
|
[] |
no_license
|
package fr.wcs.simplelist.Models;
/**
* Created by apprenti on 22/01/18.
*/
public class CoinListModel {
private String shortNameCoin;
private String longNameCoin;
private String actualValueCoin;
private String photoURLCoin;
public CoinListModel(String shortNameCoin, String longNameCoin, String actualValueCoin, String photoURLCoin) {
this.shortNameCoin = shortNameCoin;
this.longNameCoin = longNameCoin;
this.actualValueCoin = actualValueCoin;
this.photoURLCoin = photoURLCoin;
}
public CoinListModel(){
//For Firebase
}
public String getShortNameCoin() {
return shortNameCoin;
}
public void setShortNameCoin(String shortNameCoin) {
this.shortNameCoin = shortNameCoin;
}
public String getLongNameCoin() {
return longNameCoin;
}
public void setLongNameCoin(String longNameCoin) {
this.longNameCoin = longNameCoin;
}
public String getActualValueCoin() {
return actualValueCoin;
}
public void setActualValueCoin(String actualValueCoin) {
this.actualValueCoin = actualValueCoin;
}
public String getPhotoURLCoin() {
return photoURLCoin;
}
public void setPhotoURLCoin(String photoURLCoin) {
this.photoURLCoin = photoURLCoin;
}
}
|
Java
|
UTF-8
| 3,623
| 2.140625
| 2
|
[] |
no_license
|
package com.ricky.f.util;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
/**
* 资源helper
* @author Administrator
*
*/
public class ResourceUtils {
//获取颜色
public static int getColor(int id){
return AppUtils.getInstance().getContext().getResources().getColor(id);
}
//获取颜色状态list
public static ColorStateList getColorStateList(int resId){
return (ColorStateList) AppUtils.getInstance().getContext().getResources().getColorStateList(resId);
}
//获取字符串
public static String getString(int resId){
return AppUtils.getInstance().getContext().getResources().getString(resId);
}
//获取drawable
public static Drawable getDrawable(int resId){
return AppUtils.getInstance().getContext().getResources().getDrawable(resId);
}
public static LayoutInflater getInflater(){
return LayoutInflater.from(AppUtils.getInstance().getContext());
}
public static float getDimension(int resId){
return AppUtils.getInstance().getContext().getResources().getDimension( resId);
}
public static Context getContext(){
return AppUtils.getInstance().getContext();
}
public static int getDimensionPixelSize(int id){
return getContext().getResources().getDimensionPixelSize(id);
}
public static Drawable getDrawableFromDrawablePkg(String drawableName){
return getContext().getResources().getDrawable(getContext().getResources().getIdentifier(drawableName,"drawable", getContext().getPackageName()));
}
public static int getResIdFromDrawablePkg(String drawableName){
return getContext().getResources().getIdentifier(drawableName,"drawable", getContext().getPackageName());
}
public static int getLayoutId(Context paramContext, String paramString) {
return paramContext.getResources().getIdentifier(paramString, "layout",
paramContext.getPackageName());
}
public static int getStringId(Context paramContext, String paramString) {
return paramContext.getResources().getIdentifier(paramString, "string",
paramContext.getPackageName());
}
public static int getDrawableId(Context paramContext, String paramString) {
return paramContext.getResources().getIdentifier(paramString,
"drawable", paramContext.getPackageName());
}
public static int getStyleId(Context paramContext, String paramString) {
return paramContext.getResources().getIdentifier(paramString,
"style", paramContext.getPackageName());
}
public static int getId(Context paramContext, String paramString) {
return paramContext.getResources().getIdentifier(paramString,"id", paramContext.getPackageName());
}
public static int getColorId(Context paramContext, String paramString) {
return paramContext.getResources().getIdentifier(paramString,
"color", paramContext.getPackageName());
}
public static int getArrayId(Context paramContext, String paramString) {
return paramContext.getResources().getIdentifier(paramString,
"array", paramContext.getPackageName());
}
public static Animation getAnimation(Context paramContext, int animId) {
if(animId <=0 ) return null;
return AnimationUtils.loadAnimation(paramContext, animId);
}
}
|
Python
|
UTF-8
| 625
| 4.4375
| 4
|
[] |
no_license
|
"""
7. Write a Python program to print all unique values in a dictionary.
Sample Data : [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"},
{"VII":"S005"}, {"V":"S009"},{"VIII":"S007"}]
Expected Output : Unique Values: {'S005', 'S002', 'S007', 'S001', 'S009'}
"""
def print_unique_value(given_dict): # funtion tu print unique value
list1 = []
for x, y in dict1.items():
if y not in list1:
list1.append(y)
print(list1)
dict1 = {"V": "S001", "VI": "S002", "VIII": "S001", "IVI": "S005", "IIVII": "S005", "IIIVIII": "S009", "IIVIII": "S007"}
print(dict1)
print_unique_value(dict1)
|
TypeScript
|
UTF-8
| 1,114
| 2.984375
| 3
|
[] |
no_license
|
import { parse } from "date-fns";
import { isActive, isTitleValid, isValid } from "../Task";
it("isActive returns true for active at the moment task", () => {
const task = {
id: "test",
title: "test",
created: parse("2019-01-01"),
schedule: { 1: { 22: true } },
};
expect(isActive(task, parse("2019-04-22 22:00"))).toBe(true);
expect(isActive(task, parse("2019-04-22 22:30"))).toBe(true);
expect(isActive(task, parse("2019-04-15 22:59"))).toBe(true);
expect(isActive(task, parse("2019-04-22 20:00"))).toBe(false);
expect(isActive(task, parse("2019-04-23 22:00"))).toBe(false);
});
it("isTitleValid ensures that title isn't empty", () => {
expect(isTitleValid("")).toBe(false);
expect(isTitleValid("test")).toBe(true);
});
it("isValid ensures that a task valid", () => {
expect(
isValid({
id: "test",
title: "test",
created: parse("2019-01-01"),
schedule: { 1: { 22: true } },
}),
).toBe(true);
expect(
isValid({
id: "test",
title: "",
created: parse("2019-01-01"),
schedule: {},
}),
).toBe(false);
});
|
Python
|
UTF-8
| 825
| 3.046875
| 3
|
[] |
no_license
|
# 36_7
import sys
from itertools import product
out = open("output.txt",'w')
Input = open(sys.argv[1])
Input = Input.read().split("\n")
K = int(Input[0].split(" ")[0])
d = int(Input[0].split(" ")[1])
Seqs = filter(lambda s: s!='', Input[1:])
def diff(seq1,seq2,d):
'''
seq1 and seq2 must be same length
True if difference of seq1/2 no larger than d
'''
n = 0
for i in range(len(seq1)):
if seq1[i]!=seq2[i]:
n += 1
if n>d:
return False
return True
result = []
for s1 in product("ACGT",repeat=K):
s1="".join(s1)
for s in Seqs:
exist_mark = False
for i in range(len(s)-K+1):
s2 = s[i:(i+K)]
if diff(s1,s2,d):
exist_mark = True
break
if not exist_mark:
break
if exist_mark:
result.append(s1)
print >>out, " ".join(result)
|
Java
|
UTF-8
| 1,999
| 2.21875
| 2
|
[] |
no_license
|
package com.interview.request.integrationTest.controller;
import com.interview.request.controller.MatchController;
import com.interview.request.domain.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class MatchControllerIntegrationTest {
@Autowired
private MatchController matchController;
@Test
public void listAnagramsCandidateTest() {
CommonResult result = matchController.listAnagramsCandidate("test1");
Assert.assertNotNull(result);
Assert.assertEquals(Integer.valueOf(200), result.getCode());
Assert.assertEquals("OK", result.getMsg());
Assert.assertTrue( result.getResult() instanceof HashMap);
Map<String, Set> map = (HashMap<String, Set>)result.getResult();
Assert.assertEquals(1, map.size());
map.entrySet().stream()
.filter( x -> x.getKey().equals("anagrams: "))
.flatMap(x -> x.getValue().stream())
.forEach( y -> {
Assert.assertTrue(matchController.anagramsMatch("test1", String.valueOf(y)).getResult().toString().equals("areAnagrams: true"));
});
}
@Test
public void anagramsMatchTest() {
CommonResult result = matchController.anagramsMatch("test1", "test2");
Assert.assertEquals("areAnagrams: false", result.getResult().toString());
result = matchController.anagramsMatch("test1", "test1");
Assert.assertEquals("areAnagrams: true", result.getResult().toString());
}
}
|
C++
|
UTF-8
| 7,042
| 2.671875
| 3
|
[
"Unlicense"
] |
permissive
|
#include "Shaders.hpp"
using namespace Engine;
CShader::CShader(void) : Type(0), GLShader(0)
{
}
CShader::~CShader(void)
{
Destroy();
}
bool CShader::Create(std::string Filename)
{
int Status;
Filename.insert(0, RootDir + ResourceDir + "shaders\\");
this->Filename = Filename;
if (Filename.find(".frag") != std::string::npos) {
this->Type = GL_FRAGMENT_SHADER;
} else if (Filename.find(".vert") != std::string::npos) {
this->Type = GL_VERTEX_SHADER;
}
const char* Source = LoadFile(Filename);
GLShader = glCreateShader(Type);
glShaderSource(GLShader, 1, &Source, NULL);
glCompileShader(GLShader);
glGetShaderiv(GLShader, GL_COMPILE_STATUS, &Status);
delete [] Source;
if (Status == GL_TRUE) {
Logger->Text("Compiled OpenGL Shader - " + Filename);
} else {
Logger->Error("Error Compiling OpenGL Shader - " + Filename);
}
return glIsShader(GLShader);
}
bool CShader::Destroy(void)
{
if (glIsShader(GLShader)) {
glDeleteShader(GLShader);
Logger->Text("Destroyed OpenGL Shader - " + Filename);
}
return !glIsShader(GLShader);
}
const char* CShader::LoadFile(std::string Filename)
{
std::ifstream FileStream(Filename.c_str(), std::ios::binary | std::ios::in);
if (FileStream.fail()) {
Logger->Error("Error Loading Shader File - " + Filename);
}
FileStream.seekg(0, std::ios::end);
int Size = FileStream.tellg();
FileStream.seekg(0, std::ios::beg);
char* Buffer = new char[Size + 1];
FileStream.read(&Buffer[0], Size);
Buffer[Size] = '\0';
FileStream.close();
Logger->Text("Loaded Shader File - " + Filename);
return Buffer;
}
CProgram::CProgram(void) : GLProgram(0)
{
}
CProgram::~CProgram(void)
{
Destroy();
}
bool CProgram::Create(const char *Filename, ...)
{
GLProgram = glCreateProgram();
va_list Files;
va_start(Files, Filename);
while (Filename != NULL) {
CShader *Shader = new CShader();
if (Shader->Create(Filename)) {
glAttachShader(GLProgram, Shader->ShaderID());
Logger->Text("Attached Shader - " + Shader->GetFilename());
}
delete Shader;
Filename = va_arg(Files, const char*);
}
va_end(Files);
int Linked = 0;
glLinkProgram(GLProgram);
glGetProgramiv(GLProgram, GL_LINK_STATUS, &Linked);
if (Linked == GL_TRUE) {
Logger->Text("Linked Shader Program");
} else {
Logger->Error("Error Linking Shader Program");
}
if (glIsProgram(GLProgram)) {
Logger->Text("Created Shader Program");
} else {
Logger->Error("Error Creating Shader Program");
}
return glIsProgram(GLProgram);
}
bool CProgram::Destroy(void)
{
if (glIsProgram(GLProgram)) {
glDeleteProgram(GLProgram);
Logger->Text("Destroyed OpenGL Shader Program");
}
return !glIsProgram(GLProgram);
}
void CProgram::Bind(void)
{
glUseProgram(GLProgram);
}
void CProgram::Unbind(void)
{
glUseProgram(0);
}
int CProgram::SetUniform(std::string Name, float* Values, int Count)
{
int Location = glGetUniformLocation(GLProgram, Name.c_str());
glUniform1fv(Location, Count, Values);
return Location;
}
int CProgram::SetUniform(std::string Name, const float Value)
{
int Location = glGetUniformLocation(GLProgram, Name.c_str());
glUniform1fv(Location, 1, &Value);
return Location;
}
int CProgram::SetUniform(std::string Name, const float Value1, const float Value2)
{
int Location = glGetUniformLocation(GLProgram, Name.c_str());
glUniform2f(Location, Value1, Value2);
return Location;
}
int CProgram::SetUniform(std::string Name, glm::vec2* Vecs, int Count)
{
int Location = glGetUniformLocation(GLProgram, Name.c_str());
glUniform2fv(Location, Count, (GLfloat*) Vecs);
return Location;
}
int CProgram::SetUniform(std::string Name, const glm::vec2 Vec)
{
int Location = glGetUniformLocation(GLProgram, Name.c_str());
glUniform2fv(Location, 1, (GLfloat*) &Vec);
return Location;
}
int CProgram::SetUniform(std::string Name, glm::vec3* Vecs, int Count)
{
int Location = glGetUniformLocation(GLProgram, Name.c_str());
glUniform3fv(Location, Count, (GLfloat*) Vecs);
return Location;
}
int CProgram::SetUniform(std::string Name, const glm::vec3 Vec)
{
int Location = glGetUniformLocation(GLProgram, Name.c_str());
glUniform3fv(Location, 1, (GLfloat*) &Vec);
return Location;
}
int CProgram::SetUniform(std::string Name, glm::vec4* Vecs, int Count)
{
int Location = glGetUniformLocation(GLProgram, Name.c_str());
glUniform4fv(Location, Count, (GLfloat*) Vecs);
return Location;
}
int CProgram::SetUniform(std::string Name, const glm::vec4 Vec)
{
int Location = glGetUniformLocation(GLProgram, Name.c_str());
glUniform4fv(Location, 1, (GLfloat*) &Vec);
return Location;
}
int CProgram::SetUniform(std::string Name, glm::mat3* Matrices, int Count)
{
int Location = glGetUniformLocation(GLProgram, Name.c_str());
glUniformMatrix3fv(Location, Count, FALSE, (GLfloat*) Matrices);
return Location;
}
int CProgram::SetUniform(std::string Name, const glm::mat3 Matrix)
{
int Location = glGetUniformLocation(GLProgram, Name.c_str());
glUniformMatrix3fv(Location, 1, FALSE, (GLfloat*) &Matrix);
return Location;
}
int CProgram::SetUniform(std::string Name, glm::mat4* Matrices, int Count)
{
int Location = glGetUniformLocation(GLProgram, Name.c_str());
glUniformMatrix4fv(Location, Count, FALSE, (GLfloat*) Matrices);
return Location;
}
int CProgram::SetUniform(std::string Name, const glm::mat4 Matrix)
{
int Location = glGetUniformLocation(GLProgram, Name.c_str());
glUniformMatrix4fv(Location, 1, FALSE, (GLfloat*) &Matrix);
return Location;
}
int CProgram::SetUniform(std::string Name, int* Values, int Count)
{
int Location = glGetUniformLocation(GLProgram, Name.c_str());
glUniform1iv(Location, Count, Values);
return Location;
}
int CProgram::SetUniform(std::string Name, const int Value)
{
int Location = glGetUniformLocation(GLProgram, Name.c_str());
glUniform1i(Location, Value);
return Location;
}
void CProgram::SetModelAndNormalMatrix(std::string ModelMaxtrixName, std::string NormalMatrixName, glm::mat4 ModelMatrix)
{
SetUniform(ModelMaxtrixName, ModelMatrix);
SetUniform(NormalMatrixName, glm::transpose(glm::inverse(ModelMatrix)));
}
void CProgram::SetModelAndNormalMatrix(std::string ModelMaxtrixName, std::string NormalMatrixName, glm::mat4* ModelMatrix)
{
SetUniform(ModelMaxtrixName, ModelMatrix);
SetUniform(NormalMatrixName, glm::transpose(glm::inverse(*ModelMatrix)));
}
|
Ruby
|
UTF-8
| 173
| 3
| 3
|
[] |
no_license
|
input = File.open(ARGV[0]).readlines
input.each do |nums|
numbers = nums.split
output = []
numbers.each do |i|
output << i.to_f
end
puts output.sort.join(' ')
end
|
C#
|
UTF-8
| 1,036
| 3.359375
| 3
|
[] |
no_license
|
using System;
namespace OOP1
{
class Program
{
static void Main(string[] args)
{
Product product1 = new Product();
product1.Id = 1;
product1.CategoryId = 2;//Mobilya olsun
product1.ProductName = "Masa";
product1.UnitPrice = 500;
product1.UnitInSrock = 3;
Product product2 = new Product { Id = 2, CategoryId = 5,
ProductName = "Kalem", UnitPrice = 35, UnitInSrock = 5 };
//C# is case sensitive language
//PascalCase //camelCase
ProductManager productManager = new ProductManager();
productManager.Add(product1);
Console.WriteLine(product1.ProductName);//product class olduğu için yani referans tipi olduğu için çıktı "Kamera olacak" (Add() fonksiyonu içerisinde değişti)
//int, double, bool ... değer tip
//diziler, class, abstract class, interface ... referans tip
//ref out
}
}
}
|
Markdown
|
UTF-8
| 308
| 2.734375
| 3
|
[] |
no_license
|
---
title: "Give all permission to the owner, read execute to the group and nothing to others"
date: 2020-12-22T14:58:42-08:00
draft: true
---
```
# Create a file
touch file1
# Set permission using either of the method
chmod 750 file1
chmod u=rwx,g=rx,o= file1
# List the file permission
ls -lh file1
```
|
C++
|
UTF-8
| 252
| 2.984375
| 3
|
[] |
no_license
|
#include <stdio.h> // header file
#include <iostream> // header file
using namespace std; // namespace for cout
int main()
{
printf("Hello World!\n");
cout << "hello from cout" << endl;
cout << "Another line";
return 0;
}
|
Python
|
UTF-8
| 1,841
| 2.609375
| 3
|
[] |
no_license
|
'''
Created on Jun 4, 2011
@author: gr00vy
'''
from logging import debug
import os
from subprocess import PIPE, Popen
import shlex
class InvalidPintoolPathException(Exception):
pass
class AbstractPintool(object):
def __init__(self, pin_dir, tool_path, tool_name):
# pin will take a different name in windows, also the pintool will have a diferent extension
if os.name == "posix":
pinbin_name = "pin"
tool_name = tool_name + ".so"
else:
pinbin_name = "pin.bat"
tool_name = tool_name + ".dll"
self.pindir_path = pin_dir
self.pinbin_path = os.path.join(self.pindir_path, pinbin_name)
# if we compile in 64 bit the tool dir will be different. try to make an educated guess
self.tool_path = os.path.join(self.pindir_path, tool_path)
if os.path.exists(os.path.join(self.tool_path, "obj-intel32")):
self.toolbin_path = os.path.join(self.tool_path, "obj-intel32")
elif os.path.exists(os.path.join(self.tool_path, "obj-intel64")):
self.toolbin_path = os.path.join(self.tool_path, "obj-intel64")
else:
raise InvalidPintoolPathException("Cannot the path to pintools dir, did you compile?")
self.tool_name = os.path.join(self.toolbin_path, tool_name)
debug("Tool path :" + self.tool_path)
debug("Tool bin :" + self.tool_name)
debug("Pin path :" + self.pindir_path)
debug("Pin bin :" + self.pinbin_path)
def run(self, command):
command = "%s -t %s -- %s" % (self.pinbin_path, self.tool_name, command)
command = " ".join(shlex.split(command))
debug("Running command:")
debug(command)
return Popen(command, shell=True, stdout=PIPE, stderr=PIPE)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.