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
| 641 | 2.71875 | 3 |
[] |
no_license
|
#pragma once
#include "gl-inl.h"
#include "window.h"
struct TexUnit {
const GLenum unit;
const unsigned idx;
TexUnit(GLenum unit, unsigned idx) : unit(unit), idx(idx) {}
};
class Framebuffer {
GLuint fb;
GLuint tex_color_buffer;
GLuint rbo;
GLuint depth_buffer;
Window const& window;
bool const with_depth, full_rgb;
const float scale;
public:
Framebuffer(Window& window, bool with_depth, bool full_rgb, float scale = 1.0f);
void bind_for_writing() const;
void bind_for_reading(GLenum texture_unit) const;
std::pair<int, int> get_fb_size() const;
virtual ~Framebuffer();
private:
void init();
};
|
JavaScript
|
UTF-8
| 479 | 2.953125 | 3 |
[] |
no_license
|
'use strict';
function choose_multiples_of_three(collection) {
//在这里写入代码
var filter= require('../lodash/zhuyulonglodash/fiter.js');
var evens = filter(collection, function(n){
return n % 3 == 0;
});
return evens;
}
// var array=[];
//
// for(var i=0; i<collection.length; i++){
// if(collection[i] % 3 == 0){
// array.push(collection[i]);
// }
// }
// return array;
// }
module.exports = choose_multiples_of_three;
|
JavaScript
|
UTF-8
| 1,243 | 3.375 | 3 |
[] |
no_license
|
var officeItems = ["stapler", "monitor", "computer", "desk", "lamp", "computer", "lamp", "stapler", "computer", "computer"]
var count = 0
for (var i = 0; i < officeItems.length; i++){
if (officeItems[i] === "computer"){
count++
}
}
console.log(count) // -> 4
var peopleWhoWantToSeeMadMaxFuryRoad = [
{
name: "Mike",
age: 12,
gender: "male"
},{
name: "Madeline",
age: 80,
gender: "female"
},{
name: "Cheryl",
age: 22,
gender: "female"
},{
name: "Sam",
age: 30,
gender: "male"
},{
name: "Suzy",
age: 4,
gender: "female"
}]
{function isOldEnough(){
for (i = 0; i < peopleWhoWantToSeeMadMaxFuryRoad.length; i++){
if(peopleWhoWantToSeeMadMaxFuryRoad[i].age >= 18){
console.log("old enough");
}if (peopleWhoWantToSeeMadMaxFuryRoad[i].age >= 18){
console.log("old enough");
}
else if(peopleWhoWantToSeeMadMaxFuryRoad[i].age < 18){
console.log("not old enough");
}
}
}
}
isOldEnough();
function evenOrOdd(){
for(var i = 0; i < 101; i++){
if(i % 2 === 1) {
console.log(`${i} is odd`)
}
else{
console.log(`${i} is even`)
}
}
}
evenOrOdd()
|
Ruby
|
UTF-8
| 1,014 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
describe "Shiritori test" do
let(:main){ Shiritori::Main.new }
let(:__class__){ Range }
let(:__instance__){ 1..10 }
describe "Range singleton methods" do
it { instance_check(:new, %q(1, 10), obj: __class__) }
end
describe "Range instance methods" do
it { instance_check(:==, %q(1..11)) }
it { instance_check(:===, %q(5)) }
it { instance_check(:include?, %q(11)) }
it { instance_check(:member?, %q(-1)) }
it { instance_check(:begin) }
it { instance_check(:first) }
it { instance_check(:bsearch) }
it { instance_check(:cover?, %q(11)) }
it { instance_check(:each) }
it { instance_check(:end) }
it { instance_check(:last) }
it { instance_check(:eql?, %q(1..10)) }
it { instance_check(:exclude_end?) }
it { instance_check(:hash) }
it { instance_check(:inspect) }
it { instance_check(:max) }
it { instance_check(:min) }
it { instance_check(:size) }
it { instance_check(:step) }
it { instance_check(:to_s) }
end
end
|
Ruby
|
UTF-8
| 205 | 3.171875 | 3 |
[] |
no_license
|
ventas = {
Octubre: 65000,
Noviembre: 68000,
Diciembre: 72000
}
def filter(data)
filtered = {}
data.each do |k,v|
filtered[k]=v if v<70000
end
filtered
end
puts filter(ventas)
|
Markdown
|
UTF-8
| 1,517 | 3.109375 | 3 |
[
"MIT"
] |
permissive
|
# k2so 
Deploys your software -- The captain said I have to
The purpose of this crate is to assist with deployments and infrastructure changes performed via Chef.
When using [knife solo](https://matschaffer.github.io/knife-solo/) it requires some arguments passed in such as IP address and the role name. To ensure that the right machine gets provisioned with the right cookbook this tool lets the user define roles upfront which then can be used afterwards to perform deployments and/or infrastructure changes in an easy way.
## Installation
To install k2so, you first need to install Rust from https://www.rust-lang.org/en-US/install.html.
Then you can run `cargo install k2so`.
## Usage
This requires the following tools to be installed:
- [ChefDK](https://downloads.chef.io/chefdk)
- [knife solo](https://matschaffer.github.io/knife-solo/)
First, a new mapping between role and IP address has to be defined:
```bash
$ k2so add 192.168.33.10 app
```
This maps the address `192.168.33.10` to the `app` role. If that role already existed before, it gets overwritten automatically.
Then execute these commands as well:
```bash
$ k2so add_user root
$ k2so add_key keys/id_rsa
```
These two configure the user which shall be used to connect and the ssh key. These are global for all configured roles.
Then if that's done, the actual deploy can be performed:
```bash
$ k2so deploy app
```
which then runs the `app` cookbooks on the configured `app` machine.
|
Java
|
UTF-8
| 7,904 | 2.5 | 2 |
[] |
no_license
|
package com.chy.summer.framework.core.evn.resolver;
import com.chy.summer.framework.core.convert.ConversionService;
import com.chy.summer.framework.core.convert.support.ConfigurableConversionService;
import com.chy.summer.framework.util.Assert;
import com.chy.summer.framework.util.PropertyPlaceholderHelper;
import com.chy.summer.framework.util.SystemPropertyUtils;
import lombok.Setter;
import java.util.*;
import java.util.stream.Collectors;
public abstract class AbstractPropertyResolver implements ConfigurablePropertyResolver {
/**
* 占位符的后缀,默认是 }
*/
private String placeholderSuffix = SystemPropertyUtils.PLACEHOLDER_SUFFIX;
/**
* 占位符的前缀,默认是 ${
*/
private String placeholderPrefix = SystemPropertyUtils.PLACEHOLDER_PREFIX;
/**
* 分隔符,默认是 :
*/
@Setter
private String valueSeparator = SystemPropertyUtils.VALUE_SEPARATOR;
@Setter
private boolean ignoreUnresolvableNestedPlaceholders = false;
@Setter
private volatile ConfigurableConversionService conversionService;
private final Set<String> requiredProperties = new LinkedHashSet<>();
private PropertyPlaceholderHelper nonStrictHelper;
private PropertyPlaceholderHelper strictHelper;
//==========================================================================================
// ConfigurablePropertyResolver 接口 的实现
//==========================================================================================
@Override
public void setPlaceholderSuffix(String placeholderSuffix) {
Assert.notNull(placeholderSuffix, "'placeholderSuffix' must not be null");
this.placeholderSuffix = placeholderSuffix;
}
/**
* 设置一个前缀占位符
*
* @param placeholderPrefix
*/
@Override
public void setPlaceholderPrefix(String placeholderPrefix) {
Assert.notNull(placeholderPrefix, "'placeholderPrefix' must not be null");
this.placeholderPrefix = placeholderPrefix;
}
@Override
public void setRequiredProperties(String... requiredProperties) {
Collections.addAll(this.requiredProperties, requiredProperties);
}
/**
* 校验 required的key是否有效,其实也就是 调用 getProperty 去判断能不能拿到值
*/
@Override
public void validateRequiredProperties() {
List<String> invalid = new ArrayList<>();
for (String key : this.requiredProperties) {
if (this.getProperty(key) == null) {
invalid.add(key);
}
}
if (!invalid.isEmpty()) {
String collect = invalid.stream().collect(Collectors.joining(","));
throw new RuntimeException("无效的 requiredProperties: [" + collect + "]");
}
}
//==========================================================================================
// PropertyResolver 接口 的实现
//==========================================================================================
/**
* 是否包含某个key的属性
*
* @param key
*/
@Override
public boolean containsProperty(String key) {
return (getProperty(key) != null);
}
/**
* 获取某个key 的属性
*
* @param key
*/
@Override
public String getProperty(String key) {
return getProperty(key, String.class);
}
/**
* 获取某个key 的属性,如果没有就给默认值
*
* @param key
* @param defaultValue
*/
@Override
public String getProperty(String key, String defaultValue) {
String value = getProperty(key);
return (value != null ? value : defaultValue);
}
/**
* 获取某个key 的属性,并且返回指定的泛型类型,并且给与了对应的默认值
*
* @param key
* @param targetType
* @param defaultValue
*/
@Override
public <T> T getProperty(String key, Class<T> targetType, T defaultValue) {
T value = getProperty(key, targetType);
return (value != null ? value : defaultValue);
}
/**
* 同上面的 getProperty,区别在于如果没有对应的值则会抛出异常
*
* @param key
*/
@Override
public String getRequiredProperty(String key) throws IllegalStateException {
String value = getProperty(key);
if (value == null) {
throw new IllegalStateException("Required key '" + key + "' not found");
}
return value;
}
/**
* 同上面的 getProperty,区别在于如果没有对应的值则会抛出异常
*
* @param key
* @param targetType
*/
@Override
public <T> T getRequiredProperty(String key, Class<T> targetType) throws IllegalStateException {
T value = getProperty(key,targetType);
if (value == null) {
throw new IllegalStateException("Required key '" + key + "' not found");
}
return value;
}
/**
* 解析占位符${...},站位符的值来自 getProperty
*
* @param text
* @return
*/
@Override
public String resolvePlaceholders(String text) {
if (this.nonStrictHelper == null) {
this.nonStrictHelper = createPlaceholderHelper(true);
}
return doResolvePlaceholders(text, this.nonStrictHelper);
}
@Override
public String resolveRequiredPlaceholders(String text) throws IllegalArgumentException {
if (this.strictHelper == null) {
this.strictHelper = createPlaceholderHelper(false);
}
return doResolvePlaceholders(text, this.strictHelper);
}
//==========================================================================================
// 这个类里面本身的方法
//==========================================================================================
/**
* 去选择 使用哪一个 占位符解析器,根据 ignoreUnresolvableNestedPlaceholders 这个全局变量来决定的
* 2个解析器的差别在于 没有解析到值是报错还是忽略
* @param value
* @return
*/
protected String resolveNestedPlaceholders(String value) {
return (this.ignoreUnresolvableNestedPlaceholders ?
resolvePlaceholders(value) : resolveRequiredPlaceholders(value));
}
private PropertyPlaceholderHelper createPlaceholderHelper(boolean ignoreUnresolvablePlaceholders) {
return new PropertyPlaceholderHelper(this.placeholderPrefix, this.placeholderSuffix,
this.valueSeparator, ignoreUnresolvablePlaceholders);
}
private String doResolvePlaceholders(String text, PropertyPlaceholderHelper helper) {
return helper.replacePlaceholders(text, this::getPropertyAsRawString);
}
/**
* 把string类型转成对应的数据结构
* @param value
* @param targetType
* @param <T>
* @return
*/
protected <T> T convertValueIfNecessary(Object value, Class<T> targetType) {
if (targetType == null || targetType == String.class) {
return (T) value;
}
//获取了转换器
ConversionService conversionServiceToUse = this.conversionService;
//开始转换
return conversionServiceToUse.convert(value, targetType);
}
//==========================================================================================
// 这个抽象类里面的抽象方法,需要子类去重写
//==========================================================================================
/**
* 表达式
* @param key
* @return
*/
protected abstract String getPropertyAsRawString(String key);
}
|
SQL
|
UTF-8
| 283 | 3.328125 | 3 |
[] |
no_license
|
USE employees;
SELECT from_date FROM dept_emp WHERE emp_no = '101010';
SELECT emp_no, CONCAT(first_name, ' ', last_name), hire_date
FROM employees
WHERE hire_date IN (
SELECT hire_date
FROM employees
WHERE emp_no = '101010'
);
SELECT title
FROM titles
WHERE
|
Shell
|
UTF-8
| 12,333 | 3.34375 | 3 |
[
"Apache-2.0",
"BSD-3-Clause",
"BSD-2-Clause-Views",
"BSD-2-Clause"
] |
permissive
|
#!/bin/bash
################################################################################
# Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The OpenAirInterface Software Alliance licenses this file to You under
# the Apache License, Version 2.0 (the "License"); you may not use this file
# except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#-------------------------------------------------------------------------------
# For more information about the OpenAirInterface (OAI) Software Alliance:
# contact@openairinterface.org
################################################################################
# file run_mme
# brief run script for MME.
# author Lionel GAUTHIER
# company Eurecom
# email: lionel.gauthier@eurecom.fr
################################
# include helper functions
################################
THIS_SCRIPT_PATH=$(dirname $(readlink -f $0))
source $THIS_SCRIPT_PATH/../BUILD/TOOLS/build_helper
declare -i g_run_msc_gen=0
declare g_msc_dir="/tmp"
declare g_mme_default_config_file="/usr/local/etc/oai/mme.conf"
declare g_mme_default_fqdn=`hostname`".openair4G.eur"
set_openair_env
function help()
{
echo_error " "
echo_error "Usage: run_mme [OPTION]..."
echo_error "Run the MME executable."
echo_error " "
echo_error "Options:"
echo_error "Mandatory arguments to long options are mandatory for short options too."
echo_error " -c, --config-file file_abs_path Config file to be used by MME if you don't want to use the default one: $g_mme_default_config_file"
echo_error " -D, --daemon Run the daemon."
echo_error " -g, --gdb Run with GDB."
echo_error " -G, --gdb-cmd cmd cmd_arg Append this GDB cmd to GDB command file (ex1: break Attach.c:272, ex2: watch 0xffee0002)."
echo_error " All repetitions of this argument are valid."
echo_error " -h, --help Print this help."
echo_error " -I, --install-mme-files Install MME config files. (NOT RECOMMENDED. See tutorials on https://gitlab.eurecom.fr/oai/openairinterface5g/wikis/OpenAirUsage or DOCS/EPC_User_Guide.pdf"
echo_error " -k, --kill Kill all running MME instances, exit script then."
echo_error " -m, --mscgen directory Generate mscgen output files in a directory"
echo_error " -s, --scenario-player scenario_abs_path Run MME with scenario player (check it is built in MME by setting TRACE_XML to 'True' in $THIS_SCRIPT_PATH/../BUILD/MME/CMakeLists.template)"
echo_error " Continue playing scenario(s) even if an error is encountered"
echo_error " -S, scenario_abs_path Run MME with scenario player (check it is built in MME by setting TRACE_XML to 'True' in $THIS_SCRIPT_PATH/../BUILD/MME/CMakeLists.template)"
echo_error " Stop playing scenario(s) on first error encountered"
echo_error " -v, --verbosity-level Verbosity level (0,1,2)."
echo_error " 0 -> ASN1 XER printf off"
echo_error " 1 -> ASN1 XER printf on and ASN1 debug off"
echo_error " 2 -> ASN1 XER printf on and ASN1 debug on"
}
function do_msc_gen()
{
cd $g_msc_dir
$THIS_SCRIPT_PATH/msc_gen
}
function do_xml_dump()
{
for file in `ls /tmp/mme_msg*`;
do
tmpfile=`mktemp`
xmllint --format $file > $tmpfile
cat $tmpfile | $SUDO tee $file > /dev/null
rm $tmpfile
done;
}
function control_c()
# run if user hits control-c
{
echo_warning "\nExiting by ctrl+c\n"
if [ $g_run_msc_gen -eq 1 ]; then
do_msc_gen
fi
do_xml_dump
exit $?
}
NAME=mmed
DAEMON=/usr/sbin/$NAME
DAEMON_ARGS=""
PIDFILE=/var/run/$NAME.pid
function main()
{
local -i run_gdb=0
local -i run_daemon=0
local -i run_scenario_player=0
local -i set_network_interfaces=0
local -i var_check_install_mme_files=0
local exe_arguments=" "
local mme_config_file=$g_mme_default_config_file
local scenario_file
local -a gdb_args
local -i gdb_index=0
until [ -z "$1" ]
do
case "$1" in
-c | --config-file)
mme_config_file=$2
echo "setting config file to: $mme_config_file"
shift 2;
;;
-D | --daemon)
run_daemon=1
echo "Run MME as a daemon"
shift;
;;
-g | --gdb)
run_gdb=1
echo "setting GDB flag to: $run_gdb"
shift;
;;
-G | --gdb-arg)
run_gdb=1
gdb_args[$gdb_index]="$2 $3"
echo "Appending gdb args: ${gdb_args[$gdb_index]}"
gdb_index=$((gdb_index + 1))
shift 3;
;;
-h | --help)
help
exit 0
;;
-i | --set-nw-interfaces)
set_network_interfaces=1
echo "setting network interfaces: $set_network_interfaces"
shift;
;;
-I | --install-mme-files)
echo "Install MME files: .conf files."
var_check_install_mme_files=1
shift;
;;
-k | --kill)
$SUDO killall -q mme
$SUDO rm /var/run/mme.pid
do_stop_daemon
exit 0
shift;
;;
-m | --mscgen)
g_msc_dir=$2
if [ -d "$g_msc_dir" ]; then
echo "setting mscgen log files to dir: $g_msc_dir"
g_run_msc_gen=1
shift 2;
else
echo_error "Mscgen log dir does not exist"
exit -1
fi
;;
-s | --scenario-player)
run_scenario_player=1
echo "setting scenario player flag to: $run_scenario_player"
scenario_file=$2
echo "setting scenario file to: $scenario_file"
exe_arguments="-s $scenario_file $exe_arguments"
DAEMON_ARGS=$DAEMON_ARGS" -s $scenario_file"
shift 2;
;;
-S)
run_scenario_player=1
echo "setting scenario player flag to: $run_scenario_player"
scenario_file=$2
echo "setting scenario file to: $scenario_file"
exe_arguments="-S $scenario_file $exe_arguments"
DAEMON_ARGS=$DAEMON_ARGS" -S $scenario_file"
shift 2;
;;
-v | --verbosity-level)
local verbosity_level=$2
echo "setting verbosity level to: $verbosity_level"
exe_arguments="-v $verbosity_level $exe_arguments"
shift 2;
;;
*)
echo "Unknown option $1"
help
exit 0
;;
esac
done
set_openair_env
cecho "OPENAIRCN_DIR = $OPENAIRCN_DIR" $green
#####################################
# Install config files
#####################################
if [ ! -f $mme_config_file ]; then
if [ $g_mme_default_config_file != $mme_config_file ]; then
echo_fatal "Please provide -c|--config-file valid argument (\"$mme_config_file\" not a valid file)"
fi
fi
if [ $var_check_install_mme_files -gt 0 ];then
$SUDO mkdir -p /usr/local/share/oai/test > /dev/null
$SUDO cp -rupv $OPENAIRCN_DIR/TEST/MME /usr/local/share/oai/test
$SUDO mkdir -p /usr/local/etc/oai/freeDiameter > /dev/null
if [ ! -f /usr/local/etc/oai/mme.conf ]; then
$SUDO cp -upv $THIS_SCRIPT_PATH/../ETC/mme.conf /usr/local/etc/oai
echo_fatal "Please customize /usr/local/etc/oai/mme.conf (interfaces, TAIs, GUMMEI, HSS hostname, SGW IP address, logging, etc), after, please re-run run_mme -I"
else
if [ $THIS_SCRIPT_PATH/../ETC/mme.conf -nt /usr/local/etc/oai/mme.conf ]; then
read -p "Do you want to update /usr/local/etc/oai/mme.conf with $OPENAIRCN_DIR/ETC/mme.conf ? <y/N> " prompt
if [[ $prompt =~ [yY](es)* ]]; then
$SUDO cp -upv $THIS_SCRIPT_PATH/../ETC/mme.conf /usr/local/etc/oai
echo_fatal "Please customize /usr/local/etc/oai/mme.conf (interfaces, TAIs, GUMMEI, HSS hostname, SGW IP address, logging, etc), after, please re-run run_mme -I"
fi
fi
fi
$SUDO cp -upv $THIS_SCRIPT_PATH/../ETC/mme_fd.conf /usr/local/etc/oai/freeDiameter
echo_warning "Be carefull /usr/local/etc/oai/freeDiameter/mme_fd.conf has realm, freeDiameter identity, HSS "
echo_warning "IPv4 address, HSS realm, HSS FQDN, all hardcoded, please check them and change them upon your needs."
# hardcoded MME diameter ID
fqdn=`hostname --fqdn`
if [ "a$fqdn" == "a" ]; then
echo_error "Please allow the IP resolution of MME FQDN (in /etc/hosts, example: 127.0.1.1 myhostname.openair4G.eur myhostname)."
echo_fatal "Please allow the IP resolution of HSS FQDN (in /etc/hosts, example: 127.0.1.1 hss.openair4G.eur hss if HSS run on MME host)."
fi
# generate certificates if necessary
echo_warning "Generating MME certificates using MME FQDN $fqdn, if you want to use an other"
echo_warning "FQDN, please modify mme_fd.conf, /etc/hosts consistently and then "
echo_warning "re-run $OPENAIRCN_DIR/SCRIPTS/check_mme_s6a_certificate /usr/local/etc/oai/freeDiameter $fqdn consistently"
$SUDO $OPENAIRCN_DIR/SCRIPTS/check_mme_s6a_certificate /usr/local/etc/oai/freeDiameter $fqdn
fi
#####################################
# Check executables
#####################################
if [ "$run_daemon" -eq 1 ]; then
if [ ! -e /usr/sbin/mmed ]; then
echo_fatal "Cannot find /usr/sbin/mmed executable, have a look at the output of build_mme -D ... executable"
fi
else
if [ ! -e /usr/local/bin/mme ]; then
echo_fatal "Cannot find /usr/local/bin/mme executable, have a look at the output of build_mme executable"
fi
fi
#####################################
# Clean old MSC generated files
#####################################
if [ $g_run_msc_gen -eq 1 ]; then
$SUDO rm -f /tmp/openair.msc.*
fi
if [ $set_network_interfaces -eq 1 ]; then
set_mme_network_interfaces $mme_config_file
fi
#####################################
# Clean old XML generated files
#####################################
$SUDO rm -f /var/log/mme_msg_*
#####################################
# Running daemon?
#####################################
DAEMON_ARGS=$DAEMON_ARGS" -c $mme_config_file"
if [ "$run_daemon" -eq 1 ]; then
# TODO options
$SUDO killall -q mme
do_stop_daemon
case "$?" in
0) echo_success "MME daemon was running -> stopped";;
1) ;;
2) echo_fatal "FAILURE: MME daemon was running -> could not stop it";;
esac
do_start_daemon
case "$?" in
0) echo_success "MME daemon started";;
1) echo_fatal "FAILURE: MME daemon was already running";;
2) echo_fatal "FAILURE: Cannot start MME daemon";;
esac
exit 0
fi
#####################################
# Running executable
#####################################
exe_arguments="-c $mme_config_file $exe_arguments"
if [ $run_gdb -eq 0 ]; then
# trap keyboard interrupt (control-c)
trap control_c SIGINT
$SUDO mme `echo $exe_arguments` 2>&1
else
# trap keyboard interrupt (control-c) is done by gdb
$SUDO touch ~/.gdb_mme
$SUDO chmod 777 ~/.gdb_mme
$SUDO echo "file mme" > ~/.gdb_mme
$SUDO echo "set args $exe_arguments " >> ~/.gdb_mme
for i in `seq 0 $gdb_index`; do
$SUDO echo "${gdb_args[$i]}" >> ~/.gdb_mme
done
$SUDO echo "run" >> ~/.gdb_mme
$SUDO cat ~/.gdb_mme
$SUDO gdb -n -x ~/.gdb_mme
if [ $g_run_msc_gen -eq 1 ]; then
#$SUDO do_msc_gen
cd $g_msc_dir
$SUDO $THIS_SCRIPT_PATH/msc_gen --profile MME --dir $g_msc_dir --type png
fi
fi
}
main "$@"
|
Java
|
UTF-8
| 1,328 | 3.96875 | 4 |
[
"MIT"
] |
permissive
|
package p06_Animals;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
List<Animal> animals = new ArrayList<>();
String type = reader.readLine();
while (!type.equals("Beast!")) {
String[] tokens = reader.readLine().split("\\s+");
try {
animals.add(getAnimalFromTokens(type, tokens));
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
type = reader.readLine();
}
reader.close();
for (Animal a : animals) {
System.out.println(a);
}
}
private static Animal getAnimalFromTokens(String type, String[] tokens) {
String name = tokens[0];
String gender = tokens[2];
int age = Integer.parseInt(tokens[1]);
switch (type) {
case "Dog":
return new Dog(name, gender, age);
case "Frog":
return new Frog(name, gender, age);
case "Cat":
return new Cat(name, gender, age);
case "Kitten":
return new Kitten(name, gender, age);
case "Tomcat":
return new Tomcat(name, gender, age);
default:
throw new IllegalArgumentException("Invalid input!");
}
}
}
|
PHP
|
UTF-8
| 463 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace User\Form;
/**
* Class LoginForm
* @package User\Form
*/
class LoginForm extends AbstractUserForm
{
/**
* Constructor
*/
public function __construct()
{
parent::__construct('login');
$this->add([
'name' => 'send',
'attributes' => [
'type' => 'submit',
'value' => 'Login',
'id' => 'submitbutton'
]
]);
}
}
|
Java
|
UTF-8
| 881 | 3.03125 | 3 |
[] |
no_license
|
package commons;
import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.bidimap.DualHashBidiMap;
import org.apache.commons.collections4.bidimap.DualTreeBidiMap;
import org.apache.commons.collections4.bidimap.TreeBidiMap;
public class DualTreeBidiMapDemo {
public static void main(String[] args) {
hashMap();
}
/**
* 有序双向Map
*/
public static void treeMap() {
BidiMap<String,String> map = new DualTreeBidiMap<>();
map.put("1","q");
map.put("2","w");
map.put("3","e");
}
/**
* 无序双向Map
*/
public static void hashMap() {
BidiMap<String,String> map = new DualHashBidiMap<>();
map.put("1","q");
map.put("2","w");
map.put("3","e");
//反转
System.out.println(map.inverseBidiMap().get("q"));
}
}
|
Python
|
UTF-8
| 2,773 | 3.453125 | 3 |
[
"MIT"
] |
permissive
|
#! /usr/bin/python
import threading
from threading import Thread, Lock
from std_msgs.msg import String
from time import sleep
import copy
import rospy
import random
# These will be initialized later
pub1 = None
pub2 = None
kill = False
# Create a lock that controls who has the ball
beach_lock = Lock()
""" Simple class that will be passed back and forth
betweeen threads. For learning purposes only"""
class BeachBall:
def __init__(self):
self.hits = 1
self.court_side = "No one has the ball"
# Initialize the beach ball
ball = BeachBall()
# Function 1 will be run by thread1
def function1(args):
while not kill:
print("hello1 from thread1")
# Get the lock so thread2 does not steal the ball
beach_lock.acquire()
ball.court_side = "thread 1 has the ball"
# Deep copy the ball so that we can release the
# lock.
myball = copy.deepcopy(ball)
beach_lock.release() # let thread2 have the ball
# ONLY PUBLISH THE DEEP COPIED VALUE
pub1.publish(
String(myball.court_side))
# Force the threads to run at different rates
# so that if someone remove the locks, the ball
# will get stolen
# (For demo purposes only)
sleep(random.randint(50,200)/ 100.0)
# Function2 will be called by thread2
def function2(args):
while not kill:
print("hello2 from thread2")
# Get the lock so thread1 does not steal the ball
beach_lock.acquire()
ball.court_side = "Thread 2 got the ball"
# Deep copy the ball so that we can release the
# lock.
myball = copy.deepcopy(ball)
beach_lock.release() # let thread1 get the ball
# ONLY PUBLISH THE DEEP COPIED VALUE
pub2.publish(
String(myball.court_side))
# Force the threads to run at different rates
# so that if someone remove the locks, the ball
# will get stolen
# (For demo purposes only)
sleep(random.randint(50,200)/ 100.0)
if __name__ == "__main__":
print('Initializing')
rospy.init_node("threadripper")
# initialize the publishers PRIOR to running the
# threads
# use 'rotopic echo /t1' to view thread1's output
# use 'rostopic echo/t2' to view thread2's output
pub1 = rospy.Publisher("/t1", String, queue_size=2)
pub2 = rospy.Publisher("/t2", String, queue_size=2)
print('Launching threads')
# Creat the threads, pass in a useless argument
t1 = Thread(target=function1, args=(10,))
t2 = Thread(target=function2, args=(10,))
# Let the games begin!
t1.start()
t2.start()
# Wait for a CTRL-C or a roslaunch kill (IMPORTANT)
while not rospy.is_shutdown():
pass
# Tell the threads to die
kill = True
# wait for the threads to terminate
t1.join()
t2.join()
# hooray, we done boys
print("Threads finished, done")
|
Java
|
UTF-8
| 2,348 | 2.34375 | 2 |
[
"MIT"
] |
permissive
|
package com.ruoyi.common.utils.ip;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.beans.BeanMap;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtil;
import com.ruoyi.common.utils.http.HttpUtil.Response;
import lombok.Builder;
import lombok.Data;
/**
* 地址转换类,使用高德开放API平台提供接口
*
* @author guanzhisong
*/
public class AddressUtils {
private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);
public static final String IP_URL = "https://restapi.amap.com/v3/ip";
public static String getRealAddressByIP(String ip) {
String address = "XX XX";
// 内网不查询
if (IpUtils.internalIp(ip)) {
return "内网IP";
}
if (!RuoYiConfig.isAddressEnabled()) {
return address;
}
@SuppressWarnings("unchecked")
Map<String, Object> paramMap = BeanMap.create(IpRequest.builder().key(RuoYiConfig.getAmapKey()).ip(ip).build());
String url = HttpUtil.buildUrl(IP_URL, HttpUtil.convertMap2Pair(paramMap));
try {
Response<IpResult> resp = HttpUtil.doGet(url, IpResult.class);
if (resp.success && resp.entity != null && resp.entity.isSuccess()) {
IpResult result = resp.entity;
if (result != null) {
address = result.getProvince() + "," + result.getCity();
}
}
} catch (Exception e) {
log.error("get ip {} addr error ", ip, e);
}
return address;
}
}
@Data
@Builder()
class IpRequest {
private String key;
private String ip;
@Builder.Default()
private String output = "JSON";
}
@Data
class IpResult {
private String INFOCODE_SUCCESS = "10000";
private String status;
private String info;
private String infocode;
private String province;
private String city;
private String adcode;
private String rectangle;
public boolean isSuccess() {
return StringUtils.equalsIgnoreCase(getInfocode(), INFOCODE_SUCCESS) && StringUtils.equalsIgnoreCase(status, "1");
}
}
|
Java
|
UTF-8
| 3,317 | 3.4375 | 3 |
[] |
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 homework.make.change;
/**
*
* @author kingk
*/
import java.util.Scanner;
public class HomeWorkMakeChange {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int price;
int provided;
int change = 0;
System.out.print("Enter the purchase price:");
price = (int) Math.round(keyboard.nextDouble() * 100);
System.out.print("Enter the amount given by the customer:");
provided = (int) Math.round(keyboard.nextDouble() * 100);
if (provided > price) {
System.out.println("The change is: " + ((provided - price)/100.00));
System.out.println("The customer should be given the change as follows:");
change = provided - price;
int hundreds=change/10000;
if(hundreds>0){
change=change&100000;
System.out.println(hundreds + " $100 bill(s)");
}
int fifties=change/5000;
if(fifties>0){
change=change%5000;
System.out.println(fifties + " $50 bill(s)");
}
int twenties = change / 2000;
if (twenties > 0) {
change = change % 2000;
System.out.println(twenties + " $20 bill(s)");
}
int tens = change / 1000;
if (tens > 0) {
change = change % 1000;
System.out.println(tens + " $10 bill(s)");
}
int fives = change / 500;
if (fives > 0) {
change = change % 500;
System.out.println(fives + " $5 bill(S)");
}
int ones = change / 100;
if (ones > 0) {
change = change % 100;
System.out.println(ones + " $1 bill(s)");
int half_dollar=change/50;
if (half_dollar>0){
change=change%50;
System.out.println(half_dollar+ " half dollar(s)");
}
int quarters = change / 25;
if (quarters > 0) {
change = change % 25;
System.out.println(quarters + " quarter coin(s)");
}
int dimes = change / 10;
if (dimes > 0) {
change = change % 10;
System.out.println(dimes + " dime coin(s)");
}
int nickels = change / 5;
if (nickels > 0) {
change = change % 5;
System.out.println(nickels + " nickel coin(s)");
}
int pennies = change;
System.out.println(pennies + " penny coin(s)");
}
if (provided < price) {
System.out.print("Not enough money!");
} else if (provided == price) {
System.out.print("No change is necessary!");
}
}
}
}
|
Python
|
UTF-8
| 2,910 | 2.546875 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Wed May 29 21:05:18 2019
@author: Hazem
"""
import pandas as pd
import auxiliary_functions as aux
import matplotlib.pyplot as plt
import numpy as np
from numpy.linalg import matrix_rank as rank
# most nan are in 2016, if we drop this we have to filter out less
cbf_loaded = pd.read_csv('processed/cbf_loaded.csv', index_col=0,
parse_dates=True).loc['2017': '2018']
buses = np.unique(sum(cbf_loaded.columns.str.split(' - '), []))
total = [4,6,10,12,18,24,30,50]
consec = [2,3,4,8,10,12,18,25]
#this is a much faster approach
nans = aux.nan_statistics(cbf_loaded)
def K_from_index_list(idx):
K = pd.DataFrame(index=np.unique(sum(idx.str.split(' - '), [])),
columns=idx)
for i in idx:
bus0, bus1 = i.split(' - ')
K.at[bus0, i] = 1
K.at[bus1, i] = -1
return K.fillna(0)
def is_connected(K):
return len(K) - rank(K) == 1
contained = pd.DataFrame(0, index=consec, columns=total)\
.rename_axis(index='consec.', columns='total')\
.stack()
for tot in total:
for con in consec:
included = nans\
.query('max_total_per_month <= @tot and consecutive <= @con')\
.index
contained[con, tot] = included
border = 'ES - FR'
border_contained = contained.apply(lambda x: border in x).unstack()
number_contained = contained.apply(len).unstack()
connected = contained.apply(lambda idx: is_connected(K_from_index_list(idx)))\
.unstack()
print('remaining borders after filtering:\n', number_contained)
print(f'{border} contained after filtering:\n', border_contained)
print(f'network is connected:\n', connected)
stats = aux.get_monthly_aggregation().abs().sum()
#%%
df = contained.apply(lambda x: stats.reindex(x).sum()).sort_values()
contained = contained.reindex(df.index)
#df.index = [str(s).replace('(', '').replace(')', '') for s in df.index.values]
fig, ax = plt.subplots(figsize=(8,12))
df.loc['inf', 'inf'] = stats.sum()
df.div(1e3)[::-1].plot.barh(ax=ax)
ax.set_ylim(bottom=0)
fig.tight_layout()
fig.savefig('plots/filered_out_total_flow.png')
filtered_in_step = pd.Series(
[contained.iloc[i].difference(contained.iloc[i-1]) if i else pd.Index([])
for i in range(len(contained))],
index=contained.index).apply(pd.Index.to_list)\
.astype(str).str.replace('\[|\]','')\
.to_frame('additional connector')\
.to_html('plots/filered_out_connector_diff.html')
# does not work
#for ypos, val in filtered_in_step.iteritems():
# ax.text(500, ypos, val)
#%%
nan_share = nans.query('total != 0').div(len(cbf_loaded))\
.sort_values(by='total', ascending=False)
fig, ax = plt.subplots()
nan_share.rename(columns={'max_total_per_month': 'max total per month'})\
.plot.bar(ax=ax)
fig.savefig(f'plots/nan_share_loaded.png')
|
Markdown
|
UTF-8
| 13,297 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
# Selecting HybSeq Genes Using MarkerMiner
### Learning Objectives
* Use existing genomic/transcriptomic resources for probe design
* Run MarkerMiner from the command line
* Select single copy genes for HybSeq probe design using multiple orthologs per gene
## Introduction: HybSeq Probe Design
HybSeq is a method of targeted sequencing that focuses on capturing coding (exon) regions from high-throughput sequencing libraries. Because each fragment in a library may contain both exon and intron sequences, HybSeq offers the possibility of capturing a "splash zone" of intron regions.
Targeted sequencing typically employs RNA probe sequences between 60 and 120 bp long. A reference sequence must be used for probe design, but probes can typically capture fragments with 10-15% sequence divergence. To maximize the chances that probes will capture target genes across a wider phylogenetic breadth, we recommend using multiple orthologs for each gene.
In this tutorial we will use Markerminer to explore the process of selecting low-copy nuclear genes for phylogenetic analysis.
## About MarkerMiner
Markerminer is a bioinformatics pipeline written by Srikar Chamala and colleagues to identify single copy genes by aligning transcriptome sequences to reference genomes. It is built for use with Angiosperms, but as we will see in this tutorial, it can be modified relatively easily for use with any reasonably well annotated genome.
Markerminer Website: https://bitbucket.org/srikarchamala/markerminer
Markerminer Publication: http://www.bioone.org/doi/full/10.3732/apps.1400115
**On the HybSeq_Kew_Workshop Atmosphere image, markerminer is located here**: `/usr/local/markerminer/`
## MarkerMiner Procedure
MarkerMiner identifies clusters of single-copy gene transcripts present in each user-provided transcriptome assembly by aligning and filtering transcripts against a user-selected reference proteome database using BLAST. Each transcript is searched against the reference proteome (BLASTX) and each peptide is searched against the transcripts (TBLASTN). MarkerMiner then generates a detailed tabular report of results for each putative orthogroup.
Next, MarkerMiner runs each of the single-copy gene clusters through a multiple sequence alignment (MSA) step using MAFFT and it outputs FASTA and Phylip files that users can use to assess phylogenetic utility (e.g. sequence variation) or, if appropriate, to conduct preliminary phylogenetic analyses.
Lastly, each of the single-copy gene MSAs are re-aligned with MAFFT (using the ‘--add’ functionality; Katoh and Frith 2012) profile alignment step using a user-selected coding reference sequence with intronic regions represented as Ns. Users can use MarkerMiner’s profile alignment output to identify putative splice junctions in the transcripts and to design primers or probes for targeted sequencing.
## Exploring MarkerMiner
Markerminer comes with prepared files for 15 angiosperm reference genomes. For each genome there are three important files:
1. **Protein sequences**: a FASTA file containing peptide sequences of all genes.
2. **Intron-masked gene region file**: a FASTA file with the same genes as above, but with introns identified and "hard-masked" using Ns.
3. **Single-copy gene list**: a text file containing the names of genes identified as either "strictly single copy" (orthogroup is single copy in all 17 angiosperm genomes) or "mostly single copy" (orthogroup duplicated in 1-3 species). [Reference: De Smet et al., 2013](http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3581894/)
To view the genomic resources in Makerminer directory on Atmosphere:
```
(hybpiper) [username@127.0.0.1 markerminer_test]$ cd /usr/local/markerminer/Resources
(hybpiper) [username@127.0.0.1 Resources]$ ls
Alyrata Bdistachyon Fvesca Mdomestica Mtruncatula Osativa Rcommunis Tcacao Zmays
Athaliana Cpapaya Gmax Mesculenta organisms.tsv Ptrichocarpa Sbicolor Vvinifera
(hybpiper) [username@127.0.0.1 Resources]$ ls Alyrata/
aly_CDS_IntronMasked.fa proteome.aly.tfa_db.phr proteome.aly.tfa_db.psq
proteome.aly.tfa proteome.aly.tfa_db.pin singleCopy_AL.txt
```
Use `less` to view the protein file `.tfa` and masked intron file `_CDS_Intron_Masked.fa` for one species. Note the strings of `NNNNN` in the Intron file. This "hard masking" will allow transcriptome sequences to easily align to the coding domain sequence (CDS) in the final stage of MarkerMiner.
The identification of intron regions during probe design will help avoid wasting probes on sequences that would span splice junctions. Even though no probes will be designed for intorn regions, they will still be captured during HybSeq as part of the "splash zone," as we will see in the [HybPiper tutorial](HybPiper.md).
Let's see what percentage of `Arabidopsis lyrata` genes are marked as single copy. First, count the number of peptides in the proteome file:
`grep '>' Alyrata/proteome.aly.tfa | wc -l`
Next, count the number of lines in the single copy gene list:
`wc -l Alyrata/singleCopy_AL.txt`
Finally, what percentage of those genes are **strictly** single copy?
`grep "Strictly" Alyrata/singleCopy_AL.txt | wc -l`
Compare the results of _A. lyrata_ to one of the other reference proteomes.
### Custom Genomes
Although it is beyond the scope of this tutorial, it is possible to add genomes to MarkerMiner. This will require creating the three files above, the most important of which is the Intron-masked gene region file. However, if a genome is reasonably well annotated with a Genome Feature Format (GFF) file, the procedure is relatively straightforward using bioinformatics tools such as [bedtools](http://bedtools.readthedocs.io/en/latest/).
The MarkerMiner code also needs to be edited to reflect the new genome additions. A more thorough explanation of the process of adding a genome to MarkerMiner [can be found here](https://www.evernote.com/l/AX8KWvd6jGpK3qq1mhBErCgXfXhja9a1kTA).
## Running MarkerMiner on Cyverse
The test dataset for MarkerMiner is included with the software. To run the test dataset, first create a new directory, then copy the test data:
```
(hybpiper) [username@127.0.0.1 ~]$ mkdir ~/markerminer_test/
(hybpiper) [username@127.0.0.1 ~]$ cd markerminer_test/
(hybpiper) [username@127.0.0.1 markerminer_test]$ cp /usr/local/markerminer/Sample_Data/Sample_input/* .
(hybpiper) [username@127.0.0.1 markerminer_test]$ ls
DAT1-sample.fa DAT2-sample.fasta DAT3-sample.fasta DAT4-sample.fasta
```
Each DAT file contains transcripts from a different species. The files are named beginning with a four-character code followed by a hyphen (e.g. `DAT3-`), and must end with `.fa` or `.fasta`.
Next, view the options available when running MarkerMiner:
```
(hybpiper) [username@127.0.0.1 markerminer_test]$ /usr/local/markerminer/markerMiner.py -h
usage: markerMiner.py [-h] [-transcriptFilesDir TRANSCRIPTFILESDIR]
[-singleCopyReference {Athaliana,Ptrichocarpa,Fvesca,Tcacao,Gmax,Cpapaya,Sbicolor,Mesculenta,Mdomestica,Rcommunis,Mtruncatula,Osativa,Alyrata,Bdistachyon,Vvinifera,Zmays}]
[-minTranscriptLen MINTRANSCRIPTLEN]
[-minProteinCoverage MINPROTEINCOVERAGE]
[-minTranscriptCoverage MINTRANSCRIPTCOVERAGE]
[-minSimilarity MINSIMILARITY] [-cpus CPUS]
-outputDirPath OUTPUTDIRPATH [-email EMAIL]
[-sampleData] [-debug] [-overwrite]
MarkerMiner: Effectively discover single copy nuclear loci in flowering
plants, from user-provided angiosperm transcriptomes. Your are using
MarkerMiner version 1.2
optional arguments:
-h, --help show this help message and exit
-transcriptFilesDir TRANSCRIPTFILESDIR
Absolute or complete path of the transcript files
fasta directory. Only files ending with '.fa' or
'.fasta' will be accepted. Also, all file names must
use the following naming convention: file names must
start with a four-letter species code followed by a
hyphen (e.g. 'DAT1-', 'DAT2-', 'DAT3-', etc. (default:
None)
-singleCopyReference {Athaliana,Ptrichocarpa,Fvesca,Tcacao,Gmax,Cpapaya,Sbicolor,Mesculenta,Mdomestica,Rcommunis,Mtruncatula,Osativa,Alyrata,Bdistachyon,Vvinifera,Zmays}
Choose from the available single copy reference
datasets (default: Athaliana)
-minTranscriptLen MINTRANSCRIPTLEN
min transcript length (default: 900)
-minProteinCoverage MINPROTEINCOVERAGE
min percent of protein length aligned (default: 80)
-minTranscriptCoverage MINTRANSCRIPTCOVERAGE
min percent of transcript length aligned (default: 70)
-minSimilarity MINSIMILARITY
min similarity percent with which seqeunces are
aligned (default: 70)
-cpus CPUS cpus to be used (default: 4)
-outputDirPath OUTPUTDIRPATH
Absolute or complete path of output directory
(default: .)
-email EMAIL Specify email address to be notified on job completion
(default: None)
-sampleData run pipeline on sample datasets (default: False)
-debug turn on debug mode (default: False)
-overwrite overwrite results if output folder exists (default:
False)
```
The minimum requirement to run MarkerMiner is to specify `-transcriptFilesDir`, `-singleCopyReference`, and `-outputDirPath`. Four other parameters control how the results of BLAST searches will be filtered.
Examine the default parameter settings for `-minTranscriptLen`, `-minProteinCoverage`, `-minTranscriptCoverage`, and `-minSimilarity`.
Why do you think each of these parameters were chosen, and what would happen if they were altered from their default settings (lower or higher)?
Run MarkerMiner with the default parameters. Note that the path to the input and output files must be an *absolute path*, not a *relative path*:
```
(hybpiper) [username@127.0.0.1 ~]$ /usr/local/markerminer/markerMiner.py \
-transcriptFilesDir ~/markerminer_test \
-singleCopyReference Athaliana \
-outputDirPath ~/markerminer_test_Athaliana
```
This should finish in approximately 2 minutes. You may see some errors from `tblastn`, but these are normal and have to do with ambiguity codes in the Athaliana protein translation.
### Examining Markerminer Output
Uncompress the results:
```
(hybpiper) [username@127.0.0.1 ~]$ tar -zxf markerminer_test_Athaliana.tar.gz
(hybpiper) [username@127.0.0.1 ~]$ cd markerminer_test_Athaliana
(hybpiper) [username@127.0.0.1 markerminer_test_Athaliana]$ ls
BLAST MAFFT_NUC_ALIGN_FASTA single_copy_genes.secondaryTranscripts.txt
input_transcriptomes.txt MAFFT_NUC_ALIGN_PHY single_copy_genes.txt
LENGTH_FILTERED_FASTA markerminer_run_logfile.txt
MAFFT_ADD_REF_ALIGN_FASTA NUC_FASTA
```
A brief tour of the directories and summary files created by MarkerMiner
* **BLAST**: Contains results of reciprocal BLAST searches (transcriptome --> genome and genome --> transcriptome)
* **input_transcriptomes.txt** A list of all the transcriptomes used in the MarkerMiner run. Useful for checking if the transcriptome files were labeled properly.
* **LENGTH_FILTERED_FASTA** Transcriptome files subset for genes that had the minimum length (specified by `-minTranscriptLen`, the default is 900bp).
* **MAFFT_ADD_REF_ALIGN_FASTA** The final output of MarkerMiner for probe design-- alignments between transcriptome sequences and the intron-masked gene region genome reference for each gene.
* **MAFFT_NUC_ALIGN_FASTA** Alignments among transcriptome sequences that each had BLAST hits to the same gene in the reference genome.
* **MAFFT_NUC_ALIGN_PHY** Same as above but in Phylip format.
* **markerminer_run_logfile.txt** A log of the Markerminer process.
* **NUC_FASTA** Unaligned transcripts from each transcriptome separated by homologous reference genome gene.
* **single_copy_genes.txt** A table listing each reference genome gene (rows) and homologous transcript IDs from each transcriptome (column).
* **single_copy_genes.SecondaryTranscripts.txt** A list of alternative transcripts that had a BLAST hit to the same reference genome gene but were not chosen for the final alignment. These are typically splice forms, but could also be very recent paralogs.
In the VNC Viewer, open Alivew (Applications/Other). In the File menu of Aliview, navigate to the MarkerMiner output directory and open one of the alignments in `MAFFT_ADD_REF_ALIGN_FASTA`.
<img src=images/markerminer_aliview.png width="500">
#### Questions
* How many transcripts are aligned to the reference gene?
* Are the transcript sequences properly aligned to the reference gene?
* Do the intron/exon boundaries appear to be consistent?
* What is the affect of using different parameter settings?
* How would the results change if Alyrata was used instead of Athaliana?
|
Ruby
|
UTF-8
| 3,071 | 4.15625 | 4 |
[] |
no_license
|
class Board
def initialize(board_string)
@board_array = board_string.chars
@board = {}
@possible_values = [1,2,3,4,5,6,7,8,9]
@row = []
@column = []
gen_board
end
def print_board
board_array = []
@board.each_value { |value| board_array << value }
print "+-------------------+"
puts
board_array.each_slice(9) do |row|
print "| " + row.join(" ").gsub(/["0"]/, '_') + " |"
puts
end
print "+-------------------+"
puts
end
def solve
@board.each do |key, value|
get_value(key)
get_column(key)
end
end
#gen board needs to create a hash with key represented as column (A)/row (0) intersections ("A0") and values as board_array (1..9 or -)
def gen_board
("A".."I").each do |row|
(0..8).each_with_index { |column, value| @board.merge!( { "#{row}#{column}".to_sym => @board_array.shift.to_i } ) }
end
return @board
end
#get all the values from a row, each puts every 9 keys from board_array
#get all values from a column, each puts keys with (column)"index" from board_array
def get_row(column_label)
(0..8).each do |row_label|
@row << get_value( column_label + row_label.to_s )
end
return @row
end
def get_column(row_label)
("A".."I").each do |column_label|
@column << get_value( column_label + row_label.to_s )
end
return @column
end
#get all the values from a master cell
def get_master_cell(initial_cell)
starting_point = initial_cell.to_sym
master_cell = { }
letter = initial_cell[0]
number = initial_cell[1]
a_symbol = nil
3.times do
3.times do
a_symbol = ( letter + number ).to_sym
master_cell.merge!( { a_symbol => @board[ a_symbol ] } )
number.next!
end
letter.next!
number = initial_cell[1]
end
return master_cell
end
def get_value(key)
@board[key.to_sym]
end
def set_value(key, value)
@board[key.to_sym] = value
end
end
#cell
#master_cell = small grid of 3x3
#possible_cell_values = hash with keys are cells => values are possible numbers
#true_value = the actual value of the cell
#board = the full board, hash
#Pseudocode:
# the sudoku_puzzles.txt is BY ROW, slice(9) to each string, populate by row number first slice goes to row 1
# second slice goes to row 2, etc.
#nope, we're gonna do hashey hash
# Refer back to boggle challenge for population
# If there is a value [1..9],
# set that cell (key) to that integer
# else (there is -), then leave array [1..9]
#use .values_at function to get master_cell ==> use this one hash.values_at("A0", "B0", "C0", "A1", "B1", "C1", "A2", "B2", "C2") -- this returns an array of values
# if .size == array.uniq.size
# [1,2,3,4, -, 9, 8] =
#TESTS
board_array = "1-58-2----9--764-52--4--819-19--73-6762-83-9-----61-5---76---3-43--2-5-16--3-89--"
trial = Board.new(board_array)
# p trial.gen_board
#p trial.get_row("A")
#p trial.get_column(2)
# p trial.get_value("G3")
p trial.get_master_cell("D6")
# trial.print_board
p
|
TypeScript
|
UTF-8
| 790 | 2.6875 | 3 |
[] |
no_license
|
import AppError from '@shared/errors/AppError';
import { getCustomRepository } from 'typeorm';
import { IUser } from '../interfaces/user';
import User from '../typeorm/entities/User';
import UserRepository from '../typeorm/repositories/UserRepository';
export default class CreateUserService {
public async execute({ email, name, password }: IUser): Promise<User> {
const userRepository = getCustomRepository(UserRepository);
const userExists = await userRepository.findByEmail(email);
if (userExists) {
throw new AppError("Usuario já cadastrado");
}
const user = userRepository.create({
email,
name,
password
});
await userRepository.save(user);
return user;
}
}
|
Python
|
UTF-8
| 919 | 2.796875 | 3 |
[] |
no_license
|
#!/usr/bin/env python
# Tom Poorten, December 2017, UC Davis
# get subset of fasta records and make new fasta file
from Bio import SeqIO
import argparse
parser = argparse.ArgumentParser(description='creates a new fasta file with only specified records, which are provided in a text file')
parser.add_argument('-i', help='input fasta', dest='fastaIn',required=True)
parser.add_argument('-k', help='records to keep; given from a text file', dest='fileIn',required=True)
parser.add_argument('-o', help='output fasta', dest='fastaOut',required=True)
args = parser.parse_args()
fastaIn = args.fastaIn
fileIn = args.fileIn
fastaOut = args.fastaOut
file = open(fileIn)
recsToKeep = []
for line in file:
recsToKeep.append(line.rstrip())
file.close()
record_dict = SeqIO.index(fastaIn, "fasta")
with open(fastaOut, "w") as output_handle:
for i in recsToKeep:
SeqIO.write(record_dict[i], output_handle, "fasta")
|
Ruby
|
UTF-8
| 2,142 | 3.3125 | 3 |
[] |
no_license
|
require 'rspec'
require './lib/prct07'
describe Fraccion do
before :each do
@a = Fraccion.new(3,9)
@b = Fraccion.new(4,20)
@c = Fraccion.new(3,9)
@d = Fraccion.new(-3,-9)
@e = Fraccion.new(-4,20)
end
it "Debe existir un numerador" do
@a.num.should eq 3
@b.num.should eq 4
end
it "Debe existir un denominador" do
@a.den.should eq 9
@b.den.should eq 20
end
it "Debe estar en forma reducida" do
@a.simp.show_frac.should eq "(1/3)"
@b.simp.show_frac.should eq "(1/5)"
end
it "Debe mostrar la fraccion en la forma a/b" do
@a.show_frac.should eq "(3/9)"
@b.show_frac.should eq "(4/20)"
end
it "Debe mostrar la fraccion en formato float" do
@a.to_f.should eq 0.3333333333333333
@b.to_f.should eq 0.2
end
it "Debe mostrar la fraccion en formato float" do
@a.to_f.should eq 0.3333333333333333
@b.to_f.should eq 0.2
end
it "Debe comparar dos fracciones con ==" do
(@a==@b).should eq false
(@a==@c).should eq true
end
it "Debe calcular el valor absoluto" do
@d.abs.should eq "(3/9)"
@e.abs.should eq "(4/20)"
end
it "Debe calcular el reciproco" do
@a.reciproco.should eq "(9/3)"
@d.reciproco.should eq "(-9/-3)"
end
it "Debe calcular el opuesto" do
@c.opuesto.should eq "(-3/-9)"
@d.opuesto.should eq "(3/9)"
@e.opuesto.should eq "(4/20)"
end
it "Debe calcular la suma de 2 fracciones" do
(@a+@b).should eq "(8/15)"
end
it "Debe calcular la resta de 2 fracciones" do
(@a-@b).should eq "(2/15)"
end
it "Debe calcular la multiplicacion de 2 fracciones" do
(@a*@b).should eq "(1/15)"
end
it "Debe calcular la division de 2 fracciones" do
(@a/@b).should eq "(5/3)"
end
it "Debe comparar si una fraccion es mayor que otra" do
(@a>@b).should eq true
end
it "Debe comparar si una fraccion es menor que otra" do
(@a<@b).should eq false
end
it "Debe comparar si una fraccion es mayor o igual que otra" do
(@a>=@b).should eq true
end
it "Debe comparar si una fraccion es menor o igual que otra" do
(@a<=@c).should eq true
end
it "Debe devolver el valor absoluto de la multiplicacion" do
@a.modif(@e).should eq "(1/15)"
end
end
|
Java
|
UTF-8
| 3,714 | 1.945313 | 2 |
[] |
no_license
|
package com.bpom.dsras.fragment;
import android.annotation.SuppressLint;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bpom.dsras.R;
import com.bpom.dsras.adapter.DivisiListAdapter;
import com.bpom.dsras.adapter.SearchGlobalAdapter;
import com.bpom.dsras.callback.Callback;
import com.bpom.dsras.object.Reports;
import com.bpom.dsras.service.NetworkConnection;
import com.bpom.dsras.utility.ConstantAPI;
import com.bpom.dsras.utility.SharedPreferencesProvider;
import com.bpom.dsras.utility.Utility;
import org.json.JSONException;
import java.io.Serializable;
import java.util.HashMap;
/**
* Created by Dea Synthia on 10/24/2016.
*/
public class SearchGlobalFragment extends Fragment implements Callback {
private final static String TAG = SearchGlobalFragment.class.getSimpleName();
private Context context;
private View view;
private Serializable data;
private RecyclerView rv_divisilist;
private LinearLayoutManager rv_divisilist_llm;
private DivisiListAdapter rv_divisilist_adapter;
private SearchGlobalAdapter rv_searchglobal_adapter;
private HashMap<String, HashMap<String, HashMap<String, Object>>> searchGlobalList = new HashMap<>();
private Callback callback;
private HashMap<String, String> param_divisilist = new HashMap<>();
private Messenger messenger;
private Message message;
private Bundle bundle;
private Handler handler;
private String[] stringResponse = {""};
private String url;
private String keyword;
public SearchGlobalFragment() {
}
@SuppressLint("ValidFragment")
public SearchGlobalFragment(Context context, String keyword, Serializable data, Callback listener) {
this.context = context;
this.keyword = keyword;
this.data = data;
this.callback = listener;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
this.view = inflater.inflate(R.layout.content_divisilist, container, false);
return this.view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d(TAG, "Search result " + this.keyword);
this.rv_divisilist = (RecyclerView) view.findViewById(R.id.rv_divisilist);
this.rv_divisilist_llm = new LinearLayoutManager(this.context);
this.rv_divisilist.setHasFixedSize(true);
this.rv_divisilist.setLayoutManager(this.rv_divisilist_llm);
try {
this.searchGlobalList = Utility.ParserJSONUtility.getSearchGlobalListResultFromJSON(keyword);
Log.d(TAG, "divisiList " + this.searchGlobalList.toString());
this.rv_searchglobal_adapter = new SearchGlobalAdapter(this.context, this.searchGlobalList, this.data, this);
this.rv_divisilist.setAdapter(this.rv_searchglobal_adapter);
} catch (JSONException e) {
Log.d(TAG, "Exception " + e.getMessage());
}
}
@Override
public void onCallback(Serializable object) {
callback.onCallback(object);
}
}
|
C#
|
UTF-8
| 1,065 | 3.203125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _3._2
{
class ClassRoom
{
private List<Pupil> listOfPupils = new List<Pupil>();
public ClassRoom(Pupil pupil1, Pupil pupil2, Pupil pupil3, Pupil pupil4)
{
listOfPupils.Add(pupil1);
listOfPupils.Add(pupil2);
listOfPupils.Add(pupil3);
listOfPupils.Add(pupil4);
}
public ClassRoom(Pupil pupil1, Pupil pupil2, Pupil pupil3)
{
listOfPupils.Add(pupil1);
listOfPupils.Add(pupil2);
listOfPupils.Add(pupil3);
}
public ClassRoom(Pupil pupil1, Pupil pupil2)
{
listOfPupils.Add(pupil1);
listOfPupils.Add(pupil2);
}
public void PrintInformation()
{
foreach(Pupil p in listOfPupils) {
p.Read();
p.Relax();
p.Study();
p.Write();
}
}
}
}
|
C++
|
UTF-8
| 1,879 | 3.65625 | 4 |
[] |
no_license
|
#include "bstset.h"
BSTset::BSTset()
{
root = new TreeNode('a',
new TreeNode('b',
new TreeNode('d', NULL, NULL),
new TreeNode('e', NULL, NULL)),
new TreeNode('c',
new TreeNode('f', NULL, NULL),
new TreeNode('g', NULL, NULL)));
count = 7;
}
BSTset::~BSTset()
{
//dtor
}
void BSTset::remove (char data)
{
TreeNode* &node = find(root, data);
if(node == NULL)
{
return;
}
if(isLeaf(node))
{
delete node;
node = NULL;
}
else if(node->left != NULL && node->right == NULL)
{
TreeNode* tmp = node;
node = node->left;
delete tmp;
}
else if(node->left == NULL && node->right != NULL)
{
TreeNode* tmp = node;
node = node->left;
delete tmp;
}
}
bool BSTset::isLeaf(TreeNode* node) {return (node->left == NULL && node->right == NULL); }
bool BSTset::contains(char data)
{
return (find(root, data));
}
void BSTset::insert(char data)
{
TreeNode* &node = find(root, data);
if(node == NULL){
node = new TreeNode(data, NULL, NULL);
count++;
}
}
int BSTset::size(){return count; }
void BSTset::printInorder(ostream& out, TreeNode* node){
if(node != NULL)
{
printInorder(out, node->left);
out << node->data << " ";
printInorder(out, node->right);
}
}
TreeNode* &BSTset::find(TreeNode* &node, char data)
{
if(node == NULL || node->data == data) {return node; }
if(data < node->data){return find(node->left, data); }
if (data > node->data){return find(node->right, data); }
else{return node; }
}
ostream& operator <<(ostream& out, BSTset set)
{
set.printInorder(out, set.root);
return out;
}
|
Java
|
UTF-8
| 986 | 2.421875 | 2 |
[] |
no_license
|
package org.perform.hibernate.model;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
@Entity
public class Coach {
@Id
private Integer id;
@Column
private String name;
@ElementCollection(fetch=FetchType.EAGER)
@JoinTable(name = "COACH_ADDRESS", joinColumns = @JoinColumn(name = "COACH_ID") )
private Collection<Address> addresses = new ArrayList<>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Collection<Address> getAddresses() {
return addresses;
}
public void setAddresses(Collection<Address> addresses) {
this.addresses = addresses;
}
}
|
Python
|
UTF-8
| 4,039 | 2.59375 | 3 |
[] |
no_license
|
#!/usr/bin/python -u
"""
packet.py
Broodwar IP capture, not stable.
2021.07.02 by stypr (https://harold.kim/)
"""
import os
import sys
import locale
import binascii
import subprocess
import pyshark
def read_from(s, start):
""" (bytes, bytes) -> bytes
Read from a given character.
>>> read_from(b"test12341", b"1")
2341
"""
return start.join(s.split(start)[1:])
def read_until(s, until=b"\x00"):
""" (bytes) -> bytes
Read until a given character
"""
return s.split(until)[0]
def trace_room(device_interface):
""" (str) -> NoneType
Trace StarCraft room information
"""
user_list = {}
user_host = None
capture = pyshark.LiveCapture(interface=device_interface)
for packet in capture.sniff_continuously():
try:
# skip host
_key = packet.ip.src
if _key.startswith("158.115."):
if (packet.udp.payload.startswith("08:01:12:") and
packet.udp.payload[12:14] == "01"):
payload = packet.udp.payload.replace(":", "")
payload = binascii.unhexlify(payload).split(b",")
# Remove all from the user list when a new packet arrives
if len(payload) == 16:
user_host = payload[11].split(b"\r")[0].decode()
user_list = {}
continue
if packet.udp.dstport == "6112":
payload = packet.udp.payload.replace(":", "")
payload = binascii.unhexlify(payload)
# Magic Header
if payload.startswith(b"\x08\x01\x12"):
_packet_header = payload[:0x15]
_packet_content = payload[0x15:]
_packet_header_type = payload[0x3]
_packet_is_info = _packet_header_type == 0xa6
_packet_is_chat = _packet_header[0x14] == 0x4c
_packet_is_ping = _packet_header_type == 0x11
# 유저 정보 파싱
if _packet_is_info:
# print(_packet_content)
_packet_user = _packet_content[0x2]
_packet_battle_tag = read_until(_packet_content[0x6:], b"\x00")
_packet_nickname = read_from(read_from(_packet_content, _packet_battle_tag), b"??")
_packet_nickname = read_until(_packet_nickname[0x62:], b"\x00")
print("ID:", _packet_user, "/ BTag:", _packet_battle_tag.decode(), "/ Nickname:", _packet_nickname.decode())
# 채팅 내용 파싱
if _packet_is_chat:
_packet_chat_user = payload[0x12]
_packet_chat_content = read_until(_packet_content, b"\x00").decode()
print("ID:", _packet_chat_user, "/ Data:", _packet_chat_content)
# TODO: 퇴장내용파싱, 방장확인, 보내는 패킷 알아보기 (여러 서버로 보내는 것 같음.)
"""
# insert info
_data = f"{nickname}:{battle_tag}"
if (user_list.get(_key) and
_data not in user_list[_key]):
user_list[_key].append(_data)
else:
user_list[_key] = [_data]
# print_status(user_list, user_host)
"""
except AttributeError:
# Not UDP
continue
if __name__ == "__main__":
# Need NPF device ID for getting traffic
# _encoding = locale.getpreferredencoding()
# cmd = ["C:\\Program Files\Wireshark\\tshark.exe", "-D"]
# p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
# p.wait()
# print(p.stdout.read().decode(_encoding).strip())
# os.popen("")c
DEVICE_ID = "\\Device\\NPF_{8A1296EE-A0F9-49ED-877F-5E050B5629BB}"
trace_room(DEVICE_ID)
|
JavaScript
|
UTF-8
| 27,478 | 3.265625 | 3 |
[] |
no_license
|
// ==UserScript==
// @name Travian
// @namespace Osieczna
// @include http://ts*.travian.*/dorf1.php*
// @version 1
// @grant none
// ==/UserScript==
//
// JavaScript unit
// Add-on for the string and number manipulation
//
// Copyright (c) 2005, 2006, 2007, 2010, 2011 by Ildar Shaimordanov
//
/*
The following code is described in ECMA drafts and
might be implemented in the future of ECMA
*/
if ( ! String.prototype.repeat ) {
/**
* object.x(number)
* object.repeat(number)
* Transform the string object multiplying the string
*
* @param number Amount of repeating
* @return string
* @access public
* @see http://svn.debugger.ru/repos/jslibs/BrowserExtensions/trunk/ext/string.js
* @see http://wiki.ecmascript.org/doku.php?id=harmony:string_extras
*/
String.prototype.repeat = function(n)
{
n = Math.max(n || 0, 0);
return new Array(n + 1).join(this.valueOf());
};
}
if ( ! String.prototype.startsWith ) {
/**
* Returns true if the sequence of characters of searchString converted
* to a String match the corresponding characters of this object
* (converted to a String) starting at position. Otherwise returns false.
*
* @param string
* @param integer
* @return bollean
* @acess public
*/
String.prototype.startsWith = function(searchString, position)
{
position = Math.max(position || 0, 0);
return this.indexOf(searchString) == position;
};
}
if ( ! String.prototype.endsWith ) {
/**
* Returns true if the sequence of characters of searchString converted
* to a String match the corresponding characters of this object
* (converted to a String) starting at endPosition - length(this).
* Otherwise returns false.
*
* @param string
* @param integer
* @return bollean
* @acess public
*/
String.prototype.endsWith = function(searchString, endPosition)
{
endPosition = Math.max(endPosition || 0, 0);
var s = String(searchString);
var pos = this.lastIndexOf(s);
return pos >= 0 && pos == this.length - s.length - endPosition;
};
}
if ( ! String.prototype.contains ) {
/**
* If searchString appears as a substring of the result of converting
* this object to a String, at one or more positions that are greater than
* or equal to position, then return true; otherwise, returns false.
* If position is undefined, 0 is assumed, so as to search all of the String.
*
* @param string
* @param integer
* @return bollean
* @acess public
*/
String.prototype.contains = function(searchString, position)
{
position = Math.max(position || 0, 0);
return this.indexOf(searchString) != -1;
};
}
if ( ! String.prototype.toArray ) {
/**
* Returns an Array object with elements corresponding to
* the characters of this object (converted to a String).
*
* @param void
* @return array
* @acess public
*/
String.prototype.toArray = function()
{
return this.split('');
};
}
if ( ! String.prototype.reverse ) {
/**
* Returns an Array object with elements corresponding to
* the characters of this object (converted to a String) in reverse order.
*
* @param void
* @return string
* @acess public
*/
String.prototype.reverse = function()
{
return this.split('').reverse().join('');
};
}
/*
The following ode is not described in ECMA specs or drafts.
*/
/**
* String.validBrackets(string)
* Checks string to be valid brackets. Valid brackets are:
* quotes - '' "" `' ``
* single - <> {} [] () %% || // \\
* double - miltiline comments
* /** / C/C++ like (without whitespace)
* <??> PHP like
* <%%> ASP like
* (**) Pascal like
*
* @param string Brackets (left and right)
* @return boolean Result of validity of brackets
* @access static
*/
String.validBrackets = function(br)
{
if ( ! br ) {
return false;
}
var quot = "''\"\"`'``";
var sgl = "<>{}[]()%%||//\\\\";
var dbl = "/**/<??><%%>(**)";
return (br.length == 2 && (quot + sgl).indexOf(br) != -1)
|| (br.length == 4 && dbl.indexOf(br) != -1);
};
/**
* object.bracketize(string)
* Transform the string object by setting in frame of valid brackets
*
* @param string Brackets
* @return string Bracketized string
* @access public
*/
String.prototype.brace =
String.prototype.bracketize = function(br)
{
var string = this;
if ( ! String.validBrackets(br) ) {
return string;
}
var midPos = br.length / 2;
return br.substr(0, midPos) + string.toString() + br.substr(midPos);
};
/**
* object.unbracketize(string)
* Transform the string object removing the leading and trailing brackets
* If the parameter is not defined the method will try to remove existing valid brackets
*
* @param string Brackets
* @return string Unbracketized string
* @access public
*/
String.prototype.unbrace =
String.prototype.unbracketize = function(br)
{
var string = this;
if ( ! br ) {
var len = string.length;
for (var i = 2; i >= 1; i--) {
br = string.substring(0, i) + string.substring(len - i);
if ( String.validBrackets(br) ) {
return string.substring(i, len - i);
}
}
}
if ( ! String.validBrackets(br) ) {
return string;
}
var midPos = br.length / 2;
var i = string.indexOf(br.substr(0, midPos));
var j = string.lastIndexOf(br.substr(midPos));
if (i == 0 && j == string.length - midPos) {
string = string.substring(i + midPos, j);
}
return string;
};
/**
* object.radix(number, number, string)
* Transform the number object to string in accordance with a scale of notation
* If it is necessary the numeric string will aligned to right and filled by '0' character, by default
*
* @param number Radix of scale of notation (it have to be greater or equal 2 and below or equal 36)
* @param number Width of numeric string
* @param string Padding chacracter (by default, '0')
* @return string Numeric string
* @access public
*/
Number.prototype.radix = function(r, n, c)
{
return this.toString(r).padding(-n, c);
// return this.toString(r).padding(-Math.abs(n), c);
};
/**
* object.bin(number, string)
* Transform the number object to string of binary presentation
*
* @param number Width of numeric string
* @param string Padding chacracter (by default, '0')
* @return string Numeric string
* @access public
*/
Number.prototype.bin = function(n, c)
{
return this.radix(0x02, n, c);
// return this.radix(0x02, (n) ? n : 16, c);
};
/**
* object.oct(number, string)
* Transform the number object to string of octal presentation
*
* @param number Width of numeric string
* @param string Padding chacracter (by default, '0')
* @return string Numeric string
* @access public
*/
Number.prototype.oct = function(n, c)
{
return this.radix(0x08, n, c);
// return this.radix(0x08, (n) ? n : 6, c);
};
/**
* object.dec(number, string)
* Transform the number object to string of decimal presentation
*
* @param number Width of numeric string
* @param string Padding chacracter (by default, '0')
* @return string Numeric string
* @access public
*/
Number.prototype.dec = function(n, c)
{
return this.radix(0x0A, n, c);
};
/**
* object.hexl(number, string)
* Transform the number object to string of hexadecimal presentation in lower-case of major characters (0-9 and a-f)
*
* @param number Width of numeric string
* @param string Padding chacracter (by default, '0')
* @return string Numeric string
* @access public
*/
Number.prototype.hexl = function(n, c)
{
return this.radix(0x10, n, c);
// return this.radix(0x10, (n) ? n : 4, c);
};
/**
* object.hex(number, string)
* Transform the number object to string of the hexadecimal presentation
* in upper-case of major characters (0-9 and A-F)
*
* @param number Width of numeric string
* @param string Padding chacracter (by default, '0')
* @return string Numeric string
* @access public
*/
Number.prototype.hex = function(n, c)
{
return this.radix(0x10, n, c).toUpperCase();
};
/**
* object.human([digits[, true]])
* Transform the number object to string in human-readable format (e.h., 1k, 234M, 5G)
*
* @example
* var n = 1001;
*
* // will output 1.001K
* var h = n.human(3);
*
* // will output 1001.000
* var H = n.human(3, true);
*
* @param integer Optional. Number of digits after the decimal point. Must be in the range 0-20, inclusive.
* @param boolean Optional. If true then use powers of 1024 not 1000
* @return string Human-readable string
* @access public
*/
Number.prototype.human = function(digits, binary)
{
var n = Math.abs(this);
var p = this;
var s = '';
var divs = arguments.callee.add(binary);
for (var i = divs.length - 1; i >= 0; i--) {
if ( n >= divs[i].d ) {
p /= divs[i].d;
s = divs[i].s;
break;
}
}
return p.toFixed(digits) + s;
};
/**
* Subsidiary method.
* Stores suffixes and divisors to use in Number.prototype.human.
*
* @param boolean
* @param string
* @param divisor
* @return array
* @access static
*/
Number.prototype.human.add = function(binary, suffix, divisor)
{
var name = binary ? 'div2' : 'div10';
var divs = Number.prototype.human[name] = Number.prototype.human[name] || [];
if ( arguments.length < 3 ) {
return divs;
}
divs.push({s: suffix, d: Math.abs(divisor)});
divs.sort(function(a, b)
{
return a.d - b.d;
});
return divs;
};
// Binary prefixes
Number.prototype.human.add(true, 'K', 1 << 10);
Number.prototype.human.add(true, 'M', 1 << 20);
Number.prototype.human.add(true, 'G', 1 << 30);
Number.prototype.human.add(true, 'T', Math.pow(2, 40));
// Decimal prefixes
Number.prototype.human.add(false, 'K', 1e3);
Number.prototype.human.add(false, 'M', 1e6);
Number.prototype.human.add(false, 'G', 1e9);
Number.prototype.human.add(false, 'T', 1e12);
/**
* object.fromHuman([digits[, binary]])
* Transform the human-friendly string to the valid numeriv value
*
* @example
* var n = 1001;
*
* // will output 1.001K
* var h = n.human(3);
*
* // will output 1001
* var m = h.fromHuman(h);
*
* @param boolean Optional. If true then use powers of 1024 not 1000
* @return number
* @access public
*/
Number.fromHuman = function(value, binary)
{
var m = String(value).match(/^([\-\+]?\d+\.?\d*)([A-Z])?$/);
if ( ! m ) {
return Number.NaN;
}
if ( ! m[2] ) {
return +m[1];
}
var divs = Number.prototype.human.add(binary);
for (var i = 0; i < divs.length; i++) {
if ( divs[i].s == m[2] ) {
return m[1] * divs[i].d;
}
}
return Number.NaN;
};
if ( ! String.prototype.trim ) {
/**
* object.trim()
* Transform the string object removing leading and trailing whitespaces
*
* @return string
* @access public
*/
String.prototype.trim = function()
{
return this.replace(/(^\s*)|(\s*$)/g, "");
};
}
if ( ! String.prototype.trimLeft ) {
/**
* object.trimLeft()
* Transform the string object removing leading whitespaces
*
* @return string
* @access public
*/
String.prototype.trimLeft = function()
{
return this.replace(/(^\s*)/, "");
};
}
if ( ! String.prototype.trimRight ) {
/**
* object.trimRight()
* Transform the string object removing trailing whitespaces
*
* @return string
* @access public
*/
String.prototype.trimRight = function()
{
return this.replace(/(\s*$)/g, "");
};
}
/**
* object.dup()
* Transform the string object duplicating the string
*
* @return string
* @access public
*/
String.prototype.dup = function()
{
var val = this.valueOf();
return val + val;
};
/**
* object.padding(number, string)
* Transform the string object to string of the actual width filling by the padding character (by default ' ')
* Negative value of width means left padding, and positive value means right one
*
* @param number Width of string
* @param string Padding chacracter (by default, ' ')
* @return string
* @access public
*/
String.prototype.padding = function(n, c)
{
var val = this.valueOf();
if ( Math.abs(n) <= val.length ) {
return val;
}
var m = Math.max((Math.abs(n) - this.length) || 0, 0);
var pad = Array(m + 1).join(String(c || ' ').charAt(0));
// var pad = String(c || ' ').charAt(0).repeat(Math.abs(n) - this.length);
return (n < 0) ? pad + val : val + pad;
// return (n < 0) ? val + pad : pad + val;
};
/**
* object.padLeft(number, string)
* Wrapper for object.padding
* Transform the string object to string of the actual width adding the leading padding character (by default ' ')
*
* @param number Width of string
* @param string Padding chacracter
* @return string
* @access public
*/
String.prototype.padLeft = function(n, c)
{
return this.padding(-Math.abs(n), c);
};
/**
* object.alignRight(number, string)
* Wrapper for object.padding
* Synonym for object.padLeft
*
* @param number Width of string
* @param string Padding chacracter
* @return string
* @access public
*/
String.prototype.alignRight = String.prototype.padLeft;
/**
* object.padRight(number, string)
* Wrapper for object.padding
* Transform the string object to string of the actual width adding the trailing padding character (by default ' ')
*
* @param number Width of string
* @param string Padding chacracter
* @return string
* @access public
*/
String.prototype.padRight = function(n, c)
{
return this.padding(Math.abs(n), c);
};
/**
* Formats arguments accordingly the formatting string.
* Each occurence of the "{\d+}" substring refers to
* the appropriate argument.
*
* @example
* '{0}is not {1} + {2}'.format('JavaScript', 'Java', 'Script');
*
* @param mixed
* @return string
* @access public
*/
String.prototype.format = function()
{
var args = arguments;
return this.replace(/\{(\d+)\}/g, function($0, $1)
{
return args[$1] !== void 0 ? args[$1] : $0;
});
};
/**
* object.alignLeft(number, string)
* Wrapper for object.padding
* Synonym for object.padRight
*
* @param number Width of string
* @param string Padding chacracter
* @return string
* @access public
*/
String.prototype.alignLeft = String.prototype.padRight;
/**
* sprintf(format, argument_list)
*
* The string function like one in C/C++, PHP, Perl
* Each conversion specification is defined as below:
*
* %[index][alignment][padding][width][precision]type
*
* index An optional index specifier that changes the order of the
* arguments in the list to be displayed.
* alignment An optional alignment specifier that says if the result should be
* left-justified or right-justified. The default is
* right-justified; a "-" character here will make it left-justified.
* padding An optional padding specifier that says what character will be
* used for padding the results to the right string size. This may
* be a space character or a "0" (zero character). The default is to
* pad with spaces. An alternate padding character can be specified
* by prefixing it with a single quote ('). See the examples below.
* width An optional number, a width specifier that says how many
* characters (minimum) this conversion should result in.
* precision An optional precision specifier that says how many decimal digits
* should be displayed for floating-point numbers. This option has
* no effect for other types than float.
* type A type specifier that says what type the argument data should be
* treated as. Possible types:
*
* % - a literal percent character. No argument is required.
* b - the argument is treated as an integer, and presented as a binary number.
* c - the argument is treated as an integer, and presented as the character
* with that ASCII value.
* d - the argument is treated as an integer, and presented as a decimal number.
* u - the same as "d".
* f - the argument is treated as a float, and presented as a floating-point.
* o - the argument is treated as an integer, and presented as an octal number.
* s - the argument is treated as and presented as a string.
* x - the argument is treated as an integer and presented as a hexadecimal
* number (with lowercase letters).
* X - the argument is treated as an integer and presented as a hexadecimal
* number (with uppercase letters).
* h - the argument is treated as an integer and presented in human-readable format
* using powers of 1024.
* H - the argument is treated as an integer and presented in human-readable format
* using powers of 1000.
*/
String.prototype.sprintf = function()
{
var args = arguments;
var index = 0;
var x;
var ins;
var fn;
/*
* The callback function accepts the following properties
* x.index contains the substring position found at the origin string
* x[0] contains the found substring
* x[1] contains the index specifier (as \d+\$ or \d+#)
* x[2] contains the alignment specifier ("+" or "-" or empty)
* x[3] contains the padding specifier (space char, "0" or defined as '.)
* x[4] contains the width specifier (as \d*)
* x[5] contains the floating-point precision specifier (as \.\d*)
* x[6] contains the type specifier (as [bcdfosuxX])
*/
return this.replace(String.prototype.sprintf.re, function()
{
if ( arguments[0] == "%%" ) {
return "%";
}
x = [];
for (var i = 0; i < arguments.length; i++) {
x[i] = arguments[i] || '';
}
x[3] = x[3].slice(-1) || ' ';
ins = args[+x[1] ? x[1] - 1 : index++];
// index++;
return String.prototype.sprintf[x[6]](ins, x);
});
};
String.prototype.sprintf.re = /%%|%(?:(\d+)[\$#])?([+-])?('.|0| )?(\d*)(?:\.(\d+))?([bcdfosuxXhH])/g;
String.prototype.sprintf.b = function(ins, x)
{
return Number(ins).bin(x[2] + x[4], x[3]);
};
String.prototype.sprintf.c = function(ins, x)
{
return String.fromCharCode(ins).padding(x[2] + x[4], x[3]);
};
String.prototype.sprintf.d =
String.prototype.sprintf.u = function(ins, x)
{
return Number(ins).dec(x[2] + x[4], x[3]);
};
String.prototype.sprintf.f = function(ins, x)
{
var ins = Number(ins);
// var fn = String.prototype.padding;
if (x[5]) {
ins = ins.toFixed(x[5]);
} else if (x[4]) {
ins = ins.toExponential(x[4]);
} else {
ins = ins.toExponential();
}
// Invert sign because this is not number but string
x[2] = x[2] == "-" ? "+" : "-";
return ins.padding(x[2] + x[4], x[3]);
// return fn.call(ins, x[2] + x[4], x[3]);
};
String.prototype.sprintf.o = function(ins, x)
{
return Number(ins).oct(x[2] + x[4], x[3]);
};
String.prototype.sprintf.s = function(ins, x)
{
return String(ins).padding(x[2] + x[4], x[3]);
};
String.prototype.sprintf.x = function(ins, x)
{
return Number(ins).hexl(x[2] + x[4], x[3]);
};
String.prototype.sprintf.X = function(ins, x)
{
return Number(ins).hex(x[2] + x[4], x[3]);
};
String.prototype.sprintf.h = function(ins, x)
{
var ins = String.prototype.replace.call(ins, /,/g, '');
// Invert sign because this is not number but string
x[2] = x[2] == "-" ? "+" : "-";
return Number(ins).human(x[5], true).padding(x[2] + x[4], x[3]);
};
String.prototype.sprintf.H = function(ins, x)
{
var ins = String.prototype.replace.call(ins, /,/g, '');
// Invert sign because this is not number but string
x[2] = x[2] == "-" ? "+" : "-";
return Number(ins).human(x[5], false).padding(x[2] + x[4], x[3]);
};
/**
* compile()
*
* This string function compiles the formatting string to the internal function
* to acelerate an execution a formatting within loops.
*
* @example
* // Standard usage of the sprintf method
* var s = '';
* for (var p in obj) {
* s += '%s = %s'.sprintf(p, obj[p]);
* }
*
* // The more speed usage of the sprintf method
* var sprintf = '%s = %s'.compile();
* var s = '';
* for (var p in obj) {
* s += sprintf(p, obj[p]);
* }
*
* @see String.prototype.sprintf()
*/
String.prototype.compile = function()
{
var args = arguments;
var index = 0;
var x;
var ins;
var fn;
/*
* The callback function accepts the following properties
* x.index contains the substring position found at the origin string
* x[0] contains the found substring
* x[1] contains the index specifier (as \d+\$ or \d+#)
* x[2] contains the alignment specifier ("+" or "-" or empty)
* x[3] contains the padding specifier (space char, "0" or defined as '.)
* x[4] contains the width specifier (as \d*)
* x[5] contains the floating-point precision specifier (as \.\d*)
* x[6] contains the type specifier (as [bcdfosuxX])
*/
var result = this.replace(/(\\|")/g, '\\$1').replace(String.prototype.sprintf.re, function()
{
if ( arguments[0] == "%%" ) {
return "%";
}
arguments.length = 7;
x = [];
for (var i = 0; i < arguments.length; i++) {
x[i] = arguments[i] || '';
}
x[3] = x[3].slice(-1) || ' ';
ins = x[1] ? x[1] - 1 : index++;
// index++;
return '", String.prototype.sprintf.' + x[6] + '(arguments[' + ins + '], ["' + x.join('", "') + '"]), "';
});
return Function('', 'return ["' + result + '"].join("")');
};
/**
* Considers the string object as URL and returns it's parts separately
*
* @param void
* @return Object
* @access public
*/
String.prototype.parseUrl = function()
{
var matches = this.match(arguments.callee.re);
if ( ! matches ) {
return null;
}
var result = {
'scheme': matches[1] || '',
'subscheme': matches[2] || '',
'user': matches[3] || '',
'pass': matches[4] || '',
'host': matches[5],
'port': matches[6] || '',
'path': matches[7] || '',
'query': matches[8] || '',
'fragment': matches[9] || ''};
return result;
};
String.prototype.parseUrl.re = /^(?:([a-z]+):(?:([a-z]*):)?\/\/)?(?:([^:@]*)(?::([^:@]*))?@)?((?:[a-z0-9_-]+\.)+[a-z]{2,}|localhost|(?:(?:[01]?\d\d?|2[0-4]\d|25[0-5])\.){3}(?:(?:[01]?\d\d?|2[0-4]\d|25[0-5])))(?::(\d+))?(?:([^:\?\#]+))?(?:\?([^\#]+))?(?:\#([^\s]+))?$/i;
String.prototype.camelize = function()
{
return this.replace(/([^-]+)|(?:-(.)([^-]+))/mg, function($0, $1, $2, $3)
{
return ($2 || '').toUpperCase() + ($3 || $1).toLowerCase();
});
};
String.prototype.uncamelize = function()
{
return this
.replace(/[A-Z]/g, function($0)
{
return '-' + $0.toLowerCase();
});
};
function encodeFieldName(name){
if(name == "Las")
return 1;
else if(name == "Kopalnia gliny")
return 2;
else if(name == "Kopalnia żelaza")
return 3;
else if(name == "Pole zboża")
return 4;
else
return 0;
}
var availableRes = new Array();
var availableResId = new Array("l1", "l2", "l3", "l4");
for (var i = 0; i < availableResId.length; i++) {
var eSpan = document.getElementById(availableResId[i]);
//alert(eSpan);
var valArr = eSpan.textContent.split("/");
availableRes[i] = valArr[0];
}
var eContent = document.getElementById("rx");
var eDiv = document.createElement("div");
eDiv.className = "boxes buildingList";
var frameElementClassArray = new Array("boxes-tl", "boxes-tr", "boxes-tc", "boxes-ml", "boxes-mr", "boxes-mc", "boxes-bl", "boxes-br", "boxes-bc");
for (var i = 0; i < frameElementClassArray.length; i++) {
var eFrameElement = document.createElement("div");
eFrameElement.className = frameElementClassArray[i];
eDiv.appendChild(eFrameElement);
}
var ePara = document.createElement("div");
ePara.className = "boxes-contents cf";
eDiv.appendChild(ePara);
var eTable = document.createElement("table");
ePara.appendChild(eTable);
var eTableBody = document.createElement("tbody");
eTable.appendChild(eTableBody);
var rowsArray = new Array();
for (var j = 0; j < eContent.childNodes.length; j++) {
if(eContent.childNodes[j].nodeName.toUpperCase() == "AREA" && eContent.childNodes[j].alt.length > 0){
var eTr = document.createElement("tr");
//eTableBody.appendChild(eTr);
rowsArray[rowsArray.length] = eTr;
var strValues = eContent.childNodes[j].alt.split(" Poziom ");
// Ikona
var iconTd = document.createElement("td");
iconTd.innerHTML = "<img class=\"r" + encodeFieldName(strValues[0]) + "\" src=\"img/x.gif\" />";
eTr.appendChild(iconTd);
var eTd = document.createElement("td");
var eHref = document.createElement("a");
eHref.href = eContent.childNodes[j].href;
eHref.textContent = strValues[0];
eTd.appendChild(eHref);
eTr.appendChild(eTd);
// Poziom
var eLevelTd = document.createElement("td");
var lvlText = strValues[1];
if(eContent.childNodes[j].title.indexOf("Obecnie ulepszane do poziomu") != -1)
lvlText += " (" + (Number(strValues[1]) + 1) + ")";//→
eLevelTd.innerHTML = "<span class=\"lvl\">Poziom " + lvlText + "</span>";
eTr.appendChild(eLevelTd);
var eUpgradeTd = document.createElement("td");
eTr.appendChild(eUpgradeTd);
var eDummyDiv = document.createElement("div");
eDummyDiv.innerHTML = eContent.childNodes[j].title;
var needetRes = new Array();
var m = 0;
for (var i = 0; i < eDummyDiv.childNodes.length; i++) {
if(eDummyDiv.childNodes[i].className == "showCosts"){
var eCostElement = eDummyDiv.childNodes[i];
for (var k = 0; k < eCostElement.childNodes.length; k++) {
var value = Number(eCostElement.childNodes[k].textContent);
if(value)
needetRes[m++] = value;
}
}
}
if(availableRes[0] >= needetRes[0] &&
availableRes[1] >= needetRes[1] &&
availableRes[2] >= needetRes[2] &&
availableRes[3] >= needetRes[3]
){
var idArr = eContent.childNodes[j].href.split("?id=");
//eUpgradeTd.innerHTML = "<a href=\"dorf1.php?a=" + idArr[1] + "&c=bf905b\">Ulepsz</a>";
eUpgradeTd.innerHTML = "<a href=\""+ eContent.childNodes[j].href +"\">Ulepsz</a>";
} else {
var remainingRes = new Array();
var remainingMinutes = new Array();
var longestTime = 0;
var prodSpeed = new Array(resources.production.l1, resources.production.l2, resources.production.l3, resources.production.l4);
for (var i = 0; i < 4; i++) {
remainingRes[i] = needetRes[i] - availableRes[i];
remainingMinutes[i] = 60 * remainingRes[i] / prodSpeed[i];
if(remainingMinutes[i] > longestTime)
longestTime = remainingMinutes[i];
}
var d = new Date();
var longestTimeMiliseconds = d.getTime() + longestTime * 60000;
var nd = new Date(longestTimeMiliseconds);
//"%02d:%02d:%02d".sprintf(nd.getHours(), nd.getMinutes(), nd.getSeconds())
eUpgradeTd.innerHTML = "<span class=\"none\">" + ("%02d:%02d".sprintf(nd.getHours(), nd.getMinutes(), nd.getSeconds())) + "</span>";
}
}
}
rowsArray.sort(function(a,b){
var res = encodeFieldName(a.childNodes[1].childNodes[0].textContent) - encodeFieldName(b.childNodes[1].childNodes[0].textContent);
if(res == 0)
return Number(a.childNodes[2].textContent) - Number(b.childNodes[2].textContent);
else
return res;
});
for (var i = 0; i < rowsArray.length; i++) {
eTableBody.appendChild(rowsArray[i]);
}
var eFoot = document.getElementById("content");
eFoot.insertBefore(eDiv, eFoot.firstChild);
eContent.parentElement.removeChild(eContent);
var evillageMap = document.getElementById("village_map");
evillageMap.parentElement.removeChild(evillageMap);
|
C++
|
UTF-8
| 1,158 | 3.046875 | 3 |
[] |
no_license
|
/*-
* Copyright (c) Iris Dev. team. All rights reserved.
* See http://www.communico.pro/license for details.
*
*/
#ifndef _SCOPED_PTR_HPP__
#define _SCOPED_PTR_HPP__ 1
#include "Types.h"
namespace IRIS
{
template <typename T> class ScopedPtr
{
public:
/**
@brief Constructor
@param pIObj - pointer to object
*/
ScopedPtr(T * pIObj = NULL): pObj(pIObj) { ;; }
/**
@brief Type cast constructor
*/
ScopedPtr & operator =(T * pIObj)
{
if (pObj != NULL) { delete pObj; }
pObj = pIObj;
return *this;
}
/**
@brief Compare two pointers
*/
bool operator ==(const void * vPtr) { return pObj == vPtr; }
/**
@brief Get pointer to the object
*/
T * operator->() { return pObj; }
/**
@brief Get reference to the object
*/
T & operator*() { return *pObj; }
/**
@brief Type cast operator
*/
operator T*() { return pObj; }
/**
@brief A destructor
*/
~ScopedPtr() throw() { delete pObj; }
private:
// Does not exist
ScopedPtr(const ScopedPtr & oRhs);
ScopedPtr& operator =(const ScopedPtr & oRhs);
/** Pointer to the object */
T * pObj;
};
} // namespace IRIS
#endif // _SCOPED_PTR_HPP__
// End.
|
Python
|
UTF-8
| 1,816 | 3.46875 | 3 |
[] |
no_license
|
""" ***Author: Dana Mun***
A simple program that uses Yelp.com to get random existing addresses based on the zipcode provided in fileName.xls (make sure it's in .xls extension).
This code is compatible with Python 2.7.3 and need to download modules:
1. python pip -m install selenium
2. python pip -m install xlrd
3. python pip -m install xlwt
4. python pip -m install xlutils
To fill a certain excel sheet change field named fileName below.
To run the file you do python27 address.py (make sure the python.exe in your python path is renamed to python27.exe)
"""
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import xlrd
from xlwt import Workbook
from xlutils.copy import copy
"""*Enter Name of File here*"""
fileName = 'zipcodes.xls'
website = "http://www.yelp.com"
driver = webdriver.PhantomJS()
#driver = webdriver.Firefox()
workbook = xlrd.open_workbook(fileName)
worksheet = workbook.sheet_by_name('Sheet1')
wb = copy(workbook)
s = wb.get_sheet(0)
num_rows = worksheet.nrows - 1
curr_row = 0
correctAddr = ''
while curr_row < num_rows:
curr_row += 1
row = worksheet.row(curr_row)
print ("Zip Code: ", int(row[0].value))
driver.get(website)
elem = driver.find_element_by_id("dropperText_Mast")
driver.implicitly_wait(10)
elem.clear()
driver.implicitly_wait(10)
elem.send_keys(str(int(row[0].value)))
driver.implicitly_wait(10)
elem.send_keys(Keys.RETURN)
driver.implicitly_wait(10)
address = driver.find_elements_by_tag_name('address')
for i in range(0, len(address)):
if str(int(row[0].value)) in address[i].text:
correctAddr = address[i].text
break
i += 1
s.write(curr_row, 1, correctAddr.replace('\n', ' '))
wb.save(fileName)
print ("Zip Code: ", row[0], "Address Found: ", correctAddr.replace('\n', ' '))
correctAddr = ''
driver.close()
|
JavaScript
|
UTF-8
| 1,040 | 2.78125 | 3 |
[] |
no_license
|
ListCtrl = function (listView,footerView,store) {
var addElementToList = function(ele) {
listView.addNewElementToList(listView.list,ele);
store.add(store.data,ele);
};
var updateFooter = function(data) {
footerView.updateAllItems(data);
};
var updateFooterSelectedItems = function(ele) {
if(store.checkElements(ele)) {
ele.className = ele.className + "active_element";
} else {
ele.className = ele.className.replace("active_element","");
}
footerView.updateActiveItems(store.selectedData.length);
};
listView.on("addingElement",addElementToList);
listView.on("updateFooterSelectedItems",updateFooterSelectedItems);
store.on("ElementWasAdd",updateFooter);
};
FooterCtrl = function (footerView,store) {
var update = function() {
footerView.updateActiveItems(store.selectedData.length);
};
footerView.on("updateFooterSelectedItems",update);
};
InputCtrl = function (inputView, listView, footerView, store) {
var add = function(ele) {
listView.add(ele);
};
inputView.on("addNewElementToList",add);
};
|
C
|
UTF-8
| 2,014 | 2.515625 | 3 |
[] |
no_license
|
#include "PhysicsPrecond.h"
PhysicsPrecond::PhysicsPrecond( string label, const Epetra_Map & map)
:_my_map(map),
d_label(label)
{
std::cout <<"exsiting physicsprecond constractor"<<std::endl;
}
PhysicsPrecond::~PhysicsPrecond()
{
}
int
PhysicsPrecond::SetUseTranspose(bool UseTranspose)
{
/*
* Disable this option
*/
return false;
}
int
PhysicsPrecond::Apply(const Epetra_MultiVector& X, Epetra_MultiVector& Y) const
{
/*
* Not implemented: Throw an error!
*/
cout << "ERROR: Preconditioner::Apply() - "
<< "method is NOT implemented!! " << endl;
throw "Preconditionerr Error";
return false;
}
int
PhysicsPrecond::ApplyInverse(const Epetra_MultiVector& X, Epetra_MultiVector& Y) const
{
std::cout << "PhysicsPrecond::ApplyInverse: " << std::endl;
Y=X;
std::cout << "returning.."<<std::endl;
return 0;
/*
* Not implemented: Throw an error!
*/
cout << "ERROR: Preconditioner::Apply() - "
<< "method is NOT implemented!! " << endl;
throw "Preconditionerr Error";
return false;
}
double
PhysicsPrecond::NormInf() const
{
/*
* Not implemented: Throw an error!
*/
cout << "ERROR: int Preconditioner::NormInf() - "
<< "method is NOT implemented!! " << endl;
throw "Preconditioner Error";
return 0.0;
}
const char*
PhysicsPrecond::Label() const
{
return d_label.c_str();
}
bool
PhysicsPrecond::UseTranspose() const
{
return false;
/*
* Not implemented: Throw an error!
*/
cout << "ERROR: Preconditioner::UseTranspose() - "
<< "method is NOT implemented!! " << endl;
throw "Preconditioner Error";
return false;
}
bool
PhysicsPrecond::HasNormInf() const
{
/*
* NormInf is not implemented
*/
return false;
}
const Epetra_Comm& PhysicsPrecond::Comm() const
{
return _my_map.Comm();
}
const Epetra_Map& PhysicsPrecond::OperatorDomainMap() const
{
return _my_map;
}
const Epetra_Map& PhysicsPrecond::OperatorRangeMap() const
{
return _my_map;
}
|
Java
|
UTF-8
| 2,731 | 2.1875 | 2 |
[] |
no_license
|
/**
* Baijiahulian.com Inc. Copyright (c) 2014-2015 All Rights Reserved.
*/
package com.xiaozhaoji.dao.impl;
import com.google.common.collect.Maps;
import com.xiaozhaoji.dao.TalkDao;
import com.xiaozhaoji.dao.po.Talk;
import com.xiaozhaoji.service.dto.request.Page;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Repository;
import java.util.Date;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Repository
public class TalkDaoImpl extends SpringCommonDao implements TalkDao {
@Override
public Talk getById(Long id) {
String sql = "select * from talk where id=:id";
Map<String, Object> paramMap = Maps.newHashMap();
paramMap.put("id", id);
log.debug("sql = {}, params = {}", sql, paramMap);
return this.getNamedJdbcTemplate().queryForObject(sql, paramMap, new BeanPropertyRowMapper<Talk>(Talk.class));
}
@Override
public int addClick(Long id) {
if (id == null)
return 0;
String sql = "update talk set click = click + 1 where id = :id";
Map<String, Object> paramMap = Maps.newHashMap();
paramMap.put("id", id);
log.debug("sql = {}, params = {}", sql, paramMap);
return this.getNamedJdbcTemplate().update(sql, paramMap);
}
@Override
public List<Talk> list(Long collegeId, Date startTime, Date endTime, Page page) {
String countSql =
"select count(id) from talk where " + "college_id = :collegeId " + "and add_time >= :startTime "
+ "and add_time < :endTime";
String sql =
"select id,college_id,title,hold_time,address,add_time,src_url,src_name,click "
+ "from talk where college_id = :collegeId and add_time >= :startTime "
+ "and add_time < :endTime order by add_time desc limit :start,:count";
Map<String, Object> paramMap = Maps.newHashMap();
paramMap.put("startTime", startTime);
paramMap.put("endTime", endTime);
paramMap.put("collegeId", collegeId);
log.debug("sql = {}, params = {}", sql, paramMap);
Integer cnt = this.getNamedJdbcTemplate().queryForObject(countSql, paramMap, Integer.class);
log.debug(" cnt = {}", cnt);
page.setTotalElementCount(cnt);
log.debug("limit {},{}", page.getFirstNumber(), page.getCurPageElementCount());
paramMap.put("start", page.getFirstNumber());
paramMap.put("count", page.getCurPageElementCount());
log.debug("sql = {}, params = {}", sql, paramMap);
return this.getNamedJdbcTemplate().query(sql, paramMap, new BeanPropertyRowMapper<Talk>(Talk.class));
}
}
|
Markdown
|
UTF-8
| 1,919 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
---
layout: post
title: "Spring IoC/DI 컨테이너"
date: 2018-05-06
categories: boostcourse
image : https://github.com/KoJunHee/kojunhee.github.io/raw/master/img/boostcourse.jpg
---
- 컨테이너
- 인스턴스의 생명 주기를 관리
- Servlet을 실행해주는 WAS는 Servlet 컨테이너를 가지고 있다고 말합니다.
- WAS는 웹 브라우저로부터 서블릿 URL에 해당하는 요청을 받으면, 서블릿을 메모리에 올린 후 실행합니다.
- 개발자가 서블릿 클래스를 작성했지만, 실제로 메모리에 올리고 실행하는 것은 WAS가 가지고 있는 Servlet컨테이너입니다.
- Servlet컨테이너는 동일한 서블릿에 해당하는 요청을 받으면, 또 메모리에 올리지 않고 기존에 메모리에 올라간 서블릿을 실행하여 그 결과를 웹 브라우저에게 전달합니다.
- IoC (Inversion of Control)
- 예를 들어 서블릿 클래스는 개발자가 만들지만,
- 그 서블릿의 메소드를 알맞게 호출하는 것은 WAS입니다.
- 이렇게 개발자가 만든 어떤 클래스나 메소드를 다른 프로그램이 대신 실행해주는 것을 제어의 역전이라고 합니다.
- DI(Dependency Injection)
- DI는 클래스 사이의 의존 관계를 빈(Bean) 설정 정보를 바탕으로 컨테이너가 자동으로 연결해주는 것을 말합니다.
- DI가 적용 안된 예
- 개발자가 직접 인스턴스를 생성합니다.

- Spring 에서 DI가 적용된 예
- 엔진 type의 v5변수에 아직 인스턴스가 할당되지 않았습니다.
컨테이너가 v5변수에 인스턴스를 할당해주게 됩니다.

- Reference
- NAVER edwith boostcourse Full-Stack Web Developer
|
PHP
|
UTF-8
| 802 | 2.890625 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace Kinko\Database\Query;
use Illuminate\Database\Query\Builder;
abstract class NonRelationalBuilder extends Builder
{
/**
* Execute an accumulation function on the database.
*
* @param string $field
* @param string $operation
* @return mixed
*/
abstract public function accumulate($field, $operation);
/**
* Retrieve the minimum value of a given field.
*
* @param string $field
* @return mixed
*/
public function min($field)
{
return $this->accumulate($field, 'min');
}
/**
* Retrieve the maximum value of a given field.
*
* @param string $field
* @return mixed
*/
public function max($field)
{
return $this->accumulate($field, 'max');
}
}
|
PHP
|
UTF-8
| 658 | 2.96875 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace Phate;
/**
* CsvRendererクラス
*
* csvとして出力するレンダラ
*
* @package PhateFramework
* @access public
* @author Nobuo Tsuchiya <develop@m.tsuchi99.net>
* @create 2016/12/23
**/
class CsvRenderer
{
/**
* カラム名一覧の設定
*
* @param array $columnNameArray カラム名一覧
*
* @return void
*/
public function setColumnNames(array $columnNameArray);
/**
* 描画
*
* @param array $listArray 出力データ
* @param string $filename ファイル名
*
* @return void
*/
public function render(array $listArray, string $filename = "");
}
|
Java
|
UTF-8
| 4,855 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
package de.core23.javapicross.controller;
import de.core23.javapicross.gui.Actions;
import de.core23.javapicross.gui.EditorFrame;
import de.core23.javapicross.model.Level;
import net.roydesign.app.AboutJMenuItem;
import net.roydesign.app.Application;
import net.roydesign.app.QuitJMenuItem;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class EditorController extends Application implements ActionListener {
private EditorFrame _frame;
private boolean _blockModus;
private Level _level;
public EditorController() {
}
private void initMacSettings() {
getAboutJMenuItem().setActionCommand(Actions.ABOUT);
getAboutJMenuItem().addActionListener(this);
getPreferencesJMenuItem().setEnabled(false);
getPreferencesJMenuItem().setVisible(false);
// ActionCommand not supported
getQuitJMenuItem().addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
close();
}
});
if (AboutJMenuItem.isAutomaticallyPresent())
_frame.getJMenuHelp().setVisible(false);
if (QuitJMenuItem.isAutomaticallyPresent())
_frame.getJMenuItemExit().setVisible(false);
}
public void show() {
_frame = new EditorFrame();
_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
_frame.getPicrossPanel().addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
Point p = _frame.getPicrossPanel().translatePoint(e.getPoint());
if (p != null && _level.isValidBlock(p.x, p.y))
_blockModus = !_level.getBlock(p.x, p.y);
}
public void mouseReleased(MouseEvent e) {
Point p = _frame.getPicrossPanel().translatePoint(e.getPoint());
if (p != null && _level.isValidBlock(p.x, p.y))
setStatus(p.x, p.y, _blockModus);
}
});
_frame.getPicrossPanel().addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
Point p = _frame.getPicrossPanel().translatePoint(e.getPoint());
if (p != null && _level.isValidBlock(p.x, p.y))
setStatus(p.x, p.y, _blockModus);
}
});
_frame.getJMenuItemExit().addActionListener(this);
_frame.getJMenuItemLoad().addActionListener(this);
_frame.getJMenuItemSave().addActionListener(this);
_frame.getJMenuItemAbout().addActionListener(this);
_frame.getJMenuItemNewLevel().addActionListener(this);
initMacSettings();
newLevel(5);
_frame.setLocationRelativeTo(null);
_frame.setVisible(true);
}
private void close() {
System.exit(0);
}
public void newLevel(int size) {
setLevel(new Level(size));
}
private void setStatus(int x, int y, boolean block) {
if (!_level.isValidBlock(x, y))
return;
_level.setBlock(x, y, block);
_frame.getPicrossPanel().setStatus(x, y, block);
_frame.getPicrossPanel().repaint();
_frame.getPicrossPreviewPanel().setStatus(x, y, block);
_frame.getPicrossPreviewPanel().repaint();
}
public void showNewLevelDialog() {
new NewLevelController(this).show(_frame);
}
private void showSaveDialog() {
if (_level == null)
return;
new LevelManagerController(this, LevelManagerController.SAVE).show(_frame);
}
private void showLoadDialog() {
new LevelManagerController(this, LevelManagerController.LOAD).show(_frame);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals(Actions.EXIT)) {
close();
} else if (ae.getActionCommand().equals(Actions.NEW_DIALOG)) {
showNewLevelDialog();
} else if (ae.getActionCommand().equals(Actions.LOAD)) {
showLoadDialog();
} else if (ae.getActionCommand().equals(Actions.SAVE)) {
showSaveDialog();
}
}
public void setLevel(Level level) {
_level = level;
_frame.getPicrossPreviewPanel().setGridSize(_level.getSize(), _level.getSize());
_frame.getPicrossPanel().setGridSize(_level.getSize(), _level.getSize());
for (int x = 0; x < _level.getSize(); x++) {
for (int y = 0; y < _level.getSize(); y++) {
_frame.getPicrossPreviewPanel().setStatus(x, y, _level.getBlock(x, y));
_frame.getPicrossPanel().setStatus(x, y, _level.getBlock(x, y));
}
}
_frame.getPicrossPanel().setPreferredSize(new Dimension(_frame.getPicrossPanel().getPaintWidth(), _frame.getPicrossPanel().getPaintHeight()));
_frame.getPicrossPreviewPanel().setPreferredSize(
new Dimension(_frame.getPicrossPreviewPanel().getPaintWidth(), _frame.getPicrossPreviewPanel().getPaintHeight()));
resize();
}
private void resize() {
int width = _frame.getPicrossPanel().getPaintWidth() + 40;
int height = _frame.getPicrossPanel().getPaintHeight() + 200;
_frame.setSize(Math.max(_frame.getWidth(), width), Math.max(_frame.getHeight(), height));
_frame.setMinimumSize(new Dimension(width, height));
_frame.getContentPane().doLayout();
_frame.repaint();
}
public Level getLevel() {
return _level;
}
public JFrame getFrame() {
return _frame;
}
}
|
C#
|
UTF-8
| 5,178 | 3.203125 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
using System;
using Xunit;
namespace SharpCollections.Generic
{
public class BinaryHeapTests
{
private readonly struct TestType : IComparable<TestType>
{
public readonly int Priority;
public TestType(int priority)
{
Priority = priority;
}
public int CompareTo(TestType other)
{
return Priority.CompareTo(other.Priority);
}
}
[Fact]
public void ReturnsItemsInCorrectOrder()
{
BinaryHeap<TestType> heap = new BinaryHeap<TestType>();
heap.Push(new TestType(123));
heap.Push(new TestType(124));
heap.Push(new TestType(120));
heap.Push(new TestType(95));
Assert.Equal(95, heap.Pop().Priority);
heap.Push(new TestType(-1));
Assert.Equal(-1, heap.Pop().Priority);
Assert.Equal(120, heap.Pop().Priority);
Assert.Equal(123, heap.Pop().Priority);
Assert.Equal(124, heap.Pop().Priority);
}
[Fact]
public void ReportsCorrectItemCount()
{
BinaryHeap<TestType> heap = new BinaryHeap<TestType>();
Assert.Equal(0, heap.Count);
heap.Push(new TestType(123));
heap.Push(new TestType(124));
Assert.Equal(2, heap.Count);
Assert.Equal(123, heap.Pop().Priority);
Assert.Equal(1, heap.Count);
Assert.Equal(124, heap.Pop().Priority);
Assert.Equal(0, heap.Count);
heap.Push(new TestType(-1));
Assert.Equal(1, heap.Count);
Assert.Equal(-1, heap.Pop().Priority);
Assert.Equal(0, heap.Count);
}
[Fact]
public void ReportsCorrectCapacity()
{
BinaryHeap<TestType> heap = new BinaryHeap<TestType>(7);
Assert.Equal(0, heap.Count);
Assert.Equal(7, heap.Capacity);
heap.Push(new TestType(1));
heap.Push(new TestType(2));
heap.Push(new TestType(3));
heap.Push(new TestType(4));
heap.Push(new TestType(5));
heap.Push(new TestType(6));
heap.Push(new TestType(7));
Assert.Equal(7, heap.Capacity);
heap.Push(new TestType(8));
Assert.True(heap.Capacity > 7);
}
[Fact]
public void ResizesByDoubling()
{
BinaryHeap<TestType> heap = new BinaryHeap<TestType>();
Assert.Equal(0, heap.Count);
Assert.Equal(3, heap.Capacity);
heap.Push(new TestType(1));
heap.Push(new TestType(2));
heap.Push(new TestType(3));
Assert.Equal(3, heap.Capacity);
heap.Push(new TestType(4));
Assert.Equal(6, heap.Capacity);
heap.Push(new TestType(5));
heap.Push(new TestType(6));
Assert.Equal(6, heap.Capacity);
heap.Push(new TestType(7));
Assert.Equal(12, heap.Capacity);
}
[Fact]
public void ClearsItems()
{
BinaryHeap<TestType> heap = new BinaryHeap<TestType>();
Assert.Equal(0, heap.Count);
heap.Push(new TestType(1));
heap.Push(new TestType(2));
heap.Push(new TestType(3));
Assert.Equal(3, heap.Count);
heap.Clear();
Assert.Equal(0, heap.Count);
}
[Fact]
public void ThrowsOnNullPush()
{
BinaryHeap<string> heap = new BinaryHeap<string>();
Assert.Throws<ArgumentNullException>(() => { heap.Push(default); });
BinaryHeap<int> heapOfValueTypes = new BinaryHeap<int>();
// Does not throw on default value
heapOfValueTypes.Push(default);
}
[Fact]
public void ThrowsOnInvalidCapacitySizes()
{
Assert.Throws<ArgumentOutOfRangeException>(() => { new BinaryHeap<string>(-1); });
Assert.Throws<ArgumentOutOfRangeException>(() => { new BinaryHeap<string>(int.MaxValue); });
BinaryHeap<string> heap = new BinaryHeap<string>(10);
Assert.Equal(0, heap.Count);
Assert.Equal(10, heap.Capacity);
// Can resize to fit
heap.Capacity = 0;
Assert.Equal(0, heap.Capacity);
Assert.Throws<ArgumentOutOfRangeException>(() => { heap.Capacity = -1; });
Assert.Throws<ArgumentOutOfRangeException>(() => { heap.Capacity = int.MaxValue; });
heap.Push("foo");
Assert.Throws<ArgumentOutOfRangeException>(() => { heap.Capacity = 0; });
heap.Capacity = 1;
heap.Pop();
heap.Capacity = 0;
}
[Fact]
public void ThrowsOnPopWhenEmpty()
{
BinaryHeap<int> heap = new BinaryHeap<int>();
Assert.Throws<InvalidOperationException>(() => { _ = heap.Top; });
Assert.Throws<InvalidOperationException>(() => { _ = heap.Pop(); });
}
}
}
|
Java
|
UTF-8
| 2,788 | 2.984375 | 3 |
[] |
no_license
|
package model;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AccountListTest {
private AccountList accountList;
private Account a1;
private Account a2;
private Account a3;
private Account a4;
@BeforeEach
public void runBefore() {
accountList = new AccountList();
a1 = new Income(500, 2000, 3, 28, "allowance");
a2 = new Income(1000, 2010, 6, 26, "part-time job");
a3 = new Expenditure(-200, 2020, 8, 28, "drink");
a4 = new Expenditure(-500, 2000, 3, 28, "food");
}
//test the empty constructor
@Test
public void testConstructor() {assertEquals(accountList.getSize(), 0);}
//test the getters i.e. getSize() and getAccounts
@Test
public void testGetters() {
assertEquals(accountList.getSize(), 0);
assertEquals(accountList.getAccounts().size(), 0);
}
//test AddAccount method with empty Accountlist
@Test
public void testAddAccountWithEmptyAccountList(){
assertEquals(0, accountList.getSize());
accountList.addAccount(a1);
assertEquals(1,accountList.getSize());
}
//test AddAccount method with not empty Accountlist
@Test
public void testAddAccountWithNotEmptyAccountList(){
accountList.addAccount(a1);
accountList.addAccount(a2);
assertEquals(2,accountList.getSize());
accountList.addAccount(a3);
assertEquals(3,accountList.getSize());
}
//test RemoveAccount method with empty Accountlist
@Test
public void testRemoveAccountFromEmptyAccountList(){
assertEquals(0,accountList.getSize());
accountList.removeAccount(a1);
assertEquals(0,accountList.getSize());
}
//test RemoveAccount method with not empty Accountlist
@Test
public void testRemoveAccountFromNotEmptyAccountList(){
accountList.addAccount(a1);
accountList.addAccount(a2);
accountList.addAccount(a3);
assertEquals(3,accountList.getSize());
accountList.removeAccount(a2);
assertEquals(2,accountList.getSize());
}
//test BalanceAccount method with empty Accountlist
@Test
public void testBalanceAccountWithEmptyAccountList(){
assertEquals(0,accountList.getSize());
assertEquals(0,accountList.balanceAccount());
}
//test BalanceAccount method with not empty Accountlist
@Test
public void testBalanceAccountWithNotEmptyAccountList(){
accountList.addAccount(a1);
accountList.addAccount(a2);
accountList.addAccount(a3);
assertEquals(3,accountList.getSize());
assertEquals(1300,accountList.balanceAccount());
}
}
|
C#
|
UTF-8
| 990 | 2.59375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Farmacie.Models;
namespace Farmacie.Test.Mock
{
public class ServiziOgdiFake
{
public static IEnumerable<Farmacia> RichiamaServizio(Func<Farmacia, bool> query)
{
List<Farmacia> lista = new List<Farmacia>();
for (int i = 0; i < Costanti.NUM_FARMACIE_LAZIO; i++)
{
lista.Add(new Farmacia()
{
Regione = new Regione("120", "Lazio"),
partitaiva = (100+i).ToString()
});
}
for (int i = 0; i < Costanti.NUM_FARMACIE_PIEMONTE; i++)
{
lista.Add(new Farmacia()
{
Regione = new Regione("10", "Piemonte"),
partitaiva = (500 + i).ToString()
});
}
return lista;
}
}
}
|
Java
|
UTF-8
| 1,519 | 1.914063 | 2 |
[] |
no_license
|
package com.union.aimei.common.feign.pc.store.hystrix;
import com.github.pagehelper.PageInfo;
import com.union.aimei.common.feign.pc.store.StoreFollowerFeign;
import com.union.aimei.common.model.store.StoreFollower;
import org.springframework.stereotype.Component;
/**
* 店铺粉丝
*
* @author liurenkai
* @time 2018/1/12 17:35
*/
@Component(value = "pc-StoreFollowerFeign")
public class StoreFollowerApiHystrix implements StoreFollowerFeign {
/**
* 前端分页查询店铺粉丝
*
* @param pageNo 分页索引
* @param pageSize 每页显示数量
* @param storeFollower 查询条件
* @return
*/
@Override
public PageInfo<StoreFollower> findByPageForFront(Integer pageNo, Integer pageSize, StoreFollower storeFollower) {
return null;
}
/**
* 添加店铺粉丝
*
* @param storeFollower
* @return
*/
@Override
public int insert(StoreFollower storeFollower) {
return 0;
}
/**
* 删除店铺粉丝
*
* @param id
* @return
*/
@Override
public int deleteById(int id) {
return 0;
}
/**
* 修改店铺粉丝
*
* @param storeFollower
* @return
*/
@Override
public int edit(StoreFollower storeFollower) {
return 0;
}
/**
* 根据ID查询
*
* @param id
* @returnstoreFollower
*/
@Override
public StoreFollower queryById(int id) {
return null;
}
}
|
Go
|
UTF-8
| 872 | 2.921875 | 3 |
[] |
no_license
|
package transformer
import (
"encoding/json"
"math3usmartins.com/todo-api-golang/account"
)
type JsonTransformer struct{}
type UserForJson struct {
Uuid string `json:"uuid"`
Email string `json:"email"`
Password string `json:"password"`
Roles []string `json:"roles"`
}
func (transformer JsonTransformer) FromUser(user account.User) (string, error) {
var err error
userForJson := UserForJson{
user.Uuid,
user.Email,
user.Password,
user.Roles,
}
userJson, err := json.Marshal(userForJson)
return string(userJson), err
}
func (transformer JsonTransformer) ToUser(userJson string) (account.User, error) {
var err error
userForJson := UserForJson{}
json.Unmarshal([]byte(userJson), &userForJson)
user := account.User{
userForJson.Uuid,
userForJson.Email,
userForJson.Password,
userForJson.Roles,
}
return user, err
}
|
C++
|
UTF-8
| 1,896 | 3.640625 | 4 |
[] |
no_license
|
#include "Quadrilateral.h"
#include <iostream>
#include <cmath>
using namespace std;
//Must call the super class constructor via member initialization list.
//If not, will call the default constructor of super class.
Quadrilateral::Quadrilateral(const Point2D points[], int numPoints):Polygon(points, numPoints){
if (numPoints != 4) {
cout << "Illegal! Number of points should be 4" << endl;
if (this->numPoints != 0) {
delete [] this->points;
}
numPoints = 0;
this->points = NULL;
return;
}
cout << "Initialized by Quadrilateral's other constructor" << endl;
}
Quadrilateral::~Quadrilateral() {
cout << "Quadrilateral's destructor!" << endl;
}
void Quadrilateral::print() const {
cout << "Quadrilateral's center: ";
this->center().print();
cout << endl;
cout << "Quadrilateral's perimeter: "<<perimeter()<<endl;
cout << "Quadrilater's area: "<<area()<<endl;
}
Point2D Quadrilateral::center() const {
double xValue = 0, yValue = 0;
for (int i = 0; i < this->numPoints; i++) {
xValue += this->points[i].getX();
yValue += this->points[i].getY();
}
return Point2D(xValue / this->numPoints, yValue / this->numPoints);
}
double Quadrilateral::perimeter() const {
double perimeter = 0;
perimeter += this->points[0].distance(this->points[1]);
perimeter += this->points[1].distance(this->points[2]);
perimeter += this->points[2].distance(this->points[3]);
perimeter += this->points[3].distance(this->points[0]);
return perimeter;
}
double Quadrilateral::area() const{
double result=0;
for (int i=0;i<this->numPoints;i++){
if (i==3){
result+=this->points[i].getX()*this->points[i-3].getY();
result-=this->points[i-3].getX()*this->points[i].getY();
}else{
result+=this->points[i].getX()*this->points[i+1].getY();
result-=this->points[i+1].getX()*this->points[i].getY();
}
}
result=abs(result);
return result/2.0;
}
|
PHP
|
UTF-8
| 1,505 | 2.875 | 3 |
[
"Apache-2.0"
] |
permissive
|
<?php
print("<html>\n\t<head>\n\t\t<title>Uploading file...</title></head><body>");
$target_dir = "../img/"; # test commend
// $target_file = $target_dir . basename($_FILES["add"]["name"]);
$title = $_POST['title'];
$target_file = $target_dir . basename($title . ".png");
print("<h1>Uploading $target_file</h1>");
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["add"]["tmp_name"]);
if($check !== false) {
echo "<p>File is an image of type " . $check["mime"] . ".</p>";
$uploadOk = 1;
}
else {
echo "<p>File is not an image.</p>";
$uploadOk = 0;
}}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "<p>Sorry, your file was not uploaded.</p>";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["add"]["tmp_name"], $target_file)) {
echo "<p>The file ". basename( $_FILES["add"]["name"]). " has been uploaded.<p>";
$records = fopen("../records", "a");
fwrite($records, $title . "\t" . $_POST['comments']. "\n");
fclose($records);
} else {
echo "<p>Sorry, there was an error uploading your file.</p>";
}
}
echo '<p><a href="upload_portal.html">Create another entry</a><p>';
echo '<p><a href="../index.cgi">Return to main page</a></p>';
echo '</form>';
echo '</body></html>';
?>
|
Python
|
UTF-8
| 410 | 2.921875 | 3 |
[] |
no_license
|
from tkinter import *
import os
def got_clicked():
os.system('python im3.py')
top = Tk()
top.title("SRM Attendance System")
top.geometry("500x500")
label=Label(top,text="Attendance System using Face Recognition",relief=RAISED)
img=PhotoImage(file='srmlogo.png')
Label(top,image=img).pack()
label.pack()
my_button = Button(text="Start Face Recognition", command=got_clicked)
my_button.pack()
top.mainloop()
|
Java
|
UTF-8
| 838 | 2.421875 | 2 |
[
"MIT"
] |
permissive
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mgatelabs.bytemapper.support.fields.types;
import com.mgatelabs.bytemapper.support.instances.FieldInstance;
import com.mgatelabs.bytemapper.support.instances.FormatInstance;
/**
*
* @author MiniMegaton
*/
public abstract class SimpleBaseType extends AbstractBaseType {
public SimpleBaseType(String type, String name, String description) {
super(type, name, description);
}
@Override
public AbstractBaseType getInstance(FormatInstance format, FieldInstance field) {
return this;
}
public boolean isType(String type) {
return this.getType().equalsIgnoreCase(type);
}
}
|
Java
|
UTF-8
| 1,122 | 2.765625 | 3 |
[] |
no_license
|
package annotool;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.*;
public class AnnSplashScreen extends JWindow {
final String imageResSplash = "images/screen.jpg";
public AnnSplashScreen() {
ImageIcon image = null;
JLabel label = new JLabel(image);
try {
java.net.URL url = this.getClass().getResource("/"+imageResSplash);
if (url != null)
image = new ImageIcon(url);
else
image = new ImageIcon(imageResSplash);
label = new JLabel(image);
} catch (Exception ex) {
label = new JLabel("unable to find splash screen image.");
}
getContentPane().add(label);
pack();
Dimension dim =
Toolkit.getDefaultToolkit().getScreenSize();
int x = (int)(dim.getWidth() - getWidth())/2;
int y = (int)(dim.getHeight() - getHeight())/2;
setLocation(x,y);
}
public void showSplashScreen()
{
pack();
setVisible(true);
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
setVisible(false);
} catch (InterruptedException ex) {
}
}
}).start();
}
}
|
PHP
|
UTF-8
| 1,946 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace Whchi\LaravelApplicationInsights\Validators;
use ApplicationInsights\Channel\Contracts\Data_Point_Type;
use Whchi\LaravelApplicationInsights\Exceptions\TelemetryDataFormatException;
class MetricData extends CommonHelper
{
protected function validateOptionalData(array $data): void
{
if (isset($data['properties'])) {
foreach ($data['properties'] as $ele) {
if (is_array($ele)) {
throw new TelemetryDataFormatException('"properties" should be 1D array', $this->class);
}
}
}
if (isset($data['type'])) {
if (!is_int($data['type'])) {
throw new TelemetryDataFormatException('"type" should be int type', $this->class);
}
if (!in_array(
$data['type'], [
Data_Point_Type::Measurement,
Data_Point_Type::Aggregation,
]
)
) {
throw new TelemetryDataFormatException('"type" out of range', $this->class);
}
}
if (isset($data['count'])) {
if (!is_int($data['count'])) {
throw new TelemetryDataFormatException('"count" should be int type', $this->class);
}
}
if (isset($data['min'])) {
if (!is_double($data['min'])) {
throw new TelemetryDataFormatException('"min" should be double type', $this->class);
}
}
if (isset($data['max'])) {
if (!is_double($data['max'])) {
throw new TelemetryDataFormatException('"max" should be double type', $this->class);
}
}
if (isset($data['stdDev'])) {
if (!is_double($data['stdDev'])) {
throw new TelemetryDataFormatException('"stdDev" should be double type', $this->class);
}
}
}
}
|
Java
|
UTF-8
| 3,035 | 2.65625 | 3 |
[] |
no_license
|
package pipeline;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author wensen
* @since 2019-04-08
*/
public class DefaultPipeline implements Pipeline{
private final List<Valve> valves;
public DefaultPipeline(List<Valve> valves) {
if (valves != null && !valves.isEmpty()) {
this.valves = Collections.unmodifiableList(valves);
} else {
this.valves = Collections.EMPTY_LIST;
}
}
public PipelineContext newInvocation() {
return new DefaultPipelineContext();
}
class DefaultPipelineContext implements PipelineContext {
private volatile Iterator<Valve> iterator;
//下面三个状态由 lock 保护
private boolean broken;
private boolean finished;
private boolean canceled;
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
public DefaultPipelineContext() {
this.iterator = valves.listIterator();
}
public void invokeNext() {
if (this._isFinish()) {
return;
}
if (!isBroken() && iterator.hasNext()) {
Valve valve = iterator.next();
valve.invoke(this);
} else {
finish(false);
}
}
public boolean isBroken() {
try {
lock.lock();
return broken;
} finally {
lock.unlock();
}
}
private boolean _isFinish() {
try {
lock.lock();
return finished;
} finally {
lock.unlock();
}
}
public boolean isFinish() {
try {
lock.lock();
return !canceled && !broken && finished;
} finally {
lock.unlock();
}
}
private void finish(boolean cancel) {
try {
lock.lock();
if (cancel) {
this.canceled = true;
}
finished = true;
condition.signalAll();
} finally {
lock.unlock();
}
}
public void breakPipeline() {
try {
lock.lock();
broken = true;
} finally {
lock.unlock();
}
invokeNext();
}
public boolean isCanceled() {
return false;
}
public Map<String, Object> getAttributeMap() {
return null;
}
public <T> T getOuterContext() {
return null;
}
public <T> void setOuterContext(T context) {
}
}
}
|
Markdown
|
UTF-8
| 2,446 | 2.921875 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Cloud Journey Project Quickstart

<walkthrough-tutorial-url
url="https://cloud.google.com/compute/docs/gcpquest/intro_project">
</walkthrough-tutorial-url>
## Introduction
<walkthrough-tutorial-duration duration="10"></walkthrough-tutorial-duration>
Before you can can play the game, you have to make sure that you have a Google
Cloud account ready and a project to run the game. **If you are already a
Google Cloud user, you must create a new project to play the game.** \
\
This tutorial will instruct you to install an App Engine Application into
your project. **If you already have an App Engine application it will replace
it.** That's why you should use a clean project. \
\
Additionally, the game will ask you to perform technical tasks in the Cloud
Console. All of these have been designed to use free options.
\
To create a new project for the game follow below.
Please note: Limit project names to **30 characters** or less. This is a
limitation of the engine behind Cloud Journey, and not of GCP. \
\
<walkthrough-project-billing-setup></walkthrough-project-billing-setup>
## Record Project ID
**Please *Copy the ID* of the project you created. You will need this in the
game** \
\
You can see it by clicking the [Project Selector][spotlight-purview-switcher]
## Install Game Helper Application
The game uses an App Engine application to make various progress checks. You
must install this to progress in the game. **If you already have an App Engine application it will replace
it.**
Open Cloud Shell by clicking
<walkthrough-cloud-shell-icon></walkthrough-cloud-shell-icon> in the navigation
bar at the top of the console.
A Cloud Shell session opens inside a new frame at the bottom of the console and
displays a command-line prompt. It can take a few seconds for the shell session
to be initialized. \
\
When Cloud Shell is ready enter the following:
```bash
git clone https://github.com/tpryan/GCPQuest-Companion.git
```
When done enter the following:
```bash
cd GCPQuest-Companion && make
```
Once the App Engine application is installed you should see a success message.
## Conclusion
<walkthrough-conclusion-trophy></walkthrough-conclusion-trophy>
You're done!
Go back to the game, and keep questing.
[spotlight-purview-switcher]: walkthrough://spotlight-pointer?spotlightId=purview-switcher
|
PHP
|
UTF-8
| 541 | 2.890625 | 3 |
[] |
no_license
|
<?php
/**
* @file hola-mundo.php
* @version 1.0
* @author Linea de Codigo (http://lineadecodigo.com)
* @date 19-septiembre-2009
* @url http://lineadecodigo.com/php/hola-mundo-en-php/
* @description Programa Hola Mundo en PHP
*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hola Mundo en PHP</title>
</head>
<body>
<?php
echo "Hola Mundo";
?>
</body>
</html>
|
Java
|
UTF-8
| 713 | 1.898438 | 2 |
[] |
no_license
|
package cn.qlq.service;
import java.util.List;
import cn.qlq.bean.Doctor;
import cn.qlq.bean.Register;
import cn.qlq.bean.User;
import cn.qlq.bean.Usertype;
public interface UserService {
public List<User> findAllUser();
public List<Usertype> findAllUsertype();
public List<Register> findAllregister();
public void insertRegisterS(Register res);
public void deleteRegisterS(int id);
public void updateRegisterS(Register res);
public List<Doctor> finddoctor(String type);
public List<Doctor>findalldoctor();
public void deleteDoctorS(int id);
public void updateDoctorS(Doctor res);
public void insertDoctorS(Doctor res);
}
|
Java
|
UTF-8
| 685 | 1.945313 | 2 |
[] |
no_license
|
package kr.co.daters.serviceImpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import kr.co.daters.dao.BoMenuDAO;
import kr.co.daters.domain.BoMenuVO;
import kr.co.daters.service.BoMenuService;
@Service
public class BoMenuServiceImpl implements BoMenuService {
@Autowired
BoMenuDAO boMenuDAO;
@Override
public List<BoMenuVO> selectMenu(int boCode) {
return boMenuDAO.selectMenu(boCode);
}
@Override
public List<BoMenuVO> choiceMenuInfo(int mNo) {
return boMenuDAO.choiceMenuInfo(mNo);
}
@Override
public void updateQuantity(int mNo) {
boMenuDAO.updateQuantity(mNo);
}
}
|
Python
|
UTF-8
| 689 | 3.09375 | 3 |
[
"Apache-2.0"
] |
permissive
|
class command:
'''Command class;
allows the user to make their own commands for the AI
'''
def __init__(self,inp,function,response=''):
self.inp=inp #List
self.func=function #Function
self.response=response#String
commands=[]
#Example, shutdown command
import os
def shutdown():
os.system('shutdown /s')
commands.append(command(['shutdown'],shutdown,['shutting down...','shutting down the system...']))
#Example, open browser
import webbrowser
def openbrowser():
webbrowser.open('google.com')
commands.append(command(['open browser','browser'],openbrowser,['opening...','opening browser...']))
|
C++
|
UTF-8
| 3,892 | 4.46875 | 4 |
[] |
no_license
|
/*
Problem statement:
Design a class to efficiently find the Kth largest element in a stream of numbers.
The class should have the following two things:
The constructor of the class should accept an integer array containing initial numbers from the stream and an integer ‘K’.
The class should expose a function add(int num) which will store the given number and return the Kth largest number.
Example 1:
Input: [3, 1, 5, 12, 2, 11], K = 4
1. Calling add(6) should return '5'.
2. Calling add(13) should return '6'.
2. Calling add(4) should still return '6'.
*/
/*
------------------------- My Approaches:
1. Top k elements pattern
we can use a min heap as it follows the top k elements pattern. by using a min heap and
restricting it to size k, we will always have k elements. also since we have a min heap of size
k, the kth largest elemnt will always be atht the top of the min heap since the max value will be k levels down.
as a result, when adding a number, it becomes really easy to return the kth largest element since it is the top of the heap
depending whether the value we are adding is greater than the top of the heap or not.
Time complexity: O(log k) for add; O(log n) in worst case for return value
Space complexity: O(k)
*/
/*
------------------------- Other Approaches
1.
Time complexity: O()
Space complexity: O()
*/
/*
------------------------- Notes
follows top k elements pattern and shares similarities with kth smallest number.
can follow the same approach as dicussed in 'kth smallest number' problem. however, will use a
min heap(instead of max heap) as we need to find the kth largest number.
Time complexity: O()
Space complexity: O()
*/
// My approaches(1)
using namespace std;
#include <iostream>
#include <queue>
#include <vector>
class KthLargestNumberInStream {
public:
priority_queue<int, vector<int>, greater<int>> pq;
KthLargestNumberInStream(const vector<int> &nums, int k) {
// TODO: Write your code here
for(int i=0; i< nums.size(); i++){
if(pq.size() < k)
pq.push(nums[i]);
else if(nums[i] > pq.top()){
pq.pop();
pq.push(nums[i]);
}
}
}
virtual int add(int num) {
// TODO: Write your code here
int result = 0;
if(num > pq.top()){
pq.pop();
result = pq.top();
pq.push(num);
}
else
result = pq.top();
return result;
}
};
int main(int argc, char *argv[]) {
KthLargestNumberInStream kthLargestNumber({3, 1, 5, 12, 2, 11}, 4);
cout << "4th largest number is: " << kthLargestNumber.add(6) << endl;
cout << "4th largest number is: " << kthLargestNumber.add(13) << endl;
cout << "4th largest number is: " << kthLargestNumber.add(4) << endl;
}
// Other Approaches(1)
using namespace std;
#include <iostream>
#include <queue>
#include <vector>
class KthLargestNumberInStream {
public:
struct numCompare {
bool operator()(const int &x, const int &y) { return x > y; }
};
priority_queue<int, vector<int>, numCompare> minHeap;
const int k;
KthLargestNumberInStream(const vector<int> &nums, int k) : k(k) {
// add the numbers in the min heap
for (int i = 0; i < nums.size(); i++) {
add(nums[i]);
}
}
virtual int add(int num) {
// add the new number in the min heap
minHeap.push(num);
// if heap has more than 'k' numbers, remove one number
if ((int)minHeap.size() > this->k) {
minHeap.pop();
}
// return the 'Kth largest number
return minHeap.top();
}
};
int main(int argc, char *argv[]) {
KthLargestNumberInStream kthLargestNumber({3, 1, 5, 12, 2, 11}, 4);
cout << "4th largest number is: " << kthLargestNumber.add(6) << endl;
cout << "4th largest number is: " << kthLargestNumber.add(13) << endl;
cout << "4th largest number is: " << kthLargestNumber.add(4) << endl;
}
|
Markdown
|
UTF-8
| 22,157 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
---
layout: post
title: 实现 socks5 代理
description: 现在很多人都在用,天天用的软件,却对它的实现协议却知之甚少。
category: blog
---
socks5 协议继承自 socks 协议。
> 竟然是两年前的旧文,终于要来填坑了。
## 正向代理和反向代理
反向代理就医院里的挂号处,公司里的行政前台,你不需要关心具体的处理人,不用关心内部逻辑,只需要找到对接人就可以了,反向代理服务器就是这个对接人。
正向代理像是你的望远镜,就是你的皮夹克,穿戴上他,你可以伪装成另一个人,甚至就像附身在你的小跟班身上,通过另一双眼镜去看世界,隐藏自己的身份,逃出生天,正向代理服务器就是这个伪装。
## 反向代理
首先我们看下最简单的反向代理实现,简单的请求转发。你以为你请求的是A,实际上调用的是B,即B被反向代理到了A上,A的请求被转发到了B上。
```python
# -*- coding: utf-8 -*-
import socket
import threading
source_host = '127.0.0.1'
source_port = 5002
desc_host = '127.0.0.1'
desc_port = 8099
def send(sender, recver):
while 1:
try:
data = sender.recv(2048)
except:
print("recv error")
break
if not data:
break
try:
recver.sendall(data)
except:
print("send error")
break
sender.close()
recver.close()
def proxy(client):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.connect((source_host, source_port))
threading.Thread(target=send, args=(client, server)).start()
threading.Thread(target=send, args=(server, client)).start()
def main():
proxy_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
proxy_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
proxy_server.bind((desc_host, desc_port))
proxy_server.listen(5)
print("Proxying from %s:%s to %s:%s ..." % (source_host, source_port, desc_host, desc_port))
while 1:
conn, addr = proxy_server.accept()
print("received connect from %s:%s" % (addr[0], addr[1]))
threading.Thread(target=proxy, args=(conn,)).start()
if __name__ == '__main__':
main()
```
真的非常简单,手动监听端口,手动处理请求,手动读写数据。
使用 socketserver 提供的 server 和 handle 处理就是这样。
```python
# -*- coding: utf-8 -*-
import socket
import logging
import threading
from socketserver import StreamRequestHandler, BaseRequestHandler
from socketserver import ThreadingTCPServer as RawThreadingTCPServer
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class ThreadingTCPServer(RawThreadingTCPServer):
allow_reuse_address = True
class ProxyHandler(BaseRequestHandler):
def handle(self):
# should be blocked until finish handle.
target = socket.create_connection(('127.0.0.1', 5002))
thread_list = []
thread_list.append(threading.Thread(
target=self.forward_reply, args=(self.request, target)
))
thread_list.append(threading.Thread(
target=self.forward_reply, args=(target, self.request)
))
for t in thread_list:
t.start()
for t in thread_list:
t.join()
def forward_reply(self, local, target):
try:
while True:
# target.write(local.read())
data = local.recv(1024)
if not data:
return
target.send(data)
except Exception as e:
logger.info("forward error:%r", e)
raise e
if __name__ == '__main__':
server = ThreadingTCPServer(('127.0.0.1', 5003), ProxyHandler)
server.serve_forever()
```
看起来确实少些两行代码,但是实际上还是非常的基础和简单。
## socks5 协议
socks5 属于正向代理的一种,像上面的反向代理和正向代理的区别在哪里呢?
那就是反向代理的目标地址是固定的,也就是说,请求转发的的终点已经固定了,但是如果我们想要自由的转发请求到任意地址呢?就需要正向代理服务了。
```python
# -*- coding: utf-8 -*-
import socket
import struct
import select
import gevent
import logging
import threading
from socketserver import StreamRequestHandler
from socketserver import ThreadingTCPServer as RawThreadingTCPServer
from gevent import monkey
monkey.patch_all()
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
AUTH_USERNAME = "YOUR_PROXY_LOGIN"
AUTH_PASSWORD = "YOUR_PROXY_PASSWORD"
class ThreadingTCPServer(RawThreadingTCPServer):
allow_reuse_address = True
class SocksException(Exception):
pass
class Socks5Handler(StreamRequestHandler):
def handle_forward(self, client, remote):
# two threading to read and write
# handle should be blocked
thread_list = [threading.Thread(
target=self.forward_reply, args=(client, remote)
), threading.Thread(
target=self.forward_reply, args=(remote, client)
)]
for t in thread_list:
t.start()
for t in thread_list:
t.join()
def handle_forward_in_gevent(self, client, remote):
spawns = [gevent.spawn(self.forward_reply, client, remote), gevent.spawn(self.forward_reply, remote, client)]
gevent.joinall(spawns)
def forward_reply(self, local, target):
# type: (socket.socket, socket.socket) -> None
try:
while True:
# target.write(local.read())
data = local.recv(1024)
if not data:
return
target.send(data)
except Exception as e:
logger.info("forward error:%r", e)
raise e
def handle_forward_in_select(self, client, remote):
# type: (socket.socket, socket.socket) -> None
try:
inputs = [client, remote]
while inputs:
readable, _, _ = select.select(inputs, [], [])
if client in readable:
data = client.recv(4096)
if not data:
break
remote.sendall(data)
if remote in readable:
data = remote.recv(4096)
if not data:
break
client.sendall(data)
except Exception as e:
logger.info("select error:%r", e)
def socks_user_auth(self):
buf = self.rfile.read(2)
if buf[0] != chr(0x01):
raise SocksException("invalid version")
username_length = ord(buf[1])
username = self.rfile.read(username_length)
buf = self.rfile.read(1)
password_length = ord(buf[0])
password = self.rfile.read(password_length)
logger.info("user auth: %s-%s", username, password)
if username == AUTH_USERNAME and password == AUTH_PASSWORD:
self.wfile.write(b'\x01\x00')
else:
self.wfile.write(b'\x01\x01')
raise SocksException("socks user auth fail")
def socks_auth(self):
# self.rfile._sock.recv(2)
buf = self.rfile.read(2)
if buf[0] != chr(0x05):
# python3 will get int
# if buf[0] != chr(0x05):
# if buf[0] != b'\x05':
raise SocksException("invalid version")
methods_length = ord(buf[1])
methods = self.rfile.read(methods_length)
logger.info("receive methods:%r", methods)
if b'\x02' in methods:
# socks user auth
self.wfile.write(b'\x05\x02')
self.socks_user_auth()
else:
self.wfile.write(b'\x05\x00')
# maybe need one
# self.wfile.flush()
def socks_connect(self):
ver, cmd, _, addr_type = self.rfile.read(4)
if ver != chr(0x05) or cmd != chr(0x01):
raise SocksException("invalid ver/cmd")
if addr_type == chr(0x01):
logger.info("client addr type:IPv4")
packed_ip = self.rfile.read(4)
remote_addr = socket.inet_ntoa(packed_ip)
elif addr_type == chr(0x03):
logger.info("client addr type:URL")
addr_length = self.wfile.read(1)
remote_addr = self.rfile.read(ord(addr_length))
elif addr_type == chr(0x04):
logger.info("client addr type:IPv6")
packed_ip = self.rfile.read(16)
remote_addr = socket.inet_ntop(socket.AF_INET6, packed_ip)
else:
raise SocksException("addr_type not supported.")
addr_port = self.rfile.read(2)
# 注意:这里是返回的tuple
remote_port = struct.unpack('>H', addr_port)[0]
reply = b'\x05\x00\x00\x01'
reply += socket.inet_aton('0.0.0.0') + struct.pack('>H', 2222)
self.wfile.write(reply)
return remote_addr, remote_port
def handle(self):
try:
logger.info("receive from:%r", self.request.getpeername())
# step one: sock auth
self.socks_auth()
# step two: sock connect
remote_addr, remote_port = self.socks_connect()
logger.info("target addr:%r", (remote_addr, remote_port))
# step three: sock forward
remote = socket.create_connection((remote_addr, remote_port))
self.handle_forward_in_select(self.connection, remote)
except SocksException as e:
logger.info("socks error:%r", e)
except socket.error as e:
logger.info("socket error:%r", e)
raise
if __name__ == '__main__':
server = ThreadingTCPServer(('127.0.0.1', 8572), Socks5Handler)
server.serve_forever()
```
实现了 TCP 的 socks5 代理,同时支持 IPv6和用户认证,使用 curl 来测试下。
```shell
$ curl --socks5 socks5://127.0.0.1:9458 http://ipconfig.io
65.13.234.13
$ curl -4 --socks5 socks5://YOUR_PROXY_LOGIN:YOUR_PROXY_PASSWORD@127.0.0.1:9458 http://ipconfig.io
65.13.234.13
$ curl -6 --socks5 socks5://YOUR_PROXY_LOGIN:YOUR_PROXY_PASSWORD@127.0.0.1:9458 http://ipconfig.io
240e:b2:e401:4::7
$ curl --socks5 socks5://YOUR_PROXY_LOGIN:YOUR_PROXY_PASSWOR@127.0.0.1:9458 http://ipconfig.io
curl: (7) User was rejected by the SOCKS5 server (1 1).
```
## 具体实现
研究一下 socks5 的协议定义,socks5 protocol 在请求转发之前有两步交互,在请求认证,和获取目的地址之后,就和上文一下发起请求转发即可。
> 正向代理中,除了 socks5 还有 socks4 和 socks4a,都比 socks5 简单,就不详细介绍了。
1. sock auth
2. sock connect
3. sock forward
#### Auth
认证流程
##### client ---> server
客户端发送请求确认版本和请求方式,单位字节
```
+-------------------------+
| VER | NMETHODS | METHODS|
+-------------------------+
| 1 | 1 | 1-255 |
+-------------------------+
```
- VER: socks 的版本,这里应该是 `0x05`
- NMETHODS: METHODS 部分的长度,取值范围 1~255
- METHODS: 客户端支持的认证方式列表,每个方法占1字节,支持的认证方式有
- `0x00`: 不需要认证
- `0x01`: GSSAPI
- `0x02`: 用户名,密码认证
- `0x03`-`0x7F`: 保留,有 IANA 分配
- `0x80`-`0xFE`: 自定义,私人方法
- `0xFF`: 无可接受的的方法
###### server ---> client
服务器端返回支持的方法,单位字节
```
+--------------+
| VER | METHOD |
+--------------+
| 1 | 1 |
+--------------+
```
- VER: socks 的版本,这里应该是 `0x05`
- METHOD: 服务端选中的方法。如果返回 `0xFF` 表示没有选中任何方法,客户端需要关闭连接。
#### Connect
认证结束之后,客户端发送请求信息
##### client ---> server
```
+---------------------------------------------------+
| VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
+---------------------------------------------------+
| 1 | 1 | 1 | 1 | (dynamic) | 2 |
+---------------------------------------------------+
```
- VER: socks 的版本,这里应该是 `0x05`
- CMD: sock 的命令码
- `0x01`: 表示 CONNECT 请求
- `0x02`: 表示 BIND 请求
- `0x03`: 表示 UDP 转发
- RSV: 保留,固定 `0x00`
- ATYP: DST.ADDR 的地址类型
- `0x01`: IPv4 地址,DST.ADDR 部分4字节长度
- `0x03`: DST.ADDR 部分第一个字节为域名长度,DST.ADDR 剩余部分内容为域名,没有`\0`的结束符
- `0x04`: IPv6 地址,DST.ADDR 部分16字节长度
- DST.ADDR 目的地址
- DST.PORT 目的端口
##### server ---> client
```
+---------------------------------------------------+
| VER | REP | RSV | ATYP | DST.ADDR | DST.PORT |
+---------------------------------------------------+
| 1 | 1 | 1 | 1 | (dynamic) | 2 |
+---------------------------------------------------+
```
- VER: socks 的版本,这里应该是 `0x05`
- REP: 应答字段,表示请求状态
- `0x00`: 表示成功
- `0x00`: 表示 SOCKS 服务器连接失败
- `0x02`: 表示现有规则不允许连接
- `0x03`: 表示网络不可达
- `0x04`: 表示主机不可达
- `0x05`: 表示连接被拒
- `0x06`: 表示TTL超时
- `0x07`: 表示不支持的命令
- `0x08`: 表示不支持的地址类型
- `0x09`-`0xFF`: 未定义
- RSV: 保留,固定 `0x00`
- ATYP: DST.ADDR 的地址类型
- `0x01`: IPv4 地址,DST.ADDR 部分4字节长度
- `0x03`: DST.ADDR 部分第一个字节为域名长度,DST.ADDR 剩余部分内容为域名,没有`\0`的结束符
- `0x04`: IPv6 地址,DST.ADDR 部分16字节长度
- DST.ADDR 服务器绑定的地址
- DST.PORT 服务器绑定的端口
#### Forward
端口转发
#### UserAuth
使用用户名密码的方式进行用户认证
##### client ---> server
```
+--------------------------------------------------------------------+
| VER | username length | username | password length | password |
+--------------------------------------------------------------------+
| 1 | 1 | (dynamic) | 1 | (dynamic) |
+--------------------------------------------------------------------+
```
- VER: 鉴定协议版本,目前为 `0x01`
- username length: 用户名长度
- username: 用户名
- password length: 密码长度
- password: 密码
##### server ---> client
```
+--------------+
| VER | STATUS |
+--------------+
| 1 | 1 |
+--------------+
```
- VER: 鉴定协议版本,目前为 `0x01`
- STATUS: 鉴定状态
- `0x00`: 表示成功
- `0x01`: 表示失败
## 其他实现
用 Python 实现已经很简单了,但是我没想到的时候,使用 Golang 在网络操作上更底层更方便,也更加容易扩展。
```golang
package main
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"log"
"net"
)
type Socks5UserAuthInfo struct {
Username []byte
Password []byte
}
var socks5UserAuthInfo = Socks5UserAuthInfo{
Username: []byte("YOUR_PROXY_LOGIN"),
Password: []byte("YOUR_PROXY_PASSWORD"),
}
func Socks5Connect(client net.Conn) (dstConn net.Conn, err error) {
buf := make([]byte, 256)
// 读取请求命令
n, err := client.Read(buf[:4])
if n != 4 || err != nil {
return nil, errors.New("reading header: " + err.Error())
}
ver, cmd, _, atyp := buf[0], buf[1], buf[2], buf[3]
if ver != 5 || cmd != 1 {
return nil, errors.New("invalid ver/cmd")
}
// 读取请求地址
addr := ""
switch atyp {
case 1:
log.Printf("client addr type:IPv4\n")
n, err = io.ReadFull(client, buf[:4])
if n != 4 || err != nil {
return nil, errors.New("reading IPv4 addr error:" + err.Error())
}
addr = net.IP(buf[:4]).String()
case 3:
log.Printf("client addr type:URL\n")
n, err = io.ReadFull(client, buf[:1])
if n != 1 || err != nil {
return nil, errors.New("reading addr Len error:" + err.Error())
}
addrLen := int(buf[0])
n, err = io.ReadFull(client, buf[:addrLen])
if n != addrLen || err != nil {
return nil, errors.New("reading addr URL error:" + err.Error())
}
addr = string(buf[:addrLen])
case 4:
log.Printf("client addr type:IPv6\n")
n, err = io.ReadFull(client, buf[:16])
if n != 16 || err != nil {
return nil, errors.New("reading IPv4 addr error:" + err.Error())
}
addr = net.IP(buf[:16]).String()
default:
log.Printf("client addr type:Unknown\n")
return nil, errors.New("invalid atyp")
}
n, err = io.ReadFull(client, buf[:2])
if n != 2 || err != nil {
return nil, errors.New("reading port error:" + err.Error())
}
port := binary.BigEndian.Uint16(buf[:2])
network := ""
dst := ""
switch atyp {
case 1:
network = "tcp"
dst = fmt.Sprintf("%s:%d", addr, port)
case 3:
network = "tcp"
dst = fmt.Sprintf("%s:%d", addr, port)
case 4:
network = "tcp6"
dst = fmt.Sprintf("[%s]:%d", addr, port)
}
log.Printf("client addr:%s\n", dst)
dstConn, err = net.Dial(network, dst)
if err != nil {
return nil, errors.New("dial dst error:" + err.Error())
}
// 返回连接状态
n, err = client.Write([]byte{0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
if err != nil {
dstConn.Close()
return nil, errors.New("writing error:" + err.Error())
}
return dstConn, nil
}
func Socks5Auth(client net.Conn) (err error) {
buf := make([]byte, 256)
// 读取 VER 和 NMETHODS
//n, err := io.ReadFull(client, buf[:2])
n, err := client.Read(buf[:2])
if n != 2 || err != nil {
return errors.New("reading header: " + err.Error())
}
ver, nMethods := int(buf[0]), int(buf[1])
if ver != 5 {
return errors.New("invalid version")
}
// 读取 METHODS 列表
n, err = io.ReadFull(client, buf[:nMethods])
if n != nMethods {
return errors.New("reading methods:" + err.Error())
}
log.Printf("client accept methods:%+v\n", buf[:nMethods])
if bytes.IndexByte(buf[:nMethods], 0x02) < 0 {
// 如果没有用户名密码,则返回无需认证
n, err = client.Write([]byte{0x05, 0x00})
if n != 2 || err != nil {
return errors.New("writing error:" + err.Error())
}
} else {
// 返回用户名密码认证
n, err = client.Write([]byte{0x05, 0x02})
if n != 2 || err != nil {
return errors.New("writing error:" + err.Error())
}
return Socks5UserAuth(client)
}
return nil
}
func Socks5UserAuth(client net.Conn) (err error) {
buf := make([]byte, 256)
var username, password []byte
// 读取用户名
n, err := client.Read(buf[:2])
if n != 2 || err != nil {
return errors.New("reading header: " + err.Error())
}
ver, nUsername := int(buf[0]), int(buf[1])
if ver != 1 {
return errors.New("invalid version")
}
n, err = client.Read(buf[:nUsername])
if n != nUsername {
return errors.New("reading username error:" + err.Error())
}
username = make([]byte, nUsername)
copy(username, buf[:nUsername])
// 读取密码
n, err = client.Read(buf[:1])
if n != 1 || err != nil {
return errors.New("reading header: " + err.Error())
}
nPassword := int(buf[0])
n, err = client.Read(buf[:nPassword])
if n != nPassword {
return errors.New("reading password error:" + err.Error())
}
password = make([]byte, nPassword)
copy(password, buf[:nPassword])
log.Printf("user auth username:%s, password:%s\n", username, password)
if bytes.Equal(username, socks5UserAuthInfo.Username) && bytes.Equal(password, socks5UserAuthInfo.Password) {
// 认证成功
n, err = client.Write([]byte{0x01, 0x00})
if n != 2 || err != nil {
return errors.New("writing error:" + err.Error())
}
} else {
// 认证失败
n, err = client.Write([]byte{0x01, 0x01})
if n != 2 || err != nil {
return errors.New("writing error:" + err.Error())
}
return errors.New("user auth fail")
}
return nil
}
func Socks5Forward(client, target net.Conn) {
forward := func(src, dst net.Conn) {
defer src.Close()
defer dst.Close()
io.Copy(src, dst)
}
go forward(client, target)
go forward(target, client)
}
func Socks5Process(client net.Conn) {
log.Printf("start socks5 auth handle")
if err := Socks5Auth(client); err != nil {
log.Printf("auth error:%+v\n", err)
client.Close()
return
}
log.Printf("start socks5 connect handle")
target, err := Socks5Connect(client)
if err != nil {
log.Printf("connect error:%+v\n", err)
client.Close()
return
}
log.Printf("start socks5 forward handle")
Socks5Forward(client, target)
}
func main() {
server, err := net.Listen("tcp", ":6543")
if err != nil {
log.Printf("Listen failed: %v\n", err)
return
}
for {
client, err := server.Accept()
if err != nil {
log.Printf("Accept failed: %v\n", err)
continue
}
remoteAddr := client.RemoteAddr().String()
remoteNetwork := client.RemoteAddr().Network()
log.Printf("Connection from: [%s]%s\n", remoteNetwork, remoteAddr)
// 反向代理服务器
//go ReverseProxyProcess(client)
// 正向代理服务器-socks5
go Socks5Process(client)
}
}
func ReverseProxyProcess(client net.Conn) {
dstConn, err := net.Dial("tcp", "127.0.0.1:5002")
if err != nil {
client.Close()
log.Printf("Connect Internal failed: %v\n", err)
return
}
Socks5Forward(client, dstConn)
}
```
## 参考链接
[实战:150行Go实现高性能socks5代理](https://mp.weixin.qq.com/s?__biz=MzU4NDA0OTgwOA==&mid=2247484209&idx=1&sn=2e9a2f2000d4430d4c0ccf31b25a1344&chksm=fd9ef6cecae97fd8b264700f10bae0c97557a2cc852180454757877d9c172161227a4fa2f733&scene=21#wechat_redirect)
[实战:150行Go实现高性能加密隧道](https://mp.weixin.qq.com/s?__biz=MzU4NDA0OTgwOA==&mid=2247484246&idx=1&sn=be8a1e6f36c7b7da22da34854adb022e&chksm=fd9ef6a9cae97fbf983af32a4ff5b20853b716d24ef43edcfda71539ebe8e97ea1ae2ce92245&scene=21#wechat_redirect)
[实战:+65行Go实现低延迟隧道](https://mp.weixin.qq.com/s/4r1I9-wCLcs2uf8uxXtVvQ)
[SOCKS Protocol Version 5](https://tools.ietf.org/html/rfc1928)
[SOCKS](https://zh.wikipedia.org/wiki/SOCKS)
[socks4 protocol](https://www.openssh.com/txt/socks4.protocol)
|
Java
|
UTF-8
| 766 | 3.390625 | 3 |
[] |
no_license
|
package com.learn;
import java.util.Arrays;
/**
* 示例 1:
* <p>
* 输入: [1,2,3], [1,1]
* <p>
* 输出: 1
* <p>
* 解释:
* 你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。
* 虽然你有两块小饼干,由于他们的尺寸都是1,你只能让胃口值是1的孩子满足。
* 所以你应该输出1。
*/
public class leet455 {
public int findContentChildren(int[] g, int[] s) {
if (g.length == 0 || s.length == 0) {
return 0;
}
Arrays.sort(g);
Arrays.sort(s);
int gi = 0, si = 0;
while (gi < g.length && si < s.length) {
if (g[gi] <= s[si]) {
gi++;
}
si++;
}
return gi;
}
}
|
Python
|
UTF-8
| 7,766 | 3.03125 | 3 |
[] |
no_license
|
from collections import defaultdict
import pprint
import fileinput
import math
import sys
import matplotlib.pyplot as plt
import time
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class LearnGrammar:
def __init__(self):
self.probability = defaultdict(lambda: defaultdict(float))
def parse_tree(self, root):
if root.left == None:
return
if root.right == None:
self.probability[root.val][root.left.val] += 1
return
self.probability[root.val][root.left.val + " " + root.right.val] += 1
self.parse_tree(root.left)
self.parse_tree(root.right)
def calculate_probability(self):
output = ""
for row in self.probability:
total = 0
for i in self.probability[row]:
total += self.probability[row][i]
for j in self.probability[row]:
self.probability[row][j] = self.probability[row][j] / float(total)
output += row + " -> " + j + " # " + str(self.probability[row][j]) + "\n"
return output
def recursion_build_tree(self, text):
token = self.tokenize(text)
if not token:
return None
elif len(token) == 2:
root = TreeNode(token[0])
root.left = TreeNode(token[1])
return root
root = TreeNode(token[0])
root.left = self.recursion_build_tree(token[1])
root.right = self.recursion_build_tree(token[2])
return root
def tokenize(self, text):
text = text.strip()[1:-1]
pos = text.find("(")
if pos == -1:
return text.split(" ")
output = [text[:pos].strip()]
stack = []
for i in xrange(len(text)):
if text[i] == '(':
stack.append(1)
elif text[i] == ')' and stack:
stack.pop(-1)
elif text[i] == ')':
print "Invalid input"
return []
else:
continue
if not stack:
output.append(text[pos:i + 1].strip())
output.append(text[i + 1:].strip())
return output
class Parser:
def __init__(self, rules):
self.rules = rules
self.reverse_rules = defaultdict(lambda: defaultdict(float))
for i in self.rules:
for j in self.rules[i]:
self.reverse_rules[j][i] = self.rules[i][j]
def parse(self, text, mode = 0):
tokens = text.split(" ")
best = {}
back = {}
for i in xrange(0, len(tokens)):
for j in xrange(i + 1, len(tokens) + 1):
best[(i,j)] = defaultdict(lambda: float(-sys.maxint - 1))
back[(i,j)] = {}
for i in xrange(1, len(tokens) + 1):
tmp = self.lookup(tokens[i - 1])
for (x, y, pro) in tmp:
if pro > best[(i - 1, i)][x]:
best[(i - 1, i)][x] = pro
back[(i - 1, i)][x] = (x, y)
for offset in xrange(2, len(tokens) + 1):
for i in xrange(len(tokens) - offset + 1):
j = i + offset
for k in xrange(i + 1, j):
if not best[(i, k)] or not best[(k, j)]:
continue
for l_tag, l_pro in best[(i, k)].items():
for r_tag, r_pro in best[(k, j)].items():
tmp = self.lookup(l_tag + " " + r_tag)
for (x, y, pro) in tmp:
p = pro + l_pro + r_pro
if p > best[(i, j)][x]:
best[(i, j)][x] = p
back[(i, j)][x] = (x, y, k)
if not back[(0, len(tokens))] and mode == 0:
return ""
elif not back[(0, len(tokens))]:
output = []
for i in xrange(len(tokens)):
best_pro = -sys.maxint - 1
best_tag = ""
for t in best[(i, i + 1)]:
if best[(i, i + 1)][t] > best_pro:
best_pro = best[(i, i + 1)][t]
best_tag = t
tag = best_tag
if tag == "":
continue
output.append("(" + back[(i, i + 1)][tag][0] + " " + back[(i, i + 1)][tag][1] + ")")
return " ".join(output)
return self.recursive_print_tree(0, len(tokens), best, back)
def lookup(self, items):
output = []
if items in self.reverse_rules:
for i in self.reverse_rules[items]:
output.append((i, items, math.log(self.reverse_rules[items][i], 10)))
elif len(items.split(" ")) == 1:
for i in self.reverse_rules["<unk>"]:
output.append((i, items, math.log(self.reverse_rules["<unk>"][i], 10)))
return output
def recursive_print_tree(self, l, r, best, back, tag=None):
if tag == None:
best_pro = -sys.maxint - 1
best_tag = ""
for t in best[(l, r)]:
if best[(l,r)][t] > best_pro:
best_pro = best[(l ,r)][t]
best_tag = t
tag = best_tag
if tag == None:
return
if l + 1 == r:
return "(" + back[(l, r)][tag][0] + " " + back[(l, r)][tag][1] + ")"
mid = back[(l, r)][tag][2]
l_tag = back[(l, r)][tag][1].split()[0]
r_tag = back[(l, r)][tag][1].split()[1]
return "(" + back[(l, r)][tag][0] + " " + self.recursive_print_tree(l, mid, best, back, l_tag) + " " + self.recursive_print_tree(mid, r, best, back, r_tag) + ")"
def pretty(d, indent=0):
for key, value in d.items():
print('\t' * indent + str(key))
if isinstance(value, dict):
pretty(value, indent + 1)
else:
print('\t' * (indent + 1) + str(value))
lg_sibling = LearnGrammar()
lg_parent = LearnGrammar()
flag = True
for line in fileinput.input():
if flag:
root = lg_sibling.recursion_build_tree(line)
lg_sibling.parse_tree(root)
flag = not flag
else:
root = lg_parent.recursion_build_tree(line)
lg_parent.parse_tree(root)
flag = not flag
a = lg_sibling.calculate_probability()
b = lg_parent.calculate_probability()
# output_pro = open("rules_sibling", "w")
# output_pro.write(a)
# output_pro.close()
with open('dev.strings') as f:
lines = f.readlines()
f_output = open('dev.parses', 'w')
#plot_file = open('length-time', 'w')
text_length = []
elapsed_time = []
i = 1
p_sibling = Parser(lg_sibling.probability)
p_parent = Parser(lg_parent.probability)
for line in lines:
# start_time = time.time()
tmp = p_sibling.parse(line.strip())
if tmp.strip() == "":
tmp = p_parent.parse(line.strip(), 1)
# text_length.append(math.log(len(line.split()), 10))
# elapsed_time.append(math.log((time.time() - start_time) * 1000 * 300, 10))
f_output.write(tmp + "\n")
#print str(i) + " done."
#i += 1
#sys.stdout.flush()
# plt.figure(1)
# plt.plot(text_length, elapsed_time, 'bo')
# a = [0, 1, 1.2, 1.4, 1.6, 1.8, 2]
# plt.plot(a, [i * 3 for i in a])
# plt.axis([0, max(text_length), 0, max(elapsed_time)])
# plt.xlabel('Text Length (log)')
# plt.ylabel('Elapsed Time (log)')
# plt.show()
# p = Parser(lg.probability)
# print p.parse("The flight should be eleven a.m tomorrow .")
# print p.parse("I would like it to have a stop in New York and I would like a flight that serves breakfast .")
#unit test for lookup function
#print p.lookup("DT NP_NN")
|
PHP
|
UTF-8
| 1,433 | 2.78125 | 3 |
[] |
no_license
|
<?php
session_start();
if (!isset($_SESSION['zalogowany'])) {
header('Location: index.php');
exit();
}
unset($_SESSION['blad']);
if (isset($_POST['haslo'])) {
//Przypisanie loginu z sesji do zmiennej
$user = $_SESSION['user'];
$haslo = $_POST['haslo'];
require_once "connect.php";
mysqli_report(MYSQLI_REPORT_STRICT);
$polaczenie = @new mysqli($host, $db_user, $db_password, $db_name);
if ($polaczenie->connect_errno != 0) {
} else {
//sprawdzenie poprawności hasła
$rezultat = $polaczenie->query(sprintf("SELECT pass FROM uzytkownicy WHERE user = '$user'"));
$wiersz = $rezultat->fetch_assoc();
if (password_verify($haslo, $wiersz['pass'])) {
$polaczenie->query("DELETE FROM `uzytkownicy` WHERE `uzytkownicy`.`user`='$user'");
header('Location: logout.php');
exit();
} else {
$_SESSION['blad'] = "Niepoprawne hasło";
}
}
$polaczenie->close();
}
?>
<!DOCTYPE HTML>
<html lang="pl">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<title>Projekt TAI</title>
</head>
<body>
<a href="index.php">Wróć</a><br/><br/>
<form method="post">
Hasło: <br/><input type="password" name="haslo"/><br/>
<input type="submit" value="Usuń konto">
</form>
<?php
if (isset($_SESSION['blad'])) echo $_SESSION['blad'];
?>
</body>
</html>
|
Java
|
UTF-8
| 5,858 | 3 | 3 |
[
"MIT"
] |
permissive
|
package com.example.app;
import java.awt.event.*;
import javax.swing.*;
public class Calculator {
private static Calculator ms_instance = null;
public native String print();
public native int key(String val);
private JTextField m_output;
static
{
System.loadLibrary("calculator_jni");
}
private Calculator() {
m_output = new JTextField();
}
public static synchronized Calculator getInstance()
{
if (ms_instance == null)
{
ms_instance = new Calculator();
}
return ms_instance;
}
JTextField getOutput()
{
return m_output;
}
public static void main( String[] args )
{
Calculator calc = Calculator.getInstance();
JFrame frame = new JFrame("Calculator");
getInstance().getOutput().setBounds(5, 5, 370, 30);
getInstance().getOutput().setHorizontalAlignment(JTextField.TRAILING);
getInstance().getOutput().setEditable(false);
getInstance().getOutput().setText(calc.print());
frame.add(getInstance().getOutput());
JButton[] keys = {
new JButton("0"),
new JButton("1"),
new JButton("2"),
new JButton("3"),
new JButton("4"),
new JButton("5"),
new JButton("6"),
new JButton("7"),
new JButton("8"),
new JButton("9"),
};
int key_w = 70;
int key_h = 70;
keys[7].setBounds(5 + (key_w * 0) + (5 * 0), 40 + (key_h * 0), key_w, key_h);
keys[8].setBounds(5 + (key_w * 1) + (5 * 1), 40 + (key_h * 0), key_w, key_h);
keys[9].setBounds(5 + (key_w * 2) + (5 * 2), 40 + (key_h * 0), key_w, key_h);
keys[4].setBounds(5 + (key_w * 0) + (5 * 0), 40 + (key_h * 1) + (5 * 1), key_w, key_h);
keys[5].setBounds(5 + (key_w * 1) + (5 * 1), 40 + (key_h * 1) + (5 * 1), key_w, key_h);
keys[6].setBounds(5 + (key_w * 2) + (5 * 2), 40 + (key_h * 1) + (5 * 1), key_w, key_h);
keys[1].setBounds(5 + (key_w * 0) + (5 * 0), 40 + (key_h * 2) + (5 * 2), key_w, key_h);
keys[2].setBounds(5 + (key_w * 1) + (5 * 1), 40 + (key_h * 2) + (5 * 2), key_w, key_h);
keys[3].setBounds(5 + (key_w * 2) + (5 * 2), 40 + (key_h * 2) + (5 * 2), key_w, key_h);
keys[0].setBounds(5 + (key_w * 0) + (5 * 0), 40 + (key_h * 3) + (5 * 3), key_w, key_h);
keys[0].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Calculator.getInstance().key("0");
getInstance().getOutput().setText(Calculator.getInstance().print());
}
});
keys[1].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Calculator.getInstance().key("1");
getInstance().getOutput().setText(Calculator.getInstance().print());
}
});
keys[2].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Calculator.getInstance().key("2");
getInstance().getOutput().setText(Calculator.getInstance().print());
}
});
keys[3].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Calculator.getInstance().key("3");
getInstance().getOutput().setText(Calculator.getInstance().print());
}
});
keys[4].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Calculator.getInstance().key("4");
getInstance().getOutput().setText(Calculator.getInstance().print());
}
});
keys[5].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Calculator.getInstance().key("5");
getInstance().getOutput().setText(Calculator.getInstance().print());
}
});
keys[5].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Calculator.getInstance().key("5");
getInstance().getOutput().setText(Calculator.getInstance().print());
}
});
keys[6].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Calculator.getInstance().key("6");
getInstance().getOutput().setText(Calculator.getInstance().print());
}
});
keys[7].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Calculator.getInstance().key("7");
getInstance().getOutput().setText(Calculator.getInstance().print());
}
});
keys[8].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Calculator.getInstance().key("8");
getInstance().getOutput().setText(Calculator.getInstance().print());
}
});
keys[9].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Calculator.getInstance().key("9");
getInstance().getOutput().setText(Calculator.getInstance().print());
}
});
for(JButton b : keys)
{
frame.add(b);
}
frame.setSize(400,400);
frame.setResizable(false);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
|
Markdown
|
UTF-8
| 6,294 | 2.640625 | 3 |
[] |
no_license
|
---
description: "Steps to Prepare Speedy Taco bowl"
title: "Steps to Prepare Speedy Taco bowl"
slug: 1573-steps-to-prepare-speedy-taco-bowl
date: 2020-11-14T02:39:23.042Z
image: https://img-global.cpcdn.com/recipes/5579c5ad088b816a/751x532cq70/taco-bowl-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/5579c5ad088b816a/751x532cq70/taco-bowl-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/5579c5ad088b816a/751x532cq70/taco-bowl-recipe-main-photo.jpg
author: Gregory Shelton
ratingvalue: 4.3
reviewcount: 29061
recipeingredient:
- " Ground beef"
- " Pinto beans"
- " Lettuce"
- " Tomatoes"
- " Bell peppers"
- " Cucumbers"
- " Cheese"
- " Flour tortillas"
recipeinstructions:
- "Make the ground beef as you do for tacos."
- "I use home cooked pinto beans."
- "Fry flour tortillas in deep oil to bowl shape."
- "Make your own bowl."
categories:
- Recipe
tags:
- taco
- bowl
katakunci: taco bowl
nutrition: 162 calories
recipecuisine: American
preptime: "PT16M"
cooktime: "PT46M"
recipeyield: "2"
recipecategory: Dessert
---

Hey everyone, it is Jim, welcome to my recipe site. Today, we're going to prepare a special dish, taco bowl. It is one of my favorites. This time, I will make it a bit unique. This will be really delicious.
Taco bowl is one of the most popular of recent trending foods on earth. It's simple, it's fast, it tastes yummy. It's appreciated by millions every day. They're fine and they look fantastic. Taco bowl is something that I've loved my entire life.
At Your Doorstep Faster Than Ever. An easy and simple Taco Bowl Recipe. The bowl is with rice and taco meat (with a homemade seasoning) topped with avocado, tomatoes, cheese, and sour cream. All the taco helpings but served in a bowl - SO GOOD!
To begin with this particular recipe, we have to prepare a few components. You can cook taco bowl using 8 ingredients and 4 steps. Here is how you can achieve it.
<!--inarticleads1-->
##### The ingredients needed to make Taco bowl:
1. Take Ground beef
1. Take Pinto beans
1. Take Lettuce
1. Prepare Tomatoes
1. Make ready Bell peppers
1. Get Cucumbers
1. Take Cheese
1. Get Flour tortillas
My mom made them with ground beef and served them in those crispy taco shells. Taco Tuesday gets expensive, so we like to make taco bowls at home. Whether you're vegan or craving beef, one of these healthy taco bowls will make your night. I've seen some homemade taco bowl (or taco salad shells) methods around the Internets over the years, but this is the only way I've found to make a really huge bowl - a bowl big enough to hold a full salad.
<!--inarticleads2-->
##### Steps to make Taco bowl:
1. Make the ground beef as you do for tacos.
1. I use home cooked pinto beans.
1. Fry flour tortillas in deep oil to bowl shape.
1. Make your own bowl.
Whether you're vegan or craving beef, one of these healthy taco bowls will make your night. I've seen some homemade taco bowl (or taco salad shells) methods around the Internets over the years, but this is the only way I've found to make a really huge bowl - a bowl big enough to hold a full salad. If you're interested, the way to make smaller bowls is just to use the underside of a muffin tin. The first one I want to share is the taco bowl. Because who doesn't love Mexican food, right?
Foods That Make You Happy
In general, people have been trained to think that "comfort" foods are terrible for the body and must be avoided. However, if your comfort food is candy or junk food this holds true. Otherwise, comfort foods may be super healthy and good for you. There are several foods that, when you eat them, may better your mood. If you feel a little bit down and you're needing an emotional pick me up, try some of these.
Eggs, you might be surprised to find out, are great at battling depression. Just see to it that you do not throw out the yolk. When you wish to cheer yourself up, the egg yolk is the most important part of the egg. Eggs, the egg yolks in particular, are high in B vitamins. B vitamins can be great for boosting your mood. This is because they help your neural transmitters--the parts of your brain that dictate your mood--work better. Eat an egg and feel a lot better!
Make a trail mixout of a variety of seeds and nuts. Your mood can be elevated by consuming peanuts, almonds, cashews, sunflower seeds, pumpkin seeds, and other types of nuts. This is because these nuts are high in magnesium, which helps to boost serotonin production. Serotonin is a feel-good substance that directs the brain how to feel at any given moment. The more of it in your brain, the more pleasant you'll feel. Not only that, nuts, particularly, are a fantastic source of protein.
If you would like to beat depression, try consuming some cold water fish. Cold water fish such as tuna, trout and wild salmon are high in DHA and omega-3 fats. These are two things that truly help the grey matter in your brain work a lot better. It's true: consuming a tuna fish sandwich can basically help you fight back depression.
Some grains are actually excellent for repelling bad moods. Barley, quinoa, millet, teff, etc are all excellent for helping you feel happier. These grains fill you up better and that can help improve your moods also. It's not difficult to feel low when you feel famished! The reason these grains are so great for your mood is that they are easy for your stomach to digest. You digest these foods faster than other foods which can help increase your blood sugar levels, which, in turn, helps make you feel better, mood wise.
Green tea is fantastic for moods. You just knew green tea had to be in this article somewhere, right? Green tea is rich in an amino acid referred to as L-theanine. Research has proven that this amino acid promotes the production of brain waves. This helps improve your mental focus while having a relaxing effect on the rest of your body. You knew that green tea helps you be healthier. Now you know that green tea can improve your mood too!
As you can see, you don't need to consume all that junk food when you are wanting to feel better! Test out these hints instead!
|
Python
|
UTF-8
| 1,688 | 2.625 | 3 |
[] |
no_license
|
import struct
from multiprocessing import Process
from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
TAG = "LOGSERVER"
class LogServer(LineReceiver):
log = None
def __init__(self, log):
self.log = log
def connectionMade(self):
self.log.log(TAG, "Connection made")
def connectionLost(self, _):
self.log.log(TAG, "Connection lost")
def lineReceived(self, line):
self.handle_request(line)
def handle_request(self, line):
l = line[0]
data = line[1:]
# Length of the tag is encoded in a single unsigned byte
(tagLength,) = struct.unpack('B', l)
self.log.log(TAG, tagLength)
# Extract the tag and the message
tag = data [:tagLength]
message = data[tagLength:]
# Send it to the log
self.log.log(tag, message)
class LogServerFactory(Factory):
""" Listens for clients and creates vision servers for them when they connect """
def __init__(self, log):
self.log = log
def buildProtocol(self, addr):
return LogServer(self.log)
class LogServerStarter:
def __init__(self, log):
self.l = log
self.lsf = LogServerFactory(log)
def start(self, port):
""" Start the subprocess """
self._subp = Process(target=self._run, args=(port,))
self._subp.start()
def _run(self, port):
""" Run the vision server """
reactor.listenTCP(port, self.lsf)
try:
reactor.run()
except KeyboardInterrupt:
print "VISION: User exited"
self.l.close()
|
Java
|
UTF-8
| 329 | 2.671875 | 3 |
[] |
no_license
|
package initializationAndCleanup.exercise;
/**
* @author Li Yan
*/
public class Exercise10 {
@Override
protected void finalize(){
System.out.println("finalize() called");
}
public static void main(String[] args){
new Exercise10();
System.gc();
System.runFinalization();
}
}
|
SQL
|
UTF-8
| 5,544 | 3.3125 | 3 |
[] |
no_license
|
-- Version "2016-02-17"
-- ...added "BPHRPT:BPH_READ_ROLE" as valid owner-grantee pair
create or replace
procedure fix_access_to_me
( p_schema varchar2, p_read_grantee varchar2 default user,
p_incl_private_synonyms boolean default true,
p_excl_type_list varchar2 default null, p_excl_obj_list varchar2 default null )
is
-- Only "object owners - reader schema" pairs are allowed
-- Example 'OWNERSCH1:ReaderSchA,OWNERSCH1:ReaderSchB,OWNERSCH2:ReaderSchB'
C_ALLOWED_OWNER_READER_PAIRS constant varchar2(4000) :=
'BPHADMIN:BPH_READ_ROLE,BPH:BPH_READ_ROLE,BPHRPT:BPH_READ_ROLE,BPHADMIN:GpeDbRead,SCT03_BPHADMIN:GpeDbRead03,SCT03_BPHADMIN:SCT03_BPH_READ_ROLE,SCT04_BPHADMIN:GpeDbRead04,SCT04_BPHADMIN:SCT04_BPH_READ_ROLE';
l_own_read_pair varchar2(70);
l_access_allowed boolean := false;
l_excls varchar2(4000);
l_obj_sql varchar2(32767) :=
'select object_type, object_name from dba_objects '
||'where owner = '''||upper(p_schema)
||''' and object_type in (''TABLE'',''VIEW'',''MATERIALIZED VIEW'')';
l_object_type varchar2(30);
l_object varchar2(30);
l_ddl varchar2(4000);
l_obj_cnt number := 0;
l_tab_cnt number := 0;
l_view_cnt number := 0;
l_mview_cnt number := 0;
l_cnt number;
l_grantee varchar2(30) := upper(p_read_grantee);
rc_objs sys_refcursor;
--
function itm_cnt(p_str varchar2, p_del varchar2 default ',') return number is
begin
return regexp_count(p_str||p_del,',');
end itm_cnt;
function itm_at(p_str varchar2, p_ix number, p_del varchar2 default ',') return varchar2 is
begin
return regexp_substr(p_str||p_del, '([^'||p_del||']*)'||p_del||'|$', 1, p_ix, NULL, 1);
end itm_at;
procedure log(p_str varchar2) is
begin
dbms_output.put_line(p_str);
end log;
begin --------------------------------------------------------------------------
dbms_output.enable(1000000);
-- First check it the chosen grantee exists
with v_grantees as
(select username g from dba_users union all select role g from dba_roles)
select count(*) into l_cnt from v_grantees where g = l_grantee;
if l_cnt = 0 then
log('The role or user '||l_grantee||' doesn''t exist!');
return;
end if;
-- Then check if acccess to chosen schema is allowed for the chosen grantee
for i in 1..itm_cnt(C_ALLOWED_OWNER_READER_PAIRS) loop
l_own_read_pair := upper( itm_at(C_ALLOWED_OWNER_READER_PAIRS,i) );
l_access_allowed := upper(p_schema)||':'||l_grantee = l_own_read_pair;
exit when l_access_allowed;
end loop;
if NOT l_access_allowed then
log('Granting privileges on objects owned by '||itm_at(p_schema,1,':')||' to '||l_grantee||' NOT allowed using this procedure!');
else -- acces was allowed. DO THE WORK -------------
-- Allowed to fix privs on this requested schema for current user
if p_excl_type_list is not null then
log('Excluding object type(s): '||upper(p_excl_type_list));
l_excls := ''''||replace(upper(p_excl_type_list),',',''',''')||'''';
l_obj_sql := l_obj_sql||' and object_type not in ('||l_excls||')';
end if;
if p_excl_obj_list is not null then
log('Excluding object(s): '||upper(p_excl_obj_list));
l_excls := ''''||replace(upper(p_excl_obj_list),',',''',''')||'''';
l_obj_sql := l_obj_sql||' and object_name not in ('||l_excls||')';
end if;
open rc_objs for l_obj_sql||' order by 1, 2';
fetch rc_objs into l_object_type, l_object;
while rc_objs%FOUND loop
l_obj_cnt := l_obj_cnt + 1;
l_tab_cnt := l_tab_cnt + case when l_object_type = 'TABLE' then 1 else 0 end;
l_view_cnt := l_view_cnt + case when l_object_type = 'VIEW' then 1 else 0 end;
l_mview_cnt := l_mview_cnt + case when l_object_type = 'MATERIALIZED VIEW' then 1 else 0 end;
l_ddl := 'grant select on '||p_schema||'.'||l_object||' to '||l_grantee;
begin
execute immediate l_ddl;
exception
when others then
log('Error granting select on '||p_schema||'.'||l_object||' to '||l_grantee||' ('||SQLERRM||')');
end;
if p_incl_private_synonyms then
l_ddl := 'create or replace synonym '||user||'.'||l_object||' for '||p_schema||'.'||l_object;
begin
execute immediate l_ddl;
exception
when others then
log('Error creating synonym for '||p_schema||'.'||l_object||' in schema '||user);
end;
end if;
fetch rc_objs into l_object_type, l_object;
end loop;
-- Grant the given role to the current user as well (if that hasn't been done already)
if user != l_grantee then -- The grantee is a role
begin
execute immediate 'grant '||l_grantee||' to '||user;
exception
when others then
log('Error granting role '||l_grantee||' to '||user);
end;
end if;
-- Show results
log('Granting select on '||upper(p_schema)||' to '||l_grantee
||case when p_incl_private_synonyms = true then ' and creating synonyms' end
||' succeeded :)' );
log(l_obj_cnt||' objects handled:');
log('...'||l_tab_cnt||' tables');
log('...'||l_view_cnt||' views');
log('...'||l_mview_cnt||' materialized views');
end if;
exception
when others then
log('Unhandled expetion :( '||SQLERRM||' )');
raise_application_error(-20001, 'Unhandled exception :( '||SQLERRM||' )');
end fix_access_to_me;
/
|
Java
|
UTF-8
| 1,634 | 3.03125 | 3 |
[] |
no_license
|
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc=new Scanner(System.in);
Stack<Integer> s=new Stack<Integer>();
Stack<Integer> s1=new Stack<Integer>();
int q,n,q1,q2,q3;
q=sc.nextInt();
while(q!=0){
q1=sc.nextInt();
if(q1==1){
s.push(sc.nextInt());
}
if(q1==2){
if(!s1.isEmpty())
s1.pop();
else{
while(!s.isEmpty())
s1.push(s.pop());
s1.pop();
}
}
if(q1==3){
if(!s1.isEmpty())
System.out.println(s1.peek());
else{
while(!s.isEmpty())
s1.push(s.pop());
System.out.println(s1.peek());
}
}
--q;
}
}
}
|
C
|
GB18030
| 851 | 3.078125 | 3 |
[] |
no_license
|
#ifndef _STDDEF_H
#define _STDDEF_H
#ifndef _PTRDIFF_T
#define _PTRDIFF_T
typedef long ptrdiff_t; /* ָ͡ */
#endif
#ifndef _SIZE_T
#define _SIZE_T
typedef unsigned long size_t; /* sizeof ص͡ */
#endif
#undef NULL
#define NULL ((void *)0) /* ָ롣 */
/* 涨һijԱƫλõĺꡣʹøúȷһԱֶΣ
* ĽṹдӽṹʼֽƫĽΪsize_t
* ʽһ÷(TYPE *)0ǽһ0Ͷ䣨type cast
* ݶָͣȻڸýϽ㡣
*/
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) /* Աеƫλá */
#endif
|
Java
|
UTF-8
| 557 | 1.984375 | 2 |
[
"MIT"
] |
permissive
|
package org.cobraparser.html.renderer;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import org.cobraparser.html.domimpl.ModelNode;
import org.cobraparser.ua.UserAgentContext;
abstract class BaseBlockyRenderable extends BaseElementRenderable {
public BaseBlockyRenderable(RenderableContainer container, ModelNode modelNode, UserAgentContext ucontext) {
super(container, modelNode, ucontext);
}
public abstract void layout(int availWidth, int availHeight, boolean b, boolean c, FloatingBoundsSource source, boolean sizeOnly);
}
|
Python
|
UTF-8
| 1,175 | 2.859375 | 3 |
[] |
no_license
|
__doc__ = """
create a encrypted code for a file
"""
__author__ = "Kai"
__version__ = "v1.1"
from Crypto.Signature import PKCS1_v1_5
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256
import os
def create_digital_signature(key_info, der):
"""
create a digital signature from hashed info
:param key_info
:return:
"""
private_key = _read_key(None, der)
hashed_info = _create_hashed_info(key_info)
signer = PKCS1_v1_5.new(private_key)
signature = signer.sign(hashed_info)
return SHA256.new(signature.hex().encode()).hexdigest()
def _create_hashed_info(key_info):
"""
create hashed info using crypto hashing SHA256 (secure) algorithms
:param key_info: a json file that contains key information on report
:return:
"""
hashed_obj = SHA256.new()
with open(key_info, "rb") as fh:
for line in fh:
hashed_obj.update(line)
return hashed_obj
def _read_key(passphrase, der):
"""
read the private key
:return:
"""
with open(der, 'rb') as fh:
data = fh.read()
private_key = RSA.import_key(data, passphrase=passphrase)
return private_key
|
Markdown
|
UTF-8
| 1,763 | 3.171875 | 3 |
[] |
no_license
|
# My TicketSwap - Robert Langereis
*NOTE THIS PROJECT IS STILL IN DEVELOPMENT*
*We had 5 days to finish this final assignment, building both the frontend and backend (to be found here: https://github.com/robertlangereis/my-ticketswap-backend)*
This is the frontend webapp is a replica of Ticketswap (basic features), by Robert Langereis, as a final (individual) assignment for the Codaisseur Academy. Dev tech used for this client-side webapp:
- React / Redux
- JS/Node (incl. ES6)
- CSS
# Interesting features
* You can register and login as a user
* As a user you can create new events, for which you can add tickets (to be sold - but feature to sell not implemented)
* The most interesting feature was the showing of the "risk of fraud" a certain tickets has when it is on sale. The calculation of the fraud risk is done in the backend (for obvious security reasons) and calculates the following:
1. If the ticket is the only ticket of the author, add 10%
2. if the ticket price is lower than the average ticket price for that event, that's a risk
3. if a ticket is X% cheaper than the average price, add X% to the risk
4. if a ticket is X% more expensive than the average price, deduct X% from the risk, with a maximum of 10% deduction
5. if the ticket was added during business hours (9-17), deduct 10% from the risk, if not, add 10% to the risk
6. if there are >3 comments on the ticket, add 5% to the risk
7. The minimal risk is 5% (there's no such thing as no risk) and the maximum risk is 95%.
# How to run this webapp:
1. Install the dependencies using npm install
2. Use npm run start to start the webapp.
3. NOTE: this requires a working server/backend. For this, see repository: https://github.com/robertlangereis/my-ticketswap-backend
|
Java
|
UTF-8
| 8,701 | 3.265625 | 3 |
[] |
no_license
|
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
/**
* The panel which displays the Julia set and contains all the calculations
* needed to draw it.
* @author Daniel
*
*/
@SuppressWarnings("serial")
public class JuliaPanel extends JPanel{
/**
* The numerical value of each pixel across.
*/
private double pixelValueX;
/**
* The numerical value of each pixel down.
*/
private double pixelValueY;
/**
* The maximum number of iterations to go up to.
*/
private int max;
/**
* The base complex number.
*/
private Complex c;
/**
* The X coordinate of the centre of the screen.
*/
private int middleXCo;
/**
* The Y coordinate of the centre of the screen.
*/
private int middleYCo;
/**
* The buffered image showing the julia set if drawn.
*/
private BufferedImage julia;
/**
* One of five threads which paints a given area of a given buffered image.
*/
private JuliaWorker section1;
/**
* One of five threads which paints a given area of a given buffered image.
*/
private JuliaWorker section2;
/**
* One of five threads which paints a given area of a given buffered image.
*/
private JuliaWorker section3;
/**
* One of five threads which paints a given area of a given buffered image.
*/
private JuliaWorker section4;
/**
* One of five threads which paints a given area of a given buffered image.
*/
private JuliaWorker section5;
/**
* An int representation of the type of fractal formula to be used.
*/
private int fractalType;
/**
* An int representation of the number of threads being used on the buffered
* image. A 0 means single thread, while 1 means multi threads.
*/
private int threadType;
/**
* Creates a JuliaPanel, with default values for the max number
* of iterations and the fractal formula to be used. Sets the base
* complex number to the number given.
*
* @param c The given complex number.
*/
public JuliaPanel(Complex c, int fractalType){
this.c = c;
max = 100;
this.fractalType = fractalType;
}
/**
* Sets the base complex number to the number given.
*
* @param c The given complex number.
*/
public void setC(Complex c){
this.c = c;
}
/**
* Sets the type of fractal formula that should be used on the
* Julia set.
* @param fractalType An int representation of the fractal type.
*/
public void setFractalType(int fractalType){
this.fractalType = fractalType;
}
/**
* Paints the buffered image containing the Julia Set to the screen. First creates the
* buffered image and then once the threads have finished it it's painted to the screen.
*
* @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
*/
protected void paintComponent(Graphics g){
super.paintComponent(g);
int height = this.getHeight();
int width = this.getWidth();
pixelValues(height, width);
julia = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
generate(julia);
g.drawImage(julia, 0, 0, null);
}
/**
* Generates the Julia set buffered image. Will either use one thread for the
* whole image or five threads to each paint a section of the buffered image depending
* on the thread type option. Gives each thread the section of the image for it
* to paint and starts each thread or for single threaded loops over the whole screen
* going down the screen first for each pixel across.
*
* @param julia The buffered image being generated.
*/
private void generate(BufferedImage julia){
int width = this.getWidth()/5;
int height = this.getHeight();
switch(threadType){
case 0:
//loops for every pixel on the screen, going down the screen first for every pixel across
for(int x = 0; x < this.getWidth(); x++){
for(int y = 0; y < this.getHeight(); y++){
int paintColour = juliaIterations(((x-middleXCo)*pixelValueX), ((middleYCo-y)*pixelValueY));
Color myColour = (paintColour==max) ? Color.BLACK : new Color(255, 255-((int) (paintColour*7) % 255), 0);
julia.setRGB(x, y, myColour.getRGB());
}
}
break;
case 1:
section1 = new JuliaWorker(0, width, height);
section1.execute();
section2 = new JuliaWorker(width, width*2, height);
section2.execute();
section3 = new JuliaWorker(width*2, width*3, height);
section3.execute();
section4 = new JuliaWorker(width*3, width*4, height);
section4.execute();
section5 = new JuliaWorker(width*4, this.getWidth(), height);
section5.execute();
//waits until all the threads have finished
while(!(section1.finish && section2.finish && section3.finish && section4.finish && section5.finish)){
}
break;
}
}
/**
* Allows the buffered image of the Julia Set to be accessed.
*
* @return The Julia set buffered image.
*/
public BufferedImage getJulia(){
return julia;
}
/**
* Calculates the value of each pixel in both the x and y axis' and
* calculates the coordinates of the middle of the Panel
*
* @param height The height of the JPanel
* @param width The width of the JPanel
*/
public void pixelValues(int height, int width) {
pixelValueX = 4.0/width;
pixelValueY = 3.2/height;
middleXCo = width / 2 + 1;
middleYCo = height / 2 + 1;
}
/**
* Iterates over the given Complex Number using the formula selected by the switch case
* statement for the correct set until the given number diverges. The number of iterations is kept track of.
*
* @param real The real part of the current Complex Number.
* @param imaginary The imaginary part of the current Complex number.
* @return the number of iterations before complex number diverges.
*/
private int juliaIterations(double real, double imaginary){
Complex previous = new Complex(real, imaginary);
int iterations = 0;
Complex next;
while(previous.modulusSquared()<4 && iterations < max){
switch (fractalType) {
case 0: //ordinary mandelbrot set
next = previous.square().add(c);
break;
case 1: //burning ship set
next = previous.burningShip().add(c);
break;
case 2: //tricorn set
next = previous.triCorn().add(c);
break;
case 3: //multibrot d=3
next = previous.square().multiply(previous).add(c);
break;
case 4: //multibrot d=4
next = previous.square().square().add(c);
break;
case 5: //multibrot d=5
next = previous.square().square().multiply(previous).add(c);
break;
case 6: //multibrot d=6
next = previous.square().square().multiply(previous.square()).add(c);
break;
default:
next = previous.square().add(c);
break;
}
iterations++;
previous = next;
}
return iterations;
}
/**
* Changes the thread option to be used to the given integer.
*
* @param i The thread int representation given.
*/
public void setThread(int i) {
this.threadType = i;
}
/**
* Thread to paint a section of the julia set to the Buffered Image.
*
* @author Daniel
*
*/
@SuppressWarnings("rawtypes")
class JuliaWorker extends SwingWorker{
/**
* The upper x pixel to go up to.
*/
private int limit;
/**
* The height to iterate over.
*/
private int height;
/**
* The lower x pixel to start at.
*/
private int lower;
/**
* Contains whether the thread has finished.
*/
private volatile boolean finish = false;
/**
* The graphics used to colour in the julia set image.
*/
private Graphics2D drawer;
/**
* Creates the thread, and gives the limits of the area it should colour.
*
* @param lower The lower x pixel to start from.
* @param limit The upper x pixel limit to end at.
* @param height The height of the image to paint.
*/
public JuliaWorker(int lower, int limit, int height){
this.limit = limit;
this.height = height;
this.lower = lower;
drawer = julia.createGraphics();
}
/**
* Loops through the section given to colour, calculates the correct colour according
* to the number of iterations, and colours that pixel in. Sets a boolean to true when
* completely finished.
* @see javax.swing.SwingWorker#doInBackground()
*/
@Override
protected Object doInBackground() throws Exception {
for(int x = lower; x < limit; x++){
for(int y = 0; y < height; y++){
int paintColour = juliaIterations(((x-middleXCo)*pixelValueX), ((middleYCo-y)*pixelValueY));
Color myColour = (paintColour==max) ? Color.BLACK : new Color(255, 255-((int) (paintColour*7) % 255), 0);
drawer.setColor(myColour);
drawer.drawLine(x, y, x, y);
}
}
this.finish = true;
return null;
}
}
}
|
Markdown
|
UTF-8
| 19,487 | 3.640625 | 4 |
[] |
no_license
|
#**CS433** 并行与分布式程序设计
#Project2实验报告
**Group16**:秦格华 刘宸林
##1 并行思路
### 1.1 循环并行
在Nbody问题的每一次迭代中,`position_step()`都对每个星体进行了如下的操作: a). 遍历所有星体,计算其他星体对当前星体的引力值; b). 根据所得的引力值,计算当前时间点该星体速度的x和y分量,并且更新该星体的坐标。
可以看出,`position_step()`函数是O(n^2)的。在第一层循环中,对每个星体进行更新;在第二层循环中,利用其他星体的数据来更新该星体受到的引力。
```c
for (i = 0; i < world->num_bodies; i++) {
for (j = 0; j < world->num_bodies; j++) {
...
...
}
}
```
很自然的,我们联想到了OpenMP中提供的循环并行方法,可以直接将该循环拆分之后分散给线程进行运算,从而提高CPU的利用率,以达到加速的效果。
在OpenMP中,语句`#pragma omp parallel for {}`是用来对for痪进行并行处理的。该语句可以自动的将大括号(或者紧跟其后)的for循环语句进行并行处理。
但是,在这里,一共有关于i和关于j的两层循环,而显然,我们只能将其中一层循环并行化。那么,到底应该选择外层循环还是内层循环呢?
### 1.2 选择外层循环并行化的原因
考虑到需要提高对cache的友好度,我们选择并行化外层循环来提高***Temporal Locality***以及***Spatial Locality***。
关于***Temporal Locality***:
由于内层循环的操作从0开始一次访问结构体数组中的成员,我们可以很自然的想到,如果我们将外层循环进行并行化,那么在内层循环中,同一个星体就有可能同时被多个线程访问,这样就显著的提高了***Temporal Locality***。如果我们并行化内层循环,同一个星体需要等到外层循环进行到下一步的时候才能再次被访问,这就有可能造成多余的cache存取操作,从而降低运行速度。
关于
关于***Spatial Locality***:
我们知道,c语言的数组在cache中是行相关的,本次使用的结构体数组也是一样的。所以,为了提高***Spatial Locality***, 我们对内存的访问应该尽量按照行相关的顺序来进行。由于内层循环的访问顺序正好是对数组从前向后依次遍历,所以在不打乱内层循环的前提下,我们对外层循环进行并行处理,并不会违背***Spatial Locality***的原则。同时,如果对内层循环进行并行化,很可能由于线程调度策略选择的问题,导致无法保证以行相关的顺序访问,这样反而会降低cache友好度。
因此,我们在外层循环前加入并行化语句。
```c
#pragma opm parallel for
for (i = 0; i < world->num_bodies; i++) {
for (j = 0; j < world->num_bodies; j++) {
...
...
}
}
```
### 1.3 提高cache友好度
从1.2中我们知道,选择外层循环可以有效提高cache友好度。
再次回到`position_step()`函数,除了计算引力的两层循环,我们还有另外一个循环来对每一个星体进行当前速度以及坐标的计算,该循环如下:
```c
for (i = 0; i < world->num_bodies; i++) {
// Update velocities
......
// Update positions
......
}
```
当然,我们可以再次对于这个循环进行并行化的处理。但是,我们注意到该循环的访问顺序和上一个循环的外层循环是一样的,都是从0开始访问每一个星体,我们考虑到,如果能将这个循环并入上个循环,那么就能保证每个星体在计算引力之后能立即对速度和位置进行更新,从而有效的提高***Temporal Locality***以提高cache友好度。
这显然是很容易办到的,只要将该循环中的操纵放入上一个循环中的内层循环之后,保证在计算了引力之后再对速度和位置进行更新即可,代码如下:
```c
#pragma opm parallel for
for (i = 0; i < world->num_bodies; i++) {
for (j = 0; j < world->num_bodies; j++) {
//Clculate the force
......
}
//Update velocities
......
// Update positions
......
}
```
### 1.4 变量本地化
在并行化时,我们需要考虑变量本地化的问题。由于某些变量是会被每个线程同时写入,这些变量则必须进行本地化的操作。在OpenMP中,我们可以利用`private()`语句来将变量私有化,或者,我们也可以将变量的定义放在并行部分来进行本地化。
加入变量本地化之后的代码如下:
```c
#pragma opm parallel for private(j)
for (i = 0; i < world->num_bodies; i++) {
double d, d_cubed, diff_x, diff_y;
for (j = 0; j < world->num_bodies; j++) {
//Clculate the force
......
}
//Update velocities
......
// Update positions
......
}
```
###1.5 线程调度
`#pragma opm parallel for`语句的默认线程调度方法是***static***的方法,即将循环静态的均分给每一个线程。假如我们有1000次迭代,并且有10个线程对这些迭代进行分配:

这种情况下,每个线程独立的进行自己那部分的迭代,不仅严重的违背了***Spatial Locality***, 同时还可能造成大量的***false sharing***。
为了解决这个问题,我们将采取***Dynamic***的线程调度方法。
在***Dynamic***的调度方法中,并不是预想将迭代任务分配给每个线程,而是在运算的过程中动态的进行分配。例如,首先将迭代1-10分配给线程1-10,接着就等待线程完成任务,如果线程5首先完成了任务,那么就继续将迭代11分配给线程5,以此类推。
可以看出,在***Dynamic***的调度方法中,对内存的访问是严格按照行相关的顺序进行的,也就是说此方法具有良好的***Spatial Locality***。
同时,为了避免***false sharing***,我们可以让每一个线程每次取满一个cache line的容量,这样就能保证线程之间不会发生***false sharing***。
在OpenMP中,可以添加`schedule(dynamic)`语句来更改调度策略,同时,我们还可以设定每次分配给线程的最小迭代次数。假如运行环境的L1 cache line的大小是64byte,而一个double = 8byte,所以我们可以设定每次分配8个迭代给每个线程,即`shcedule(dynamic, 8)`
加入调度策略更改后的程序如下:
```c
#pragma opm parallel for private(j) schedule(dynamic)
for (i = 0; i < world->num_bodies; i++) {
double d, d_cubed, diff_x, diff_y;
for (j = 0; j < world->num_bodies; j++) {
//Clculate the force
......
}
//Update velocities
......
// Update positions
......
}
```
##2 实验数据
在上述并行操作以及cache友好度相关的优化中,我们一共使用了一下操作:
> 1. 外层循环并行化
> 2. 两个循环合并以提高***Spatial Locality***
> 3. 更改线程调度方法为dynamic
在实验中,我们设置的迭代次数为100,星体数目分别为1000、2000、5000,***每个实验结果都是重复进行了三次以上后取平均值得到的***:

可以看出:
* 1. 简单并行的方法得到了非常好的效果,在数据量较大的情况下加速比接近3。
* 2. 循环合并的方法有较微小的提升,意义不大。
* 3. dynamic的线程调度方法反而降低了加速比,可见cache的友好度的提升并不足以抵消dynamic策略本身动态分配任务所消耗的时间。
##Bonus: the Barnes-Hut algorithm
Barnes-Hut算法是快速求解N-body问题的一种有效方法,本算法主要利用了一种新的数据结构Barnes-Hut Tree来实现对区域进行划分。有关Barnes-Hut算法的详细说明在助教给出的参考网站<http://portillo.ca/nbody/barnes-hut/>已经有了非常详细的说明,这里不再赘述,在此仅详细说明并行化思路。
###Data Structure: Barnes-Hut Tree
在实现Barnes-Hut Tree时,我们先将所有的点的值依次加入根节点的值。每当一个点加入一个cell,此cell的中心质量就会被更新,之后的步骤为:
* 1.如果本来这个cell就是空的,那就把这个cell的相关联的点设为此点,并将这个cell的值加一;
* 2.如果本来这个cell里已经有一个点了,那么先为这个cell创建8个child cell,把新加入的这个点和原来在parent cell里的点全部分配在child cell里,并将parent cell里的点的记录删除;
* 3.如果本来这个cell有不止一个点,那么仅需要把新加入的点选取一个child cell加入即可。
```python
class Particle:
//对点的坐标进行初始化
__init__(self, x, y, z, vx, vy, vz, name)
//如果点在soften距离外,则就可以利用cell的中心质量近似计算
kick(self, cell, NEWTON_G, TIMESTEP, SOFTENING)
//对点进行位置的更新
drift(self, TIMESTEP)
```
```python
class Cell:
//对cell的坐标进行初始化
__init__(self, xmin, xmax, ymin, ymax, zmin, zmax, name)
//检查一个点是不是在此cell内
incell(self, x, y, z)
//将一个点加入此cell
add(self, particle)
//为一个cell创建child cell
makedaughters(self)
//为一个cell进行child cell的分配
assigndaughters(self, daughters)
//判断一个cell是不是足够远到可以进行近似计算
meetscriterion(self, particle, TREE_THRES, SOFTENING)
```
(***注:***此部分代码来自助教给出的参考网站<http://portillo.ca/nbody/barnes-hut/>)
初始时对根节点进行处理,这一划分就可以递归进行下去,最后我们就可以生成一棵Barnes-Hut Tree。
###一般并行化思路
* 1.在根进程进行初始化工作
* 2.建立Barnes-Hut Tree;
* 3.根进程将Tree广播给每一个子进程;
* 4.每个子进程负责一部分点,计算这部分点和整个Tree内的其他点的相互作用;
* 5.根进程回收每个子进程计算得出的结果,并利用新的状态更新整棵树上的状态;
* 6.回到步骤2,直至迭代次数达到期望值
可以从上面看出,这一并行化思路实际上并行部分仅存在在每个子进程计算相互作用时,而每一次迭代都需要重新回到串行,由根进程更新整棵树的状态后才可以回到并行状态。另外,由于根进程必须将整棵树都进行广播,并行进程也需要将计算得出的结果(整棵树)发送回根进程,这一过程带来的通信开销一定较大。所以这是一种比较简单的并行化思路。
建树过程:
```python
if self.rank == 0:
root = Cell(-self.box_size, self.box_size, -self.box_size, \
self.box_size, -self.box_size, self.box_size, "0")
for particle in self.particles:
root.add(particle)
```
广播过程:
```python
root = self.comm.bcast(root, root = 0)
```
子进程计算过程:
```python
self.particles = root.particles()
nparticles = len(self.particles) / self.size
extras = len(self.particles) % self.size
if self.rank < extras:
start = self.rank * (nparticles + 1)
end = start + nparticles + 1
else:
start = self.rank * nparticles + extras
end = start + nparticles
myparticles = self.particles[start:end]
for particle in myparticles:
cells = [root]
while cells:
cell = cells.pop()
if cell.meetscriterion(particle, self.tree_thres, self.softening):
if cell.n > 0:
particle.kick(cell, self.newton_g, self.timestep, self.softening)
else:
cells.extend(cell.daughters)
particle.drift(self.timestep)
```
回收过程:
```python
particlelists = self.comm.gather(myparticles, root = 0)
if self.rank == 0:
self.particles = []
for particlelist in particlelists:
self.particles.extend(particlelist)
```
###最终并行化思路
* 1.在根进程进行初始化工作,并直接将每个点的位置、速度信息广播给所有的子进程;
* 2.每个子进程,只进行分到自己的那部分点的建树工作;
* 3.根进程将所有的子进程建的枝进行回收,构成一颗完整的Barnes-Hut Tree;
* 4.根进程将整棵树信息广播出去;
* 5.每个子进程负责一部分点,计算这部分点和整个Tree内的其他点的相互作用;
* 6.子进程直接利用allgather函数收集每个子进程计算出的新的点的信息;
* 7.回到步骤2,直到迭代次数达到期望值
这一并行化思路的主要启发点是allgather函数的特性:
<div align="center">
<img src="2.jpg" width = "200" alt="图片名称" align=center />
</div>
其可以将新的计算结果全部分发给每个进程,从而使建树的工作也可部分并行化,使得整个流程中只有组成整棵树的时候存在串行计算。
各自建树过程:
```python
root = Cell(-self.box_size, self.box_size, -self.box_size, self.box_size, \
-self.box_size, self.box_size, "0")
root.makedaughters()
granddaughters = []
for daughter in root.daughters:
daughter.makedaughters()
granddaughters.extend(daughter.daughters)
subgranddaughters = granddaughters[self.rank::self.size]
for particle in self.particles:
for granddaughter in subgranddaughters:
granddaughter.add(particle)
```
收集树枝建树过程:
```python
granddaughterlists = self.comm.gather(subgranddaughters, root = 0)
if self.rank == 0:
granddaughters = []
for granddaughterlist in granddaughterlists:
granddaughters.extend(granddaughterlist)
root = Cell(-self.box_size, self.box_size, -self.box_size, \
self.box_size, -self.box_size, self.box_size, "0")
root.makedaughters()
for i, daughter in enumerate(root.daughters):
mygranddaughters = granddaughters[i*8:(i+1)*8]
daughter.assigndaughters(mygranddaughters)
root.assigndaughters(root.daughters)
```
广播树(同上,略)
子进程计算过程(同上,略)
更新各点信息:
```python
particlelists = self.comm.allgather(myparticles)
self.particles = []
for particlelist in particlelists:
self.particles.extend(particlelist)
```
###测试结果
运行实例:
<div align="center">
<img src="3.png" width = "350" alt="图片名称" align=center />
</div>
由于我们只在单机(单处理器,4 core)上进行了测试,下面是单机测试的结果(单位:秒):
| #particles | serial(n=2)| basic(n=2)|final(n=2)|
|:------------- |:---------------:| -------------:| -------------:|
| 100 | 7.398730039596558 |5.801186800003052|5.722530841827393|
|500 | 105.86367392539978|66.55828738212585|65.40859770774841|
| #particles |serial(n=4)|basic(n=4)|final(n=4)|
|:------------- |:---------------:| -------------:| -------------:|
| 100 |14.12525486946106 |7.171090841293335|8.555819272994995|
| 500 | 214.0167419910431 |74.87617063522339|83.0267276763916|
下面是加速比结果:
| #particles |serial(n=2)|basic(n=2)|final(n=2)|
|:------------- |:---------------:| -------------:| -------------:|
| 100 |1 |1.27538214070139|1.29291221735625|
| 500 | 1 |1.5905408340454|1.61849783721719|
| #particles | serial(n=4)| basic(n=4)|final(n=4)|
|:------------- |:---------------:| -------------:| -------------:|
| 100 | 1 |1.96974981660022|1.65095292674602|
|500 | 1|2.85827573946957|2.57768489714786|
绘图如下(左边为#particles=100,右边为#particles=500):

###结果分析
首先,对于任意一个并行程序,我们都得到了大于1的加速比。
但是由于程序并不是完全并行的,所以显然无法达到完美加速比。对于n=2时,我们优化后的并行算法要略微比优化前的并行算法的加速比高一些,这符合我们优化的目的。但是对于n=4时,虽然得到的加速比均要高过n=2时的加速比,但令人意外的是出现了优化前算法比优化后算法加速比高的现象。为了解释这一现象,我们对程序运行过程中的各个步骤,按照我们之前对算法流程的分解进行了测时。
下面是n=4时未优化算法的各步骤耗费时间:
```
/****************************************************/
/* Octree Parallel Basic */
/****************************************************/
Tree construction time: 0.6149981021881104 sec
Broadcast time: 3.2539896965026855 sec
Force computation: 2.892432689666748 sec
Gather time: 0.409670352935791 sec
TOTAL = 7.171090841293335 sec
```
下面是优化后各步骤耗费时间:
```
/****************************************************/
/* Octree Parallel Tree */
/****************************************************/
Tree construction time: 0.2001333236694336 sec
Tree assembly time: 1.1009385585784912 sec
Broadcast time: 3.0562713146209717 sec
Force computation: 3.4207682609558105 sec
Allgather time: 0.7777078151702881 sec
TOTAL = 8.555819272994995s
```
对比上面两组数据可以看出,对于优化后的代码,虽然由于建树操作的一部分分配给了子进程,但是由于子进程需要建好自己的枝后再发送给根进程组装,所以这一组装的时间再加上通信的时间实际上一定程度上延长了建树操作的时间。另外,`Allgather`操作相比较`gather`操作要进行的复制等操作数更多,所以这一时间也会增加。最后造成优化后算法性能反而下降的现象。
但是对于n=2的情况,由于只存在两个并行进程,通信操作和收发操作的对象都比较少,所以在这样的情况下优化后的算法加速比的确会比优化前算法高。
####关于python并行的问题
在看到网站提供的python版的并行代码,我产生了一点疑惑:对于解释型语言(例如python,perl,PHP等),一般而言是不支持多线程的,而python比较独特地有支持多线程的机制。于是我们在网上去找到了这样一段话:
>但是实际上,在python的原始解释器CPython中存在着GIL(Global Interpreter Lock,全局解释器>锁),因此在解释执行python代码时,会产生互斥锁来限制线程对共享资源的访问,直到解释器遇到I/O操作或者操作次数达到一定数目时才会释放GIL。
>所以,虽然CPython的线程库直接封装了系统的原生线程,但CPython整体作为一个进程,同一时间只会有一个获得GIL的线程在跑,其他线程则处于等待状态。这就造成了即使在多核CPU中,多线程也只是做着分时切换而已。
>
>————知乎用户 万齐飞
所以说如果用python来实现多线程计算的话,很有可能多线程的程序还会产生负的加速比。所以对于本项目来说,基于Python和thread的并行尝试并不值得采用。但是对于MPI for Python来说,并不是线程并行的,而是多进程并行,所以我们在OpenMPI+Python的平台下进行并行加速是没有任何问题,得到的结果也说明了这一点。
|
Java
|
UTF-8
| 211 | 1.726563 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.github.chuross.recyclerviewadapters.internal;
import android.view.View;
import androidx.annotation.NonNull;
public interface EventExecutor {
void execute(@NonNull View view, int position);
}
|
Java
|
UTF-8
| 2,236 | 2.34375 | 2 |
[] |
no_license
|
package com.example.victorvela.isafeeducationnovo.activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.example.victorvela.isafeeducationnovo.R;
import com.example.victorvela.isafeeducationnovo.model.Administrador;
import com.example.victorvela.isafeeducationnovo.repository.AdministradorRepository;
import com.example.victorvela.isafeeducationnovo.repository.Repository;
public class AdministradorCadastroActivity extends AppCompatActivity {
private EditText editNomeAdministrador, editSenhaAdministrador;
private Repository repository;
private Administrador administrador;
private AdministradorRepository administradorRepository;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_administrador_cadastro);
/**
* receber nome e senha da tela de cadastro
*/
editNomeAdministrador = findViewById(R.id.edit_nomeDisciplina);
editSenhaAdministrador = findViewById(R.id.edit_senhaAdministrador);
administrador = new Administrador();
administradorRepository = new AdministradorRepository(getApplicationContext());
}
public void salvarAdministrador(View view){
administrador.setNomeAdministrador(editNomeAdministrador.getText().toString());
administrador.setSenhaAdministrador(editSenhaAdministrador.getText().toString());
//neste momento fazenmos uma chamada do repository que por fim chama o repository do administrador executando o insert
administradorRepository.insert(administrador);
Toast.makeText(this, "inserido com sucesso", Toast.LENGTH_SHORT).show();
finish();
}
public void teste(View view){
administrador.setNomeAdministrador(editNomeAdministrador.getText().toString());
administrador.setSenhaAdministrador(editSenhaAdministrador.getText().toString());
Toast.makeText(this, administrador.getId() + " " + administrador.getNomeAdministrador() + " " + administrador.getSenhaAdministrador(), Toast.LENGTH_SHORT).show();
}
}
|
Markdown
|
UTF-8
| 1,782 | 2.859375 | 3 |
[
"Apache-2.0"
] |
permissive
|
---
layout: post
title: 一天一组Linux命令(文件查询):whiereis
category: linux
tags: linux
keywords: linux whiereis
excerpt: "whereis 命令用于查找特定的文件,whereis 查找的速度非常快。"
---
## 目录
### 简述
whereis 命令用于查找特定的文件,whereis 查找的速度非常快。
### whereis 命令的使用
`whereis [-bmsu] 文件或目录名`
选项与参数:
-b:定位可执行文件
-m:定位帮助文件
-s:定位源代码文件
-u:搜索默认路径下除可执行文件、源代码文件、帮助文件以外的其它文件
### 使用实例
1. whereis php 将于php相关的文件都查找出来
```
[baihe@application_server ~]$ whereis php
php: /usr/local/bin/php /usr/local/etc/php.ini /usr/local/php /usr/local/php-7.2.2/bin/php
```
2. whereis -b php 只将二进制文件 查找出来
```
[baihe@application_server ~]$ whereis -b php
php: /usr/local/bin/php /usr/local/etc/php.ini /usr/local/php /usr/local/php-7.2.2/bin/php
```
3. whereis -m php 查出说明文档路径
4. whereis -s php 找source源文件。
### 扩展说明
1. 相比于类型 find 查找文件命令为什么查询快?
和 find 相比,whereis 查找的速度非常快,这是因为 linux 系统会将 系统内的所有文件都记录在一个数据库文件中,当使用 whereis 和下面即将介绍的 locate 时,会从数据库中查找数据,而不是像 find命令那样,通过遍历硬盘来查找,效率自然会很高。
但是该数据库文件并不是实时更新,默认情况下时一星期更新一次,因此,我们在用whereis和locate 查找文件时,有时会找到已经被删除的数据,或者刚刚建立文件,却无法查找到,原因就是因为数据库文件没有被更新。
|
Swift
|
UTF-8
| 4,072 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
//
// LocalBaseController.swift
// eMia
//
// Created by Sergey Krotkih on 17/08/2018.
// Copyright © 2018 Sergey Krotkih. All rights reserved.
//
import Foundation
import RealmSwift
import RxSwift
import RxRealm
class LocalBaseController {
var isDataBaseFetched: Bool {
return self.posts.count > 0
}
// MARK: Users
var users: [UserModel] {
return getAllData()
}
func addUser(_ item: UserItem) {
let model = UserModel(item: item)
guard model.userId.isEmpty == false else {
return
}
create(model: model)
}
func deleteUser(_ item: UserItem) {
if let model = getUser(for: item) {
Realm.delete(model: model)
}
}
func editUser(_ item: UserItem) {
self.addUser(item)
}
// MARK: Post
var posts: [PostModel] {
return getAllData()
}
func addPost(_ item: PostItem) {
let model = PostModel(item: item)
guard let modelId = model.id, modelId.isEmpty == false else {
return
}
create(model: model)
}
func deletePost(_ item: PostItem) {
if let model = getPost(for: item) {
Realm.delete(model: model)
}
}
func editPost(_ item: PostItem) {
addPost(item)
}
private func postsObservable() -> Observable<Results<PostModel>> {
let result = Realm.withRealm("getting posts") { realm -> Observable<Results<PostModel>> in
let realm = try Realm()
let posts = realm.objects(PostModel.self)
return Observable.collection(from: posts)
}
return result ?? .empty()
}
// MARK: Comments
func addComment(_ item: CommentItem) {
guard item.id.isEmpty == false else {
return
}
let model = CommentModel(item: item)
create(model: model)
}
func deleteComment(_ item: CommentItem) {
if let model = getComment(for: item) {
Realm.delete(model: model)
}
}
func editComment(_ item: CommentItem) {
addComment(item)
}
// MARK: Favorities
var favorities: [FavoriteModel] {
return getAllData()
}
func addFavorite(_ item: FavoriteItem) {
guard item.id.isEmpty == false else {
return
}
let model = FavoriteModel(item: item)
create(model: model)
}
func deleteFavorite(_ item: FavoriteItem) {
if let model = getFavorite(for: item) {
Realm.delete(model: model)
}
}
func editFavorite(_ item: FavoriteItem) {
addFavorite(item)
}
}
// MARK: - Private Methods
extension LocalBaseController {
private func getAllData<T: Object>() -> [T] {
do {
let realm = try Realm()
let results = realm.objects(T.self)
return results.toArray()
} catch let err {
print("Failed read realm user data with error: \(err)")
return []
}
}
private func create<T: Object>(model: T) {
_ = Realm.create(model: model).asObservable().subscribe(onNext: { _ in
}, onError: { error in
Alert.default.showError(message: error.localizedDescription)
})
}
// MARK: Get Object
private func getUser(for item: UserItem) -> UserModel? {
let filter = "userId = '\(item.userId)'"
return getObject(with: filter)
}
private func getFavorite(for item: FavoriteItem) -> FavoriteModel? {
let filter = "postid = '\(item.postid)' AND uid = '\(item.uid)'"
return getObject(with: filter)
}
private func getComment(for item: CommentItem) -> CommentModel? {
let filter = "id = '\(item.id)'"
return getObject(with: filter)
}
private func getPost(for item: PostItem) -> PostModel? {
let filter = "id = '\(item.id)'"
return getObject(with: filter)
}
private func getObject<T: Object>(with filter: String) -> T? {
do {
let realm = try Realm()
let data = realm.objects(T.self).filter(filter)
return data.first
} catch _ {
return nil
}
}
}
|
C++
|
UTF-8
| 1,017 | 3.265625 | 3 |
[] |
no_license
|
/*
* 94. Binary Tree Inorder Traversal
*/
#include "common.h"
#include <vector>
#include <stack>
using namespace std;
#if LEET_CODE == 94
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode* > st;
TreeNode *p = root;
if (root == NULL)
return res;
do {
while (p != NULL) {
st.push(p);
p = p->left;
}
p = st.top(); st.pop();
res.push_back(p->val);
p = p->right;
} while (!st.empty() || p != NULL);
return res;
}
private:
void inorder(TreeNode* root, vector<int> &res) {
if (root == NULL) return ;
inorder(root->left, res);
res.push_back(root->val);
inorder(root->right, res);
}
};
int main()
{
}
#endif
|
Java
|
UTF-8
| 814 | 2.203125 | 2 |
[] |
no_license
|
package com.init.mascotas.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import com.init.mascotas.entities.Animal;
import com.init.mascotas.entities.Producto;
public interface ProductoRepository extends JpaRepository<Producto, Integer>{
@Query(value = "SELECT * FROM PRODUCTO p WHERE (:categoria is null or p.categoria LIKE :categoria)"
+ "AND (:tipoAnimal is null or p.TIPOANIMAL LIKE :tipoAnimal) "
+ "ORDER BY p.tipoAnimal", nativeQuery = true)
List<Producto> findProductoFiltrado(String categoria, String tipoAnimal);
@Query(value= "SELECT max(ID_PRODUCTO) FROM PRODUCTO", nativeQuery = true)
Integer obtenerUltimoIdPedido();
}
|
PHP
|
UTF-8
| 597 | 3.234375 | 3 |
[] |
no_license
|
<!DOCTYPE html>
<html>
<head>
</title>
</head>
<body>
<form action= “site.php” method=”post”>
<input type= “text” name= “student”>
<input type= “submit”>
</form>
<?php
$grades=array("Jim"=>"A+", "Pam"=> "B+", "Oscar”=>“C+”);
echo $grades["Jim"];//prints out A+
//We access Array elements using a key in an associate array
//e.g. Jim is a key, Oscar is a key and Pam is a key.
echo $grades[$_POST["student"]];
?>
</body>
</html>
|
PHP
|
UTF-8
| 2,200 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace RusaDrako\telegram_bot_engine\object;
/**
* Этот объект представляет бота или пользователя Telegram.
*/
class WebhookInfo extends _object_object {
/** https://core.telegram.org/bots/api#chat */
protected function add_setting() {
$this->set('url', 'str'); # URL-адрес веб-перехватчика, может быть пустым, если веб-перехватчик не настроен
$this->set('has_custom_certificate', 'bool'); # True, если для проверки сертификата веб-перехватчика был предоставлен настраиваемый сертификат
$this->set('pending_update_count', 'int'); # Целое число Количество обновлений, ожидающих доставки
$this->set('ip_address', 'int'); # Опционально. Текущий IP-адрес веб-перехватчика
$this->set('last_error_date', 'date'); # Опционально. Время Unix для самой последней ошибки, которая произошла при попытке доставить обновление через веб-перехватчик
$this->set('last_error_message', 'str'); # Опционально. Сообщение об ошибке в удобочитаемом формате для самой последней ошибки, которая произошла при попытке доставить обновление через веб-перехватчик
$this->set('max_connections', 'int'); # Опционально. Максимально допустимое количество одновременных HTTPS-подключений к веб-перехватчику для доставки обновлений
$this->set('allowed_updates', 'def'); # Опционально. Список типов обновлений, на которые подписан бот. По умолчанию для всех типов обновлений, кроме chat_member
}
/**/
}
|
C++
|
UTF-8
| 625 | 3.046875 | 3 |
[] |
no_license
|
// https://www.cnblogs.com/zzhzz/p/5837815.html
#include <iostream>
using namespace std;
int a[21] = {0};
int main() {
int t;
while(cin >> t) {
while (t--) {
int n;
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> a[i];
int j = i - 1;
// 必须让左括号的个数和右括号匹配 i - j为右括号个数,a[i]-a[j]为左括号个数
while (a[i] - a[j] < i - j) {
j--;
}
cout << i - j << " ";
}
cout << endl;
}
}
}
|
C++
|
UTF-8
| 942 | 2.765625 | 3 |
[] |
no_license
|
//ABC085C - Otoshidama
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
std::vector<int> ktbl = {1000,5000,10000};//小さい順
std::vector<int> ans;
int make_sum(int rest,int uidx, int num){
int cnt=0;
if (rest == 0)
{
if ((ans[0]+ans[1]+ans[2]) == num){
cout << ans[2] << " " << ans[1] << " " << ans[0] << endl;
exit;
return 1;
}
}
else
{
for (int i = uidx; i >= 0; i--)
{
if (rest >= ktbl[i])
{
++ans[i];
cnt += make_sum(rest-ktbl[i], i,num);
if (cnt > 0) { return cnt; }//みつかったら終わり
--ans[i];
}
}
}
return cnt;
}
int main(){
int n, y;
cin>>n;
cin>>y;
ans.resize(ktbl.size(),0);
int cnt = make_sum(y,ktbl.size()-1,n);
if (cnt == 0) cout<<"-1 -1 -1" <<endl;
return 0;
}
|
C
|
UTF-8
| 3,905 | 3.5625 | 4 |
[] |
no_license
|
#include "SafeRead.h"
int readInt(const char *prompt, int min, int max) {
while (1) {
printf("%s ", prompt);
char str[16];
fgets(str, sizeof(str), stdin);
if (strchr(str, '\n') == NULL) {
int c;
bool flag = true;
while ((c = fgetc(stdin)) != '\n' && c != EOF) {
if (!isspace(c)) {
flag = false;
}
}
if (flag == false) {
printf("Введенная строка превышает допустимый размер\n");
continue;
}
}
char *endptr = NULL;
errno = 0;
int n = (int) strtol(str, &endptr, 10);
int tmp = errno;
if (tmp == ERANGE) {
printf("Переполнение\n");
continue;
}
if (endptr == str) {
printf("Не удалось применить преобразование\n");
continue;
}
bool correct = true;
for (char *p = endptr; *p != '\0'; ++p) {
if (!isspace((int) *p)) {
correct = false;
break;
}
}
if (correct == false) {
printf("Некорректная строка\n");
continue;
}
if (n > max || n < min) {
printf("Допустимый диапазон от %d до %d\n", min, max);
continue;
}
return n;
}
}
double readDouble(const char *prompt, double min, double max) {
while (1) {
printf("%s ", prompt);
char str[32];
fgets(str, sizeof(str), stdin);
if (strchr(str, '\n') == NULL) {
int c;
bool flag = true;
while ((c = fgetc(stdin)) != '\n' && c != EOF) {
if (!isspace(c)) {
flag = false;
}
}
if (flag == false) {
printf("Введенная строка превышает допустимый размер\n");
continue;
}
}
char *endptr = NULL;
errno = 0;
double n = strtod(str, &endptr);
int tmp = errno;
if (tmp == ERANGE) {
printf("Переполнение\n");
continue;
}
if (endptr == str) {
printf("Не удалось применить преобразование\n");
continue;
}
bool correct = true;
for (char *p = endptr; *p; ++p) {
if (!isspace((int) *p)) {
correct = false;
break;
}
}
if (correct == false) {
printf("Некорректная строка\n");
continue;
}
if (n > max || n < min) {
printf("Допустимый диапазон от %f до %f\n", min, max);
continue;
}
return n;
}
}
char *readStr(const char *prompt) {
printf("%s", prompt);
size_t size = 0;
size_t capacity = 16;
char *str = malloc(capacity);
if (str == NULL) {
int c;
while ((c = fgetc(stdin)) != '\n' && c != EOF);
printf("Не удалось выделить требуемый блок памяти");
return NULL;
}
int ch;
while ((ch = fgetc(stdin)) != '\n' && ch != EOF) {
if (size == capacity - 1) {
capacity += 16;
char *tmp = str;
str = (char *) realloc(str, capacity);
if (str == NULL) {
printf("Не удалось выделить требуемый блок памяти");
free(tmp);
return NULL;
}
}
str[size] = (char) ch;
size++;
}
str[size] = '\0';
return str;
}
|
TypeScript
|
UTF-8
| 18,908 | 2.6875 | 3 |
[
"Apache-2.0"
] |
permissive
|
import {
decodeERC1155AssetData,
decodeERC721AssetData,
decodeMultiAssetData,
ERC1155ProxyWrapper,
ERC20Wrapper,
ERC721Wrapper,
getAssetDataProxyId,
} from '@0x/contracts-asset-proxy';
import { AbstractAssetWrapper, constants } from '@0x/contracts-test-utils';
import { AssetProxyId } from '@0x/types';
import { BigNumber, errorUtils } from '@0x/utils';
import * as _ from 'lodash';
interface ProxyIdToAssetWrappers {
[proxyId: string]: AbstractAssetWrapper;
}
const ONE_NFT_UNIT = new BigNumber(1);
const ZERO_NFT_UNIT = new BigNumber(0);
/**
* This class abstracts away the differences between ERC20 and ERC721 tokens so that
* the logic that uses it does not need to care what standard a token belongs to.
*/
export class AssetWrapper {
private readonly _proxyIdToAssetWrappers: ProxyIdToAssetWrappers;
constructor(assetWrappers: AbstractAssetWrapper[], private readonly _burnerAddress: string) {
this._proxyIdToAssetWrappers = {};
_.each(assetWrappers, assetWrapper => {
const proxyId = assetWrapper.getProxyId();
this._proxyIdToAssetWrappers[proxyId] = assetWrapper;
});
}
public async getBalanceAsync(userAddress: string, assetData: string): Promise<BigNumber> {
const proxyId = getAssetDataProxyId(assetData);
switch (proxyId) {
case AssetProxyId.ERC20: {
// tslint:disable-next-line:no-unnecessary-type-assertion
const erc20Wrapper = this._proxyIdToAssetWrappers[proxyId] as ERC20Wrapper;
const balance = await erc20Wrapper.getBalanceAsync(userAddress, assetData);
return balance;
}
case AssetProxyId.ERC721: {
// tslint:disable-next-line:no-unnecessary-type-assertion
const assetWrapper = this._proxyIdToAssetWrappers[proxyId] as ERC721Wrapper;
// tslint:disable-next-line:no-unused-variable
const [tokenAddress, tokenId] = decodeERC721AssetData(assetData);
const isOwner = await assetWrapper.isOwnerAsync(userAddress, tokenAddress, tokenId);
const balance = isOwner ? ONE_NFT_UNIT : ZERO_NFT_UNIT;
return balance;
}
case AssetProxyId.ERC1155: {
// tslint:disable-next-line:no-unnecessary-type-assertion
const assetProxyWrapper = this._proxyIdToAssetWrappers[proxyId] as ERC1155ProxyWrapper;
const [
// tslint:disable-next-line:no-unused-variable
tokenAddress,
tokenIds,
] = decodeERC1155AssetData(assetData);
const assetWrapper = assetProxyWrapper.getContractWrapper(tokenAddress);
const balances = await Promise.all(
_.map(tokenIds).map(tokenId => assetWrapper.getBalanceAsync(userAddress, tokenId)),
);
return BigNumber.min(...balances);
}
case AssetProxyId.MultiAsset: {
// tslint:disable-next-line:no-unused-variable
const [amounts, nestedAssetData] = decodeMultiAssetData(assetData);
const nestedBalances = await Promise.all(
nestedAssetData.map(async _nestedAssetData => this.getBalanceAsync(userAddress, _nestedAssetData)),
);
const scaledBalances = _.zip(amounts, nestedBalances).map(([amount, balance]) =>
(balance as BigNumber).div(amount as BigNumber).integerValue(BigNumber.ROUND_HALF_UP),
);
return BigNumber.min(...scaledBalances);
}
default:
throw errorUtils.spawnSwitchErr('proxyId', proxyId);
}
}
public async setBalanceAsync(userAddress: string, assetData: string, desiredBalance: BigNumber): Promise<void> {
const proxyId = getAssetDataProxyId(assetData);
switch (proxyId) {
case AssetProxyId.ERC20: {
// tslint:disable-next-line:no-unnecessary-type-assertion
const erc20Wrapper = this._proxyIdToAssetWrappers[proxyId] as ERC20Wrapper;
await erc20Wrapper.setBalanceAsync(
userAddress,
assetData,
desiredBalance.integerValue(BigNumber.ROUND_DOWN),
);
return;
}
case AssetProxyId.ERC721: {
// tslint:disable-next-line:no-unnecessary-type-assertion
const erc721Wrapper = this._proxyIdToAssetWrappers[proxyId] as ERC721Wrapper;
// tslint:disable-next-line:no-unused-variable
const [tokenAddress, tokenId] = decodeERC721AssetData(assetData);
const doesTokenExist = erc721Wrapper.doesTokenExistAsync(tokenAddress, tokenId);
if (!doesTokenExist && desiredBalance.gte(1)) {
await erc721Wrapper.mintAsync(tokenAddress, tokenId, userAddress);
return;
} else if (!doesTokenExist && desiredBalance.lt(1)) {
return; // noop
}
const tokenOwner = await erc721Wrapper.ownerOfAsync(tokenAddress, tokenId);
if (userAddress !== tokenOwner && desiredBalance.gte(1)) {
await erc721Wrapper.transferFromAsync(tokenAddress, tokenId, tokenOwner, userAddress);
} else if (tokenOwner === userAddress && desiredBalance.lt(1)) {
// Burn token
await erc721Wrapper.transferFromAsync(tokenAddress, tokenId, tokenOwner, this._burnerAddress);
return;
} else if (
(userAddress !== tokenOwner && desiredBalance.lt(1)) ||
(tokenOwner === userAddress && desiredBalance.gte(1))
) {
return; // noop
}
break;
}
case AssetProxyId.ERC1155: {
// tslint:disable-next-line:no-unnecessary-type-assertion
const assetProxyWrapper = this._proxyIdToAssetWrappers[proxyId] as ERC1155ProxyWrapper;
const [
// tslint:disable-next-line:no-unused-variable
tokenAddress,
tokenIds,
tokenValues,
] = decodeERC1155AssetData(assetData);
const assetWrapper = assetProxyWrapper.getContractWrapper(tokenAddress);
const tokenValuesSum = BigNumber.sum(...tokenValues);
let tokenValueRatios = tokenValues;
if (!tokenValuesSum.eq(0)) {
tokenValueRatios = tokenValues.map(v => v.div(tokenValuesSum));
}
for (const i of _.times(tokenIds.length)) {
const tokenId = tokenIds[i];
const tokenValueRatio = tokenValueRatios[i];
const scaledDesiredBalance = desiredBalance.times(tokenValueRatio);
const isFungible = await assetWrapper.isFungibleItemAsync(tokenId);
if (isFungible) {
// Token is fungible.
const currentBalance = await assetWrapper.getBalanceAsync(userAddress, tokenId);
const difference = scaledDesiredBalance
.minus(currentBalance)
.integerValue(BigNumber.ROUND_DOWN);
if (difference.eq(0)) {
// Just right. Nothing to do.
} else if (difference.lt(0)) {
// Too much. Burn some tokens.
await assetWrapper.safeTransferFromAsync(
userAddress,
this._burnerAddress,
tokenId,
difference.abs(),
);
} else {
// difference.gt(0)
// Too little. Mint some tokens.
await assetWrapper.mintKnownFungibleTokensAsync(tokenId, [userAddress], [difference]);
}
} else {
const nftOwner = await assetWrapper.getOwnerOfAsync(tokenId);
if (scaledDesiredBalance.gte(1)) {
if (nftOwner === userAddress) {
// Nothing to do.
} else if (nftOwner !== constants.NULL_ADDRESS) {
// Transfer from current owner.
await assetWrapper.safeTransferFromAsync(nftOwner, userAddress, tokenId, ONE_NFT_UNIT);
} else {
throw new Error(`Cannot mint new ERC1155 tokens with a specific token ID.`);
}
} else {
if (nftOwner === userAddress) {
// Burn the token.
await assetWrapper.safeTransferFromAsync(
userAddress,
this._burnerAddress,
tokenId,
ONE_NFT_UNIT,
);
} else {
// Nothing to do.
}
}
}
}
break;
}
case AssetProxyId.MultiAsset: {
// tslint:disable-next-line:no-unused-variable
const [amounts, nestedAssetData] = decodeMultiAssetData(assetData);
const amountsSum = BigNumber.sum(...amounts);
let assetAmountRatios = amounts;
if (!amountsSum.eq(0)) {
assetAmountRatios = amounts.map(amt => amt.div(amountsSum));
}
for (const i of _.times(amounts.length)) {
const assetAmountRatio = assetAmountRatios[i];
await this.setBalanceAsync(userAddress, nestedAssetData[i], desiredBalance.times(assetAmountRatio));
}
break;
}
default:
throw errorUtils.spawnSwitchErr('proxyId', proxyId);
}
}
public async setUnscaledBalanceAsync(
userAddress: string,
assetData: string,
desiredBalance: BigNumber,
): Promise<void> {
const proxyId = getAssetDataProxyId(assetData);
switch (proxyId) {
case AssetProxyId.ERC20:
case AssetProxyId.ERC721:
return this.setBalanceAsync(userAddress, assetData, desiredBalance);
case AssetProxyId.ERC1155:
case AssetProxyId.MultiAsset: {
const currentBalance = await this.getBalanceAsync(userAddress, assetData);
return this.setBalanceAsync(userAddress, assetData, desiredBalance.times(currentBalance));
}
default:
throw errorUtils.spawnSwitchErr('proxyId', proxyId);
}
}
public async getProxyAllowanceAsync(userAddress: string, assetData: string): Promise<BigNumber> {
const proxyId = getAssetDataProxyId(assetData);
switch (proxyId) {
case AssetProxyId.ERC20: {
// tslint:disable-next-line:no-unnecessary-type-assertion
const erc20Wrapper = this._proxyIdToAssetWrappers[proxyId] as ERC20Wrapper;
const allowance = await erc20Wrapper.getProxyAllowanceAsync(userAddress, assetData);
return allowance;
}
case AssetProxyId.ERC721: {
// tslint:disable-next-line:no-unnecessary-type-assertion
const assetWrapper = this._proxyIdToAssetWrappers[proxyId] as ERC721Wrapper;
// tslint:disable-next-line:no-unused-variable
const [tokenAddress, tokenId] = decodeERC721AssetData(assetData);
const isProxyApprovedForAll = await assetWrapper.isProxyApprovedForAllAsync(userAddress, tokenAddress);
if (isProxyApprovedForAll) {
return constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS;
}
const isProxyApproved = await assetWrapper.isProxyApprovedAsync(tokenAddress, tokenId);
const allowance = isProxyApproved ? ONE_NFT_UNIT : ZERO_NFT_UNIT;
return allowance;
}
case AssetProxyId.ERC1155: {
// tslint:disable-next-line:no-unnecessary-type-assertion
const assetProxyWrapper = this._proxyIdToAssetWrappers[proxyId] as ERC1155ProxyWrapper;
// tslint:disable-next-line:no-unused-variable
const [tokenAddress] = decodeERC1155AssetData(assetData);
const isApprovedForAll = await assetProxyWrapper.isProxyApprovedForAllAsync(userAddress, tokenAddress);
if (!isApprovedForAll) {
// ERC1155 is all or nothing.
return constants.ZERO_AMOUNT;
}
return constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS;
}
case AssetProxyId.MultiAsset: {
// tslint:disable-next-line:no-unused-variable
const [amounts, nestedAssetData] = decodeMultiAssetData(assetData);
const allowances = await Promise.all(
nestedAssetData.map(async _nestedAssetData =>
this.getProxyAllowanceAsync(userAddress, _nestedAssetData),
),
);
return BigNumber.min(...allowances);
}
default:
throw errorUtils.spawnSwitchErr('proxyId', proxyId);
}
}
public async setProxyAllowanceAsync(
userAddress: string,
assetData: string,
desiredAllowance: BigNumber,
): Promise<void> {
const proxyId = getAssetDataProxyId(assetData);
switch (proxyId) {
case AssetProxyId.ERC20: {
// tslint:disable-next-line:no-unnecessary-type-assertion
const erc20Wrapper = this._proxyIdToAssetWrappers[proxyId] as ERC20Wrapper;
await erc20Wrapper.setAllowanceAsync(userAddress, assetData, desiredAllowance);
return;
}
case AssetProxyId.ERC721: {
if (
!desiredAllowance.eq(0) &&
!desiredAllowance.eq(1) &&
!desiredAllowance.eq(constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS)
) {
throw new Error(
`Allowance for ERC721 token can only be set to 0, 1 or 2^256-1. Got: ${desiredAllowance}`,
);
}
// tslint:disable-next-line:no-unnecessary-type-assertion
const erc721Wrapper = this._proxyIdToAssetWrappers[proxyId] as ERC721Wrapper;
// tslint:disable-next-line:no-unused-variable
const [tokenAddress, tokenId] = decodeERC721AssetData(assetData);
const doesTokenExist = await erc721Wrapper.doesTokenExistAsync(tokenAddress, tokenId);
if (!doesTokenExist) {
throw new Error(`Cannot setProxyAllowance on non-existent token: ${tokenAddress} ${tokenId}`);
}
const isProxyApprovedForAll = await erc721Wrapper.isProxyApprovedForAllAsync(userAddress, tokenAddress);
if (!isProxyApprovedForAll && desiredAllowance.eq(constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS)) {
const isApproved = true;
await erc721Wrapper.approveProxyForAllAsync(tokenAddress, userAddress, isApproved);
} else if (isProxyApprovedForAll && desiredAllowance.eq(0)) {
const isApproved = false;
await erc721Wrapper.approveProxyForAllAsync(tokenAddress, userAddress, isApproved);
} else if (isProxyApprovedForAll && desiredAllowance.eq(constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS)) {
return; // Noop
}
const isProxyApproved = await erc721Wrapper.isProxyApprovedAsync(tokenAddress, tokenId);
if (!isProxyApproved && desiredAllowance.eq(1)) {
await erc721Wrapper.approveProxyAsync(tokenAddress, tokenId);
} else if (isProxyApproved && desiredAllowance.eq(0)) {
// Remove approval
await erc721Wrapper.approveAsync(constants.NULL_ADDRESS, tokenAddress, tokenId);
} else if (
(!isProxyApproved && desiredAllowance.eq(0)) ||
(isProxyApproved && desiredAllowance.eq(1))
) {
// noop
}
break;
}
case AssetProxyId.ERC1155: {
// tslint:disable-next-line:no-unnecessary-type-assertion
const assetProxyWrapper = this._proxyIdToAssetWrappers[proxyId] as ERC1155ProxyWrapper;
// tslint:disable-next-line:no-unused-variable
const [tokenAddress] = decodeERC1155AssetData(assetData);
// ERC1155 allowances are all or nothing.
const shouldApprovedForAll = desiredAllowance.gt(0);
const currentAllowance = await this.getProxyAllowanceAsync(userAddress, assetData);
if (shouldApprovedForAll && currentAllowance.eq(constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS)) {
// Nothing to do.
} else if (!shouldApprovedForAll && currentAllowance.eq(constants.ZERO_AMOUNT)) {
// Nothing to do.
} else {
assetProxyWrapper.setProxyAllowanceForAllAsync(userAddress, tokenAddress, shouldApprovedForAll);
}
break;
}
case AssetProxyId.MultiAsset: {
// tslint:disable-next-line:no-unused-variable
const [amounts, nestedAssetData] = decodeMultiAssetData(assetData);
await Promise.all(
nestedAssetData.map(async _nestedAssetData =>
this.setProxyAllowanceAsync(userAddress, _nestedAssetData, desiredAllowance),
),
);
break;
}
default:
throw errorUtils.spawnSwitchErr('proxyId', proxyId);
}
}
}
|
Java
|
UTF-8
| 1,400 | 3.515625 | 4 |
[] |
no_license
|
public class Exam2 {
public static void main(String[] args) {
String student_name_first;
String student_name_last;
Student [][] school = new Student[5][20];
for(int counter_classroom = 1; counter_classroom < 6; counter_classroom++){
int student_counter = 0;
if(counter_classroom>2){
System.out.println("-Classroom "+ counter_classroom + "-----------------");
System.out.println("No Students in this class.");
} else {
System.out.println("-Classroom " + counter_classroom + "-----------------");
for (int counter_student = 1; counter_student < 4; counter_student++) {
student_counter++;
student_name_first = "FirstName_c" + counter_classroom + "s" + student_counter;
student_name_last = "LastName_c" + counter_classroom + "s" + student_counter;
school[counter_classroom - 1][counter_student - 1] = new Student(student_name_first, student_name_last);
outputSchool(school[counter_classroom - 1][counter_student - 1].getStudentID(),school[counter_classroom - 1][counter_student - 1].getStudentName());
}
}
}
}
private static void outputSchool(int id, String name) {
System.out.println(id + ", " + name);
}
}
|
Markdown
|
UTF-8
| 1,973 | 2.671875 | 3 |
[
"CC-BY-4.0",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# Stata Built-in Dynamic Documents
Stata started including dynamic documents capabilities with version 15 (June 2017). However, the capabilities are significantly limited when compared with either R Markdown & knitr or user-built tools that work with earlier versions of Stata such as [Markdoc](http://www.haghish.com/statistics/stata-blog/reproducible-research/markdoc.php).
The built-in tools can output HTML from Markdown ([dyndoc](https://www.stata.com/new-in-stata/markdown/)), and can output PDFs ([putpdf](https://www.stata.com/new-in-stata/create-pdfs/)) or Word documents ([putdocx](https://www.stata.com/new-in-stata/create-word-documents/)). But the syntax is different for all three! Tomas Dvorak wrote a blog post summarizing the shortcomings [here](https://muse.union.edu/dvorakt/review-of-statas-dyndoc/).
* [Video comparison](https://www.youtube.com/watch?v=tWrde-8TwPI).
* [Stata's example files](http://www.stata-press.com/data/r15/markdown/)
Thankfully, there are other free tools available.
* Stata and Markdown -->anything: [Markdoc](http://www.haghish.com/statistics/stata-blog/reproducible-research/markdoc.php). See the website, or check out the [Stata Forum](https://www.statalist.org/forums/search?q=markdoc&searchJSON=%7B%22keywords%22%3A%22markdoc%22%7D)--the developer E.F. Haghish is pretty good about answering questions there.
* For Stata (or R, SAS) and Word (for Windows only) you can try [StatTag](http://sites.northwestern.edu/stattag/).
* For LaTeX and Stata: [texdoc](http://repec.sowi.unibe.ch/stata/texdoc/) by Ben Jann.
* For Stata-->HTML/Markdoc: [webdoc](http://repec.sowi.unibe.ch/stata/webdoc/) by Ben Jann.
* I just discovered that someone has built a Stata and Jupyter Notebooks combination: [iPyStata](https://www.stata.com/meeting/chicago16/slides/chicago16_dekok.pdf).
* See the pros and cons of most of these in a [presentation](https://www.stata.com/meeting/oceania16/slides/rising-oceania16.pdf) by Bill Rising of StataCorp.
|
PHP
|
UTF-8
| 4,701 | 2.515625 | 3 |
[] |
no_license
|
<?php namespace WSUWP\Plugin\Covid;
class Email_Shortcodes {
public function init() {
}
public static function add_shortcodes() {
add_shortcode( 'e_post_feed', __CLASS__ . '::do_shortcode_post_feed' );
add_shortcode( 'e_has_posts', __CLASS__ . '::do_shortcode_has_posts' );
add_shortcode( 'e_date', __CLASS__ . '::do_shortcode_date' );
add_shortcode( 'e_date_month', __CLASS__ . '::do_shortcode_date' );
add_shortcode( 'e_date_day', __CLASS__ . '::do_shortcode_date' );
add_shortcode( 'e_date_day_name', __CLASS__ . '::do_shortcode_date' );
}
public static function add_post_shortcodes() {
add_shortcode( 'e_post_title', __CLASS__ . '::do_shortcode_post_title' );
add_shortcode( 'e_post_link', __CLASS__ . '::do_shortcode_post_link' );
add_shortcode( 'e_post_content', __CLASS__ . '::do_shortcode_post_content' );
add_shortcode( 'e_post_excerpt', __CLASS__ . '::do_shortcode_post_excerpt' );
}
public static function do_shortcode_post_title( $atts ) {
return get_the_title();
}
public static function do_shortcode_post_link( $atts, $content ) {
$default_atts = array(
'classes' => 'wsu-c-email__link',
'style' => '',
);
$atts = shortcode_atts( $default_atts, $atts );
$link = get_the_permalink();
$content = do_shortcode( $content );
return '<a class="' . $atts['classes'] . '" href="' . $link . '" style="' . $atts['style'] . '">' . $content . '</a>';
}
public static function do_shortcode_post_content( $atts ) {
ob_start();
the_content();
return ob_get_clean();
}
public static function do_shortcode_post_excerpt( $atts ) {
$default_atts = array(
'trim_words' => 35,
);
$atts = shortcode_atts( $default_atts, $atts );
return wp_trim_words( wp_strip_all_tags( get_the_excerpt() ), $atts['trim_words'] );
}
public static function do_shortcode_post_feed( $atts, $template ) {
$content = '';
$options = Email_Digest::get_options();
$options_atts['empty_posts_text'] = $options['empty_posts'];
if ( ! is_array( $atts ) ) {
$atts = array();
}
$atts = array_merge( $options_atts, $atts );
$query = self::get_query( $atts );
$the_query = new \WP_Query( $query );
self::add_post_shortcodes();
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
ob_start();
$the_query->the_post();
$content .= do_shortcode( $template );
}
} else {
$content .= '<p>' . $atts['empty_posts_text'] . '</p>';
}
wp_reset_postdata();
return $content;
}
public static function do_shortcode_has_posts( $atts, $template ) {
$content = ' ';
$query = self::get_query( $atts );
$the_query = new \WP_Query( $query );
if ( $the_query->have_posts() ) {
$content = do_shortcode( $template );
}
wp_reset_postdata();
return $content;
}
public static function do_shortcode_date( $atts, $content, $tag ) {
$default_atts = array(
'format' => 'F',
);
switch ( $tag ) {
case 'e_date_month':
$default_atts['format'] = 'F';
break;
case 'e_date_day':
$default_atts['format'] = 'j';
break;
case 'e_date_day_name':
$default_atts['format'] = 'l';
break;
}
$atts = shortcode_atts( $default_atts, $atts );
return current_time( $atts['format'] );
}
protected static function get_query( $atts ) {
$default_atts = array(
'categories' => '',
'exclude_categories' => '',
'orderby' => 'date',
'order' => 'DESC',
'count' => '20',
'by_time' => '',
'post_ids' => '',
'exclude_post_ids' => '',
);
$atts = shortcode_atts( $default_atts, $atts );
$args = array(
'post_type' => 'post',
'posts_per_page' => '10',
'orderby' => $atts['orderby'],
'order' => $atts['order'],
'posts_per_page' => $atts['count'],
);
if ( ! empty( $atts['post_ids'] ) ) {
$args['post__in'] = explode( ',', $atts['post_ids'] );
}
if ( ! empty( $atts['exclude_post_ids'] ) ) {
$args['post__not_in'] = explode( ',', $atts['exclude_post_ids'] );
}
if ( ! empty( $atts['by_time'] ) ) {
$args['date_query'] = array(
array(
'after' => $atts['by_time'],
),
);
}
if ( ! empty( $atts['exclude_categories'] ) ) {
$args['category__not_in'] = explode( ',', $atts['exclude_categories'] );
}
if ( ! empty( $atts['categories'] ) ) {
$args['cat'] = $atts['categories'];
}
if ( ! empty( $_REQUEST['demo_content'] ) ) {
unset( $args['cat'] );
unset( $args['date_query'] );
unset( $args['category__not_in'] );
$args['posts_per_page'] = 3;
}
return $args;
}
}
(new Email_Shortcodes )->init();
|
JavaScript
|
UTF-8
| 586 | 4.125 | 4 |
[] |
no_license
|
//clase 1 de
//alert(saludo)
var saludo = "hola mundo desde variable"
var array1 = ["Lunes","Martes","Miercoles"]
//alert(saludo)
console.log(saludo)
console.log(array1[0])
var nombre = prompt("Ingresa tu Nombre:","placeholder")
alert("Hola "+ nombre)
var numero = 1000
//Suma
var numeroUsuario = Number(prompt("Ingresa un NUMERO"))
alert(numero + numeroUsuario)
//Resta
var numeroUsuario = prompt("Ingresa un NUMERO")
alert(numero - numeroUsuario)
var numero1 = Number(prompt("Ingresa un NUMERO"))
var numero2 = Number(prompt("Ingresa un NUMERO"))
alert(numero1 + numero2)
|
JavaScript
|
UTF-8
| 1,029 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
function (stack, params, extra) {
extra = extra || {};
params = params.slice(0);
var last = params.pop();
if (typeof(last) === "object" && !(last instanceof Array))
extra.hash = last;
else
params.push(last);
// values[0] must be a function. if values[1] is a function, then
// apply values[1] to the remaining arguments, then apply
// values[0] to the results. otherwise, directly apply values[0]
// to the other arguments. if toplevel, also pass 'extra' as an
// argument.
var apply = function (values, toplevel) {
var args = values.slice(1);
if (args.length && typeof (args[0]) === "function")
args = [apply(args)];
if (toplevel)
args.push(extra);
return values[0].apply(stack.data, args);
};
var values = new Array(params.length);
for(var i=0; i<params.length; i++)
values[i] = eval_value(stack, params[i]);
if (typeof(values[0]) !== "function")
return values[0];
return apply(values, true);
}
|
Java
|
UTF-8
| 951 | 2.171875 | 2 |
[] |
no_license
|
package me.nexters.doctor24.batch.processor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.nexters.doctor24.batch.dto.hospital.detail.HospitalDetailRaw;
import me.nexters.doctor24.batch.processor.util.HospitalParser;
import me.nexters.domain.hospital.Hospital;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class HospitalDetailFailureProcessor implements ItemProcessor<List<HospitalDetailRaw>, List<Hospital>> {
@Override
public List<Hospital> process(List<HospitalDetailRaw> items) {
log.info("누락건 재배치 process 시작, 총 {} 개", items.size());
return items.stream().map(HospitalParser::parse).collect(Collectors.toList());
}
}
|
Java
|
UTF-8
| 1,305 | 2.296875 | 2 |
[] |
no_license
|
package com.bean;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "retailer_table")
public class Retailer
{
@Id
private long rid;
private int pincode;
@Column(name = "internet_kit")
private int internetKit;
@Column(name = "landline_kit")
private int landlineKit;
private long vid;
public long getRid() {
return rid;
}
public void setRid(long rid) {
this.rid = rid;
}
public int getPincode() {
return pincode;
}
public void setPincode(int pincode) {
this.pincode = pincode;
}
public int getInternetKit() {
return internetKit;
}
public void setInternetKit(int internetKit) {
this.internetKit = internetKit;
}
public int getLandlineKit() {
return landlineKit;
}
public void setLandlineKit(int landlineKit) {
this.landlineKit = landlineKit;
}
public long getVid() {
return vid;
}
public void setVid(long vid) {
this.vid = vid;
}
@Override
public String toString() {
return "Retailer [rid=" + rid + ", pincode=" + pincode + ", internetKit=" + internetKit + ", landlineKit="
+ landlineKit + ", vid=" + vid + ", listOfCusomer=" + "]";
}
}
|
Markdown
|
UTF-8
| 2,754 | 3.015625 | 3 |
[] |
no_license
|
# Monopoly
> Own project/application and testing with mock objects in TDD approach (writing test before code)
Explain your solution with focus on its design. Does it have low coupling, interfaces, polymorphism, Inversion of Control and Dependency injection as central design principles? If not, why? Otherwise, demonstrate it! <br>
> _Based on the UML sequence diagram and instructions, the `Player.takeTurn()` was implemented and the dependent classes are just interfaces._<br>

> _I decided to explore the other way of solving the problem, with stubs of Martin Fowler concepts. It is a common helper to testing environments, which provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test._<br>
> _IMPLEMENTATION_<br>

> _Sample test_<br>

> _this will return the sum of the 2 dice as 10, that's why we are expecting that it is gonna move 10 steps from its location_<br>

> _TEST RESULT_<br>

Explain your test case design activity and argument for the choices that you have made: <br>
• how to choose the right test conditions (i.e. what to test which in principle will be all code when you are a TDD’er )? <br>
> _Test conditions are the input that we are giving to test the application, it could also be functionalities just like when we test `takeTurn()`. It must focus to test those parts that impact the behavior or state of the system._<br>
• what test design techniques to use (both consider black-box techniques and white-box technique)? <br>
> _In most cases, white-box technique is ideally used by developers since it requires to know the system. On the other hand, black-box technique is widely used for testers who doesn't know the system, a matter of input and output verification for systems and acceptance testing._<br>
• how much effort to put into each test condition (how critical is the item will influence it’s test coverage percentage)? <br>
> _A rule of thumb: 80%_<br>
> _Here is the test coverage percentage on this assignment:_<br>

__SUBMITTED BY: CHERRY ROSE SEMEÑA__
|
C++
|
UTF-8
| 2,505 | 2.8125 | 3 |
[] |
no_license
|
#include <iostream>
#include "gtest/gtest.h"
#include "../src/Matrix.h"
#include "../src/kNN.h"
// --------- SET UP --------------
class runTest : public ::testing::Test {
protected:
virtual void SetUp() {
image_1.setIndex(0, 0, 0);
image_1.setIndex(0, 1, 0);
}
Matrix image_1 = Matrix(1,2);
};
TEST_F (runTest, trainSetSizeOneReturnsSameLabel){
Matrix ts_size_one = Matrix(1,2);
ts_size_one.setIndex(0, 0, 1);
ts_size_one.setIndex(0, 1, 2);
Matrix positive_label_size_one = Matrix(1,1);
positive_label_size_one .setIndex(0,0,1);
Matrix negative_label_size_one = Matrix(1,1);
negative_label_size_one.setIndex(0,0,0);
ASSERT_EQ( kNN(ts_size_one, positive_label_size_one,image_1, 1), 1);
ASSERT_EQ( kNN(ts_size_one, negative_label_size_one,image_1, 1), 0);
}
TEST_F (runTest, trainSetSizeTwoReturnsNearestLabel){
Matrix ts_size_two = Matrix(2,2);
ts_size_two.setIndex(0, 0, 1);
ts_size_two.setIndex(0, 1, 2);
ts_size_two.setIndex(1, 0, 2);
ts_size_two.setIndex(1, 1, 2);
Matrix label_size_two = Matrix(2,1);
label_size_two.setIndex(0,0,0);
label_size_two.setIndex(1,0,1);
ASSERT_EQ( kNN(ts_size_two, label_size_two,image_1, 1), 0);
}
TEST_F (runTest, kThreeHasTwoPositives){
Matrix ts_size_four = Matrix(4,2);
ts_size_four.setIndex(0, 0, 1);
ts_size_four.setIndex(0, 1, 2);
ts_size_four.setIndex(1, 0, 2);
ts_size_four.setIndex(1, 1, 2);
ts_size_four.setIndex(2, 0, 3);
ts_size_four.setIndex(2, 1, 2);
ts_size_four.setIndex(3, 0, 4);
ts_size_four.setIndex(3, 1, 2);
Matrix label_size_four = Matrix(4,1);
label_size_four.setIndex(0,0,0);
label_size_four.setIndex(1,0,1);
label_size_four.setIndex(2,0,1);
label_size_four.setIndex(3,0,0);
ASSERT_EQ( kNN(ts_size_four, label_size_four,image_1, 3), 1);
}
TEST_F (runTest, kThreeHasTwonegatives){
Matrix ts_size_four = Matrix(4,2);
ts_size_four.setIndex(0, 0, 1);
ts_size_four.setIndex(0, 1, 2);
ts_size_four.setIndex(1, 0, 2);
ts_size_four.setIndex(1, 1, 2);
ts_size_four.setIndex(2, 0, 3);
ts_size_four.setIndex(2, 1, 2);
ts_size_four.setIndex(3, 0, 4);
ts_size_four.setIndex(3, 1, 2);
Matrix label_size_four = Matrix(4,1);
label_size_four.setIndex(0,0,0);
label_size_four.setIndex(1,0,1);
label_size_four.setIndex(2,0,0);
label_size_four.setIndex(3,0,1);
ASSERT_EQ( kNN(ts_size_four, label_size_four,image_1, 3), 0);
}
|
JavaScript
|
UTF-8
| 959 | 4.1875 | 4 |
[] |
no_license
|
// 输入两个整数序列。 第一个表示栈的压入序列, 判断第二个序列是否为栈的弹出序列
// eg: [1, 2, 3, 4, 5], [4, 5, 3, 2, 1] => true
// [1, 2, 3, 4, 5], [4, 3, 5, 1, 2] => false
const testSq1 = [1, 2, 3, 4, 5], testSq2 = [4, 5, 3, 2, 1], testSq3 = [4, 3, 5, 1, 2];
function isPopOrder(pushSq, popSq) {
let stack = [];
let pushStart = 0, popEnd = popSq.length - 1, popStart = 0, pushEnd = pushSq.length - 1;
while (pushSq[pushStart] !== popSq[popStart]) {
stack.push(pushSq[pushStart]);
pushStart++;
}
while (popStart <= popEnd) {
if (popSq[popStart] === pushSq[pushStart]) {
pushStart++;
} else if (popSq[popStart] === stack[stack.length - 1]) {
stack.pop();
} else {
return false;
}
popStart++;
}
return true;
}
console.log(isPopOrder(testSq1, testSq2))
console.log(isPopOrder(testSq1, testSq3))
|
Shell
|
UTF-8
| 305 | 3.046875 | 3 |
[] |
no_license
|
#!/bin/sh
# Add information about current git
branch=$(git branch -a --contains `git rev-parse HEAD` | grep -v "detached" | grep "remote")
# trims whitespace
branch=$(set -f; echo $branch)
# Get current head sha
sha=$(git rev-parse HEAD)
# Create JSON
echo "{\"branch\":\"${branch}\",\"sha\":\"${sha}\"}"
|
C
|
UTF-8
| 2,069 | 2.796875 | 3 |
[] |
no_license
|
//#include <kipr/botball.h>
void GetChargingStatus();
void GetCreateSensorReadings();
void CreateSimpleMove();
void CreateLineFollowLeftFront();
int main()
{
create_connect();
msleep(1500);
// GetChargingStatus();
// msleep(1500);
GetCreateSensorReadings();
msleep(1500);
CreateLineFollowLeftFront();
create_stop();
create_disconnect();
return 0;
}
void GetChargingStatus()
{
printf("Battery Charge = %d\n", get_create_battery_charge());
printf("Battery Charging State = %d\n", get_create_battery_charging_state());
printf("Battery Charge Capacity = %d\n", get_create_battery_capacity());
printf("Battery Current = %d\n", get_create_battery_current());
}
void GetCreateSensorReadings()
{
printf("digital reading for front left sensor = %d\n", get_create_lfcliff());
printf("digital reading for front right sensor = %d\n", get_create_rfcliff());
printf("analog reading for front left sensor = %d\n", get_create_lfcliff_amt());
printf("analog reading for front right sensor = %d\n", get_create_rfcliff_amt());
}
// for testing purpposes
void CreateSimpleMove()
{
while (digital(0)==0)
{
create_drive_straight(100);
msleep(2000);
}
}
void CreateLineFollowLeftFront()
{
int black_threshold_low = 1240;
int black_threshold_high = 1500;
while (digital(0)==0)
{
// check front left and right sensor readings against the black threshold amount
if(get_create_lfcliff_amt() < black_threshold_low)
{
printf("Curving right, Left Cliff: %d Right cliff %d\n", get_create_lfcliff_amt(), get_create_rfcliff_amt());
create_drive_direct(50, 0);
}
else if(get_create_lfcliff_amt() > black_threshold_high)
{
printf("Curving left, Left Cliff: %d Right cliff %d\n", get_create_lfcliff_amt(), get_create_rfcliff_amt());
create_drive_direct(0, 50);
}
else
{
printf("Straight, Left Cliff: %d Right cliff %d\n", get_create_lfcliff_amt(), get_create_rfcliff_amt());
create_drive_direct(50, 50);
}
}
create_stop();
create_disconnect();
}
|
C++
|
UTF-8
| 63,093 | 2.578125 | 3 |
[] |
no_license
|
#include <twopi/vk/vulkan_engine.h>
#include <stdexcept>
#include <iostream>
#include <fstream>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <chrono>
#include <glm/gtc/matrix_transform.hpp>
#define STB_IMAGE_IMPLEMENTATION
#include <stb/stb_image.h>
#define TINYOBJLOADER_IMPLEMENTATION
#include <tinyobjloader/tiny_obj_loader.h>
namespace twopi
{
namespace vk
{
namespace
{
const std::vector<const char*> validation_layers = {
"VK_LAYER_KHRONOS_validation",
};
const std::vector<const char*> device_extensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME,
};
bool CheckValidationLayerSupport()
{
uint32_t layer_count;
vkEnumerateInstanceLayerProperties(&layer_count, nullptr);
std::vector<VkLayerProperties> available_layers(layer_count);
vkEnumerateInstanceLayerProperties(&layer_count, available_layers.data());
for (const char* layer_name : validation_layers)
{
bool layer_found = false;
for (const auto& layer_properties : available_layers)
{
if (strcmp(layer_name, layer_properties.layerName) == 0)
{
layer_found = true;
break;
}
}
if (!layer_found)
return false;
}
return true;
}
VKAPI_ATTR VkBool32 VKAPI_CALL DebugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT messageType, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData)
{
if ((messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) ||
(messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT))
std::cerr << "validation layer: " << pCallbackData->pMessage << std::endl;
return VK_FALSE;
}
void PopulateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& create_info)
{
create_info = {};
create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
create_info.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
create_info.pfnUserCallback = DebugCallback;
}
VkResult CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT* pDebugMessenger)
{
auto func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT");
if (func != nullptr)
return func(instance, pCreateInfo, pAllocator, pDebugMessenger);
else
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
void DestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT debugMessenger, const VkAllocationCallbacks* pAllocator)
{
auto func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT");
if (func != nullptr)
func(instance, debugMessenger, pAllocator);
}
std::vector<char> ReadFile(const std::string& filename)
{
std::ifstream file(filename, std::ios::ate | std::ios::binary);
if (!file.is_open())
throw std::runtime_error("Failed to open file!");
size_t file_size = (size_t)file.tellg();
std::vector<char> buffer(file_size);
file.seekg(0);
file.read(buffer.data(), file_size);
file.close();
return buffer;
}
}
VulkanEngine::VulkanEngine()
{
}
VulkanEngine::~VulkanEngine()
{
}
void VulkanEngine::Draw()
{
vkWaitForFences(device_, 1, &in_flight_fences_[current_frame_], VK_TRUE, UINT64_MAX);
uint32_t image_index;
VkResult result = vkAcquireNextImageKHR(device_, swapchain_, UINT64_MAX, image_available_semaphores_[current_frame_], VK_NULL_HANDLE, &image_index);
if (result == VK_ERROR_OUT_OF_DATE_KHR)
{
RecreateSwapchain();
return;
}
else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR)
throw std::runtime_error("Failed to acquire swap chain image!");
UpdateUniformBuffer(image_index);
if (images_in_flight_[image_index] != VK_NULL_HANDLE)
vkWaitForFences(device_, 1, &images_in_flight_[image_index], VK_TRUE, UINT64_MAX);
images_in_flight_[image_index] = in_flight_fences_[current_frame_];
VkSubmitInfo submit_info{};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
VkSemaphore wait_semaphores[] = { image_available_semaphores_[current_frame_] };
VkPipelineStageFlags wait_stages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
submit_info.waitSemaphoreCount = 1;
submit_info.pWaitSemaphores = wait_semaphores;
submit_info.pWaitDstStageMask = wait_stages;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &command_buffers_[image_index];
VkSemaphore signal_semaphores[] = { render_finished_semaphores_[current_frame_] };
submit_info.signalSemaphoreCount = 1;
submit_info.pSignalSemaphores = signal_semaphores;
vkResetFences(device_, 1, &in_flight_fences_[current_frame_]);
if (vkQueueSubmit(graphics_queue_, 1, &submit_info, in_flight_fences_[current_frame_]) != VK_SUCCESS)
throw std::runtime_error("Failed to submit draw command buffer!");
VkPresentInfoKHR present_info{};
present_info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
present_info.waitSemaphoreCount = 1;
present_info.pWaitSemaphores = signal_semaphores;
VkSwapchainKHR swapchains[] = { swapchain_ };
present_info.swapchainCount = 1;
present_info.pSwapchains = swapchains;
present_info.pImageIndices = &image_index;
result = vkQueuePresentKHR(present_queue_, &present_info);
if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR || framebuffer_resized_)
{
framebuffer_resized_ = false;
RecreateSwapchain();
}
else if (result != VK_SUCCESS)
throw std::runtime_error("Failed to present swap chain image!");
current_frame_ = (current_frame_ + 1) % max_frames_in_flight_;
}
void VulkanEngine::UpdateUniformBuffer(uint32_t current_image)
{
static auto startTime = std::chrono::high_resolution_clock::now();
auto currentTime = std::chrono::high_resolution_clock::now();
float time = std::chrono::duration<float, std::chrono::seconds::period>(currentTime - startTime).count();
UniformBufferObject ubo{};
ubo.model = glm::rotate(glm::mat4(1.0f), time * glm::radians(90.0f), glm::vec3(0.0f, 0.0f, 1.0f));
ubo.view = glm::lookAt(glm::vec3(2.0f, 2.0f, 2.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f));
ubo.proj = glm::perspective(glm::radians(45.0f), swapchain_extent_.width / (float)swapchain_extent_.height, 0.1f, 10.0f);
ubo.proj[1][1] *= -1;
void* data;
vkMapMemory(device_, uniform_buffers_memory_[current_image], 0, sizeof(ubo), 0, &data);
memcpy(data, &ubo, sizeof(ubo));
vkUnmapMemory(device_, uniform_buffers_memory_[current_image]);
}
void VulkanEngine::DeviceWaitIdle()
{
vkDeviceWaitIdle(device_);
}
void VulkanEngine::Prepare(const PreparationOptions& preparation_params)
{
hWindow_ = preparation_params.hWindow;
enable_validation_layers_ = preparation_params.enable_validation_layers;
CreateInstance(preparation_params.instance_extensions);
if (enable_validation_layers_)
SetupDebugMessenger();
CreateSurface(preparation_params.hInstance, preparation_params.hWindow);
PickPhysicalDevice(preparation_params.physical_device_selector);
msaa_samples_ = GetMaxUsableSampleCount();
CreateLogicalDevice();
CreateDescriptorSetLayout();
CreateCommandPool();
CreateTextureImage("../resources/viking_room.png");
CreateTextureImageView();
CreateTextureSampler();
LoadModel("../resources/viking_room.obj");
CreateVertexBuffer();
CreateIndexBuffer();
CreateSwapchain();
CreateSwapchainImageViews();
CreateSyncObjects();
CreateRenderPass();
CreateUniformBuffers();
CreateDescriptorPool();
CreateDescriptorSets();
CreateGraphicsPipeline();
CreateColorResources();
CreateDepthResources();
CreateFramebuffers();
CreateCommandBuffers();
}
void VulkanEngine::RecreateSwapchain()
{
/*
int width = 0, height = 0;
glfwGetFramebufferSize(window, &width, &height);
while (width == 0 || height == 0) {
glfwGetFramebufferSize(window, &width, &height);
glfwWaitEvents();
}
*/
RECT area;
GetClientRect(hWindow_, &area);
int width = area.right;
int height = area.bottom;
DeviceWaitIdle();
CleanupSwapchain();
CreateSwapchain();
CreateSwapchainImageViews();
CreateRenderPass();
CreateDescriptorPool();
CreateDescriptorSets();
CreateGraphicsPipeline();
CreateColorResources();
CreateDepthResources();
CreateFramebuffers();
CreateUniformBuffers();
CreateCommandBuffers();
}
void VulkanEngine::CleanupSwapchain()
{
vkDestroyImageView(device_, depth_image_view_, nullptr);
vkDestroyImage(device_, depth_image_, nullptr);
vkFreeMemory(device_, depth_image_memory_, nullptr);
vkDestroyImageView(device_, color_image_view_, nullptr);
vkDestroyImage(device_, color_image_, nullptr);
vkFreeMemory(device_, color_image_memory_, nullptr);
for (auto framebuffer : swapchain_framebuffers_)
vkDestroyFramebuffer(device_, framebuffer, nullptr);
vkFreeCommandBuffers(device_, command_pool_, static_cast<uint32_t>(command_buffers_.size()), command_buffers_.data());
vkDestroyPipeline(device_, graphics_pipeline_, nullptr);
vkDestroyPipelineLayout(device_, pipeline_layout_, nullptr);
vkDestroyRenderPass(device_, render_pass_, nullptr);
for (auto image_view : swapchain_image_views_)
vkDestroyImageView(device_, image_view, nullptr);
vkDestroySwapchainKHR(device_, swapchain_, nullptr);
for (size_t i = 0; i < swapchain_images_.size(); i++)
{
vkDestroyBuffer(device_, uniform_buffers_[i], nullptr);
vkFreeMemory(device_, uniform_buffers_memory_[i], nullptr);
}
vkDestroyDescriptorPool(device_, descriptor_pool_, nullptr);
}
void VulkanEngine::Cleanup()
{
CleanupSwapchain();
vkDestroySampler(device_, texture_sampler_, nullptr);
vkDestroyImageView(device_, texture_image_view_, nullptr);
vkDestroyImage(device_, texture_image_, nullptr);
vkFreeMemory(device_, texture_image_memory_, nullptr);
vkDestroyDescriptorSetLayout(device_, descriptor_set_layout_, nullptr);
vkDestroyBuffer(device_, index_buffer_, nullptr);
vkFreeMemory(device_, index_buffer_memory_, nullptr);
vkDestroyBuffer(device_, vertex_buffer_, nullptr);
vkFreeMemory(device_, vertex_buffer_memory_, nullptr);
for (size_t i = 0; i < max_frames_in_flight_; i++)
{
vkDestroySemaphore(device_, render_finished_semaphores_[i], nullptr);
vkDestroySemaphore(device_, image_available_semaphores_[i], nullptr);
vkDestroyFence(device_, in_flight_fences_[i], nullptr);
}
vkDestroyCommandPool(device_, command_pool_, nullptr);
vkDestroyDevice(device_, nullptr);
if (enable_validation_layers_)
DestroyDebugUtilsMessengerEXT(instance_, debug_messenger_, nullptr);
vkDestroySurfaceKHR(instance_, surface_, nullptr);
vkDestroyInstance(instance_, nullptr);
}
void VulkanEngine::CreateInstance(std::vector<std::string> extensions)
{
if (enable_validation_layers_ && !CheckValidationLayerSupport())
throw std::runtime_error("Validation layers requested, but not available!");
VkApplicationInfo app_info{};
app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
app_info.pApplicationName = "TwoPi Vk";
app_info.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
app_info.pEngineName = "TwoPi Engine";
app_info.engineVersion = VK_MAKE_VERSION(1, 0, 0);
app_info.apiVersion = VK_API_VERSION_1_0;
VkInstanceCreateInfo create_info{};
create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
create_info.pApplicationInfo = &app_info;
// Add required extensions by vulkan engine
std::unordered_set<std::string> extensions_set(extensions.begin(), extensions.end());
for (const auto& required_extension : GetRequiredExtensions())
{
if (extensions_set.find(required_extension) == extensions_set.end())
{
extensions_set.insert(required_extension);
extensions.emplace_back(required_extension);
}
}
std::vector<const char*> extensions_cstr;
for (const auto& extension : extensions)
extensions_cstr.push_back(extension.c_str());
create_info.enabledExtensionCount = static_cast<uint32_t>(extensions_cstr.size());
create_info.ppEnabledExtensionNames = extensions_cstr.data();
VkDebugUtilsMessengerCreateInfoEXT debug_create_info;
if (enable_validation_layers_)
{
create_info.enabledLayerCount = static_cast<uint32_t>(validation_layers.size());
create_info.ppEnabledLayerNames = validation_layers.data();
PopulateDebugMessengerCreateInfo(debug_create_info);
create_info.pNext = (VkDebugUtilsMessengerCreateInfoEXT*)&debug_create_info;
}
else
{
create_info.enabledLayerCount = 0;
create_info.pNext = nullptr;
}
if (vkCreateInstance(&create_info, nullptr, &instance_) != VK_SUCCESS)
throw std::runtime_error("Failed to create instance!");
}
std::vector<const char*> VulkanEngine::GetRequiredExtensions()
{
std::vector<const char*> extensions;
extensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
extensions.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
if (enable_validation_layers_)
extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
return extensions;
}
void VulkanEngine::SetupDebugMessenger()
{
VkDebugUtilsMessengerCreateInfoEXT create_info;
PopulateDebugMessengerCreateInfo(create_info);
if (CreateDebugUtilsMessengerEXT(instance_, &create_info, nullptr, &debug_messenger_) != VK_SUCCESS)
throw std::runtime_error("Failed to set up debug messenger!");
}
void VulkanEngine::CreateSurface(const HINSTANCE hInstance, const HWND hWindow)
{
VkWin32SurfaceCreateInfoKHR create_info{};
create_info.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
create_info.flags = 0;
create_info.hinstance = hInstance;
create_info.hwnd = hWindow;
if (vkCreateWin32SurfaceKHR(instance_, &create_info, nullptr, &surface_) != VK_SUCCESS)
throw std::runtime_error("Failed to set up surface!");
}
void VulkanEngine::PickPhysicalDevice(std::function<VkPhysicalDevice(VkInstance)> physical_device_selector)
{
if (physical_device_selector)
physical_device_ = physical_device_selector(instance_);
else
PickBestPhysicalDevice();
}
void VulkanEngine::PickBestPhysicalDevice()
{
uint32_t device_count = 0;
vkEnumeratePhysicalDevices(instance_, &device_count, nullptr);
if (device_count == 0)
throw std::runtime_error("Failed to find GPUs with Vulkan support!");
std::vector<VkPhysicalDevice> devices(device_count);
vkEnumeratePhysicalDevices(instance_, &device_count, devices.data());
for (const auto& device : devices)
{
if (IsDeviceSuitable(device)) {
physical_device_ = device;
break;
}
}
if (physical_device_ == VK_NULL_HANDLE)
throw std::runtime_error("Failed to find a suitable GPU!");
}
bool VulkanEngine::IsDeviceSuitable(VkPhysicalDevice device)
{
QueueFamilyIndices indices = FindQueueFamilies(device);
bool extensions_supported = CheckDeviceExtensionSupport(device);
bool swapchain_adequate = false;
if (extensions_supported)
{
SwapchainSupportDetails swapchain_support = QuerySwapchainSupport(device);
swapchain_adequate = !swapchain_support.formats.empty() && !swapchain_support.present_modes.empty();
}
VkPhysicalDeviceFeatures supported_features;
vkGetPhysicalDeviceFeatures(device, &supported_features);
return indices.IsComplete() && extensions_supported && swapchain_adequate && supported_features.samplerAnisotropy;
}
VulkanEngine::QueueFamilyIndices VulkanEngine::FindQueueFamilies(VkPhysicalDevice device)
{
QueueFamilyIndices indices;
uint32_t queue_family_count = 0;
vkGetPhysicalDeviceQueueFamilyProperties(device, &queue_family_count, nullptr);
std::vector<VkQueueFamilyProperties> queue_families(queue_family_count);
vkGetPhysicalDeviceQueueFamilyProperties(device, &queue_family_count, queue_families.data());
int i = 0;
for (const auto& queue_family : queue_families)
{
if (queue_family.queueFlags & VK_QUEUE_GRAPHICS_BIT)
indices.graphics_family = i;
VkBool32 present_support = false;
vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface_, &present_support);
if (present_support)
indices.present_family = i;
if (indices.IsComplete())
break;
i++;
}
return indices;
}
bool VulkanEngine::CheckDeviceExtensionSupport(VkPhysicalDevice device)
{
uint32_t extension_count;
vkEnumerateDeviceExtensionProperties(device, nullptr, &extension_count, nullptr);
std::vector<VkExtensionProperties> available_extensions(extension_count);
vkEnumerateDeviceExtensionProperties(device, nullptr, &extension_count, available_extensions.data());
std::set<std::string> required_extensions(device_extensions.begin(), device_extensions.end());
for (const auto& extension : available_extensions)
required_extensions.erase(extension.extensionName);
return required_extensions.empty();
}
VulkanEngine::SwapchainSupportDetails VulkanEngine::QuerySwapchainSupport(VkPhysicalDevice device)
{
SwapchainSupportDetails details;
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface_, &details.capabilities);
uint32_t formatCount;
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface_, &formatCount, nullptr);
if (formatCount != 0)
{
details.formats.resize(formatCount);
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface_, &formatCount, details.formats.data());
}
uint32_t present_mode_count;
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface_, &present_mode_count, nullptr);
if (present_mode_count != 0)
{
details.present_modes.resize(present_mode_count);
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface_, &present_mode_count, details.present_modes.data());
}
return details;
}
VkSampleCountFlagBits VulkanEngine::GetMaxUsableSampleCount()
{
VkPhysicalDeviceProperties physical_device_properties;
vkGetPhysicalDeviceProperties(physical_device_, &physical_device_properties);
VkSampleCountFlags counts = physical_device_properties.limits.framebufferColorSampleCounts & physical_device_properties.limits.framebufferDepthSampleCounts;
if (counts & VK_SAMPLE_COUNT_64_BIT) return VK_SAMPLE_COUNT_64_BIT;
if (counts & VK_SAMPLE_COUNT_32_BIT) return VK_SAMPLE_COUNT_32_BIT;
if (counts & VK_SAMPLE_COUNT_16_BIT) return VK_SAMPLE_COUNT_16_BIT;
if (counts & VK_SAMPLE_COUNT_8_BIT) return VK_SAMPLE_COUNT_8_BIT;
if (counts & VK_SAMPLE_COUNT_4_BIT) return VK_SAMPLE_COUNT_4_BIT;
if (counts & VK_SAMPLE_COUNT_2_BIT) return VK_SAMPLE_COUNT_2_BIT;
return VK_SAMPLE_COUNT_1_BIT;
}
void VulkanEngine::CreateLogicalDevice()
{
QueueFamilyIndices indices = FindQueueFamilies(physical_device_);
std::vector<VkDeviceQueueCreateInfo> queue_create_infos;
std::set<uint32_t> unique_queue_families = { indices.graphics_family.value(), indices.present_family.value() };
float queue_priority = 1.0f;
for (uint32_t queue_family : unique_queue_families)
{
VkDeviceQueueCreateInfo queue_create_info{};
queue_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queue_create_info.queueFamilyIndex = queue_family;
queue_create_info.queueCount = 1;
queue_create_info.pQueuePriorities = &queue_priority;
queue_create_infos.push_back(queue_create_info);
}
VkPhysicalDeviceFeatures device_features{};
device_features.samplerAnisotropy = VK_TRUE;
VkDeviceCreateInfo create_info{};
create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
create_info.queueCreateInfoCount = static_cast<uint32_t>(queue_create_infos.size());
create_info.pQueueCreateInfos = queue_create_infos.data();
create_info.pEnabledFeatures = &device_features;
create_info.enabledExtensionCount = static_cast<uint32_t>(device_extensions.size());
create_info.ppEnabledExtensionNames = device_extensions.data();
if (enable_validation_layers_)
{
create_info.enabledLayerCount = static_cast<uint32_t>(validation_layers.size());
create_info.ppEnabledLayerNames = validation_layers.data();
}
else
create_info.enabledLayerCount = 0;
if (vkCreateDevice(physical_device_, &create_info, nullptr, &device_) != VK_SUCCESS)
throw std::runtime_error("failed to create logical device!");
vkGetDeviceQueue(device_, indices.graphics_family.value(), 0, &graphics_queue_);
vkGetDeviceQueue(device_, indices.present_family.value(), 0, &present_queue_);
}
void VulkanEngine::CreateSwapchain()
{
SwapchainSupportDetails swapchain_support = QuerySwapchainSupport(physical_device_);
VkSurfaceFormatKHR surface_format = ChooseSwapchainSurfaceFormat(swapchain_support.formats);
VkPresentModeKHR present_mode = ChooseSwapchainPresentMode(swapchain_support.present_modes);
VkExtent2D extent = ChooseSwapchainExtent(swapchain_support.capabilities);
uint32_t image_count = swapchain_support.capabilities.minImageCount + 1;
if (swapchain_support.capabilities.maxImageCount > 0 && image_count > swapchain_support.capabilities.maxImageCount)
image_count = swapchain_support.capabilities.maxImageCount;
VkSwapchainCreateInfoKHR create_info{};
create_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
create_info.surface = surface_;
create_info.minImageCount = image_count;
create_info.imageFormat = surface_format.format;
create_info.imageColorSpace = surface_format.colorSpace;
create_info.imageExtent = extent;
create_info.imageArrayLayers = 1;
create_info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
QueueFamilyIndices indices = FindQueueFamilies(physical_device_);
uint32_t queue_family_indices[] = { indices.graphics_family.value(), indices.present_family.value() };
if (indices.graphics_family != indices.present_family)
{
create_info.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
create_info.queueFamilyIndexCount = 2;
create_info.pQueueFamilyIndices = queue_family_indices;
}
else
create_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
create_info.preTransform = swapchain_support.capabilities.currentTransform;
create_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
create_info.presentMode = present_mode;
create_info.clipped = VK_TRUE;
if (vkCreateSwapchainKHR(device_, &create_info, nullptr, &swapchain_) != VK_SUCCESS)
throw std::runtime_error("Failed to create swapchain!");
vkGetSwapchainImagesKHR(device_, swapchain_, &image_count, nullptr);
swapchain_images_.resize(image_count);
vkGetSwapchainImagesKHR(device_, swapchain_, &image_count, swapchain_images_.data());
swapchain_image_format_ = surface_format.format;
swapchain_extent_ = extent;
}
VkSurfaceFormatKHR VulkanEngine::ChooseSwapchainSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& available_formats)
{
for (const auto& available_format : available_formats)
{
if (available_format.format == VK_FORMAT_B8G8R8A8_SRGB && available_format.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR)
return available_format;
}
return available_formats[0];
}
VkPresentModeKHR VulkanEngine::ChooseSwapchainPresentMode(const std::vector<VkPresentModeKHR>& available_present_modes)
{
for (const auto& available_present_mode : available_present_modes)
{
if (available_present_mode == VK_PRESENT_MODE_MAILBOX_KHR)
return available_present_mode;
}
return VK_PRESENT_MODE_FIFO_KHR;
}
VkExtent2D VulkanEngine::ChooseSwapchainExtent(const VkSurfaceCapabilitiesKHR& capabilities)
{
if (capabilities.currentExtent.width != UINT32_MAX)
return capabilities.currentExtent;
else
{
RECT area;
GetClientRect(hWindow_, &area);
int width = area.right;
int height = area.bottom;
VkExtent2D actual_extent = {
static_cast<uint32_t>(width),
static_cast<uint32_t>(height),
};
actual_extent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actual_extent.width));
actual_extent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actual_extent.height));
return actual_extent;
}
}
void VulkanEngine::CreateSwapchainImageViews()
{
swapchain_image_views_.resize(swapchain_images_.size());
for (uint32_t i = 0; i < swapchain_images_.size(); i++)
swapchain_image_views_[i] = CreateImageView(swapchain_images_[i], swapchain_image_format_, VK_IMAGE_ASPECT_COLOR_BIT, 1);
}
VkImageView VulkanEngine::CreateImageView(VkImage image, VkFormat format, VkImageAspectFlags aspect_flags, uint32_t mip_levels)
{
VkImageViewCreateInfo view_info{};
view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
view_info.image = image;
view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
view_info.format = format;
view_info.subresourceRange.aspectMask = aspect_flags;
view_info.subresourceRange.baseMipLevel = 0;
view_info.subresourceRange.levelCount = mip_levels;
view_info.subresourceRange.baseArrayLayer = 0;
view_info.subresourceRange.layerCount = 1;
VkImageView image_view_;
if (vkCreateImageView(device_, &view_info, nullptr, &image_view_) != VK_SUCCESS)
throw std::runtime_error("Failed to create texture image view!");
return image_view_;
}
void VulkanEngine::CreateRenderPass()
{
VkAttachmentDescription color_attachment{};
color_attachment.format = swapchain_image_format_;
color_attachment.samples = msaa_samples_;
color_attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
color_attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
color_attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
color_attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
color_attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
color_attachment.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkAttachmentDescription depth_attachment{};
depth_attachment.format = FindDepthFormat();
depth_attachment.samples = msaa_samples_;
depth_attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
depth_attachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
depth_attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
depth_attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
depth_attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
depth_attachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkAttachmentDescription color_attachment_resolve{};
color_attachment_resolve.format = swapchain_image_format_;
color_attachment_resolve.samples = VK_SAMPLE_COUNT_1_BIT;
color_attachment_resolve.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
color_attachment_resolve.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
color_attachment_resolve.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
color_attachment_resolve.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
color_attachment_resolve.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
color_attachment_resolve.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
VkAttachmentReference color_attachment_ref{};
color_attachment_ref.attachment = 0;
color_attachment_ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkAttachmentReference depth_attachment_ref{};
depth_attachment_ref.attachment = 1;
depth_attachment_ref.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkAttachmentReference color_attachment_resolve_ref{};
color_attachment_resolve_ref.attachment = 2;
color_attachment_resolve_ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkSubpassDescription subpass{};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &color_attachment_ref;
subpass.pDepthStencilAttachment = &depth_attachment_ref;
subpass.pResolveAttachments = &color_attachment_resolve_ref;
VkSubpassDependency dependency{};
dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
dependency.dstSubpass = 0;
dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
dependency.srcAccessMask = 0;
dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
std::array<VkAttachmentDescription, 3> attachments = { color_attachment, depth_attachment, color_attachment_resolve };
VkRenderPassCreateInfo render_pass_info{};
render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
render_pass_info.attachmentCount = static_cast<uint32_t>(attachments.size());
render_pass_info.pAttachments = attachments.data();
render_pass_info.subpassCount = 1;
render_pass_info.pSubpasses = &subpass;
render_pass_info.dependencyCount = 1;
render_pass_info.pDependencies = &dependency;
if (vkCreateRenderPass(device_, &render_pass_info, nullptr, &render_pass_) != VK_SUCCESS)
throw std::runtime_error("Failed to create render pass!");
}
VkFormat VulkanEngine::FindDepthFormat()
{
return FindSupportedFormat(
{ VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT },
VK_IMAGE_TILING_OPTIMAL,
VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT
);
}
VkFormat VulkanEngine::FindSupportedFormat(const std::vector<VkFormat>& candidates, VkImageTiling tiling, VkFormatFeatureFlags features)
{
for (VkFormat format : candidates)
{
VkFormatProperties props;
vkGetPhysicalDeviceFormatProperties(physical_device_, format, &props);
if (tiling == VK_IMAGE_TILING_LINEAR && (props.linearTilingFeatures & features) == features)
return format;
else if (tiling == VK_IMAGE_TILING_OPTIMAL && (props.optimalTilingFeatures & features) == features)
return format;
}
throw std::runtime_error("Failed to find supported format!");
}
void VulkanEngine::CreateDescriptorSetLayout()
{
VkDescriptorSetLayoutBinding ubo_layout_binding{};
ubo_layout_binding.binding = 0;
ubo_layout_binding.descriptorCount = 1;
ubo_layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
ubo_layout_binding.pImmutableSamplers = nullptr;
ubo_layout_binding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
VkDescriptorSetLayoutBinding sampler_layout_binding{};
sampler_layout_binding.binding = 1;
sampler_layout_binding.descriptorCount = 1;
sampler_layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
sampler_layout_binding.pImmutableSamplers = nullptr;
sampler_layout_binding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
std::array<VkDescriptorSetLayoutBinding, 2> bindings = { ubo_layout_binding, sampler_layout_binding };
VkDescriptorSetLayoutCreateInfo layout_info{};
layout_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layout_info.bindingCount = static_cast<uint32_t>(bindings.size());
layout_info.pBindings = bindings.data();
if (vkCreateDescriptorSetLayout(device_, &layout_info, nullptr, &descriptor_set_layout_) != VK_SUCCESS)
throw std::runtime_error("Failed to create descriptor set layout!");
}
void VulkanEngine::CreateGraphicsPipeline()
{
auto vert_shader_code = ReadFile("shaders/mesh.vert.spv");
auto frag_shader_code = ReadFile("shaders/mesh.frag.spv");
VkShaderModule vert_shader_module = CreateShaderModule(vert_shader_code);
VkShaderModule frag_shader_module = CreateShaderModule(frag_shader_code);
VkPipelineShaderStageCreateInfo vert_shader_stage_info{};
vert_shader_stage_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
vert_shader_stage_info.stage = VK_SHADER_STAGE_VERTEX_BIT;
vert_shader_stage_info.module = vert_shader_module;
vert_shader_stage_info.pName = "main";
VkPipelineShaderStageCreateInfo frag_shader_stage_info{};
frag_shader_stage_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
frag_shader_stage_info.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
frag_shader_stage_info.module = frag_shader_module;
frag_shader_stage_info.pName = "main";
VkPipelineShaderStageCreateInfo shader_stages[] = { vert_shader_stage_info, frag_shader_stage_info };
VkPipelineVertexInputStateCreateInfo vertex_input_info{};
vertex_input_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
auto binding_description = Vertex::GetBindingDescription();
auto attribute_descriptions = Vertex::GetAttributeDescriptions();
vertex_input_info.vertexBindingDescriptionCount = 1;
vertex_input_info.vertexAttributeDescriptionCount = static_cast<uint32_t>(attribute_descriptions.size());
vertex_input_info.pVertexBindingDescriptions = &binding_description;
vertex_input_info.pVertexAttributeDescriptions = attribute_descriptions.data();
VkPipelineInputAssemblyStateCreateInfo input_assembly{};
input_assembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
input_assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
input_assembly.primitiveRestartEnable = VK_FALSE;
VkViewport viewport{};
viewport.x = 0.0f;
viewport.y = 0.0f;
viewport.width = (float)swapchain_extent_.width;
viewport.height = (float)swapchain_extent_.height;
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
VkRect2D scissor{};
scissor.offset = { 0, 0 };
scissor.extent = swapchain_extent_;
VkPipelineViewportStateCreateInfo viewport_state{};
viewport_state.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewport_state.viewportCount = 1;
viewport_state.pViewports = &viewport;
viewport_state.scissorCount = 1;
viewport_state.pScissors = &scissor;
VkPipelineRasterizationStateCreateInfo rasterizer{};
rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterizer.depthClampEnable = VK_FALSE;
rasterizer.rasterizerDiscardEnable = VK_FALSE;
rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
rasterizer.lineWidth = 1.0f;
rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
rasterizer.depthBiasEnable = VK_FALSE;
VkPipelineMultisampleStateCreateInfo multisampling{};
multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisampling.sampleShadingEnable = VK_FALSE;
multisampling.rasterizationSamples = msaa_samples_;
VkPipelineDepthStencilStateCreateInfo depth_stencil{};
depth_stencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
depth_stencil.depthTestEnable = VK_TRUE;
depth_stencil.depthWriteEnable = VK_TRUE;
depth_stencil.depthCompareOp = VK_COMPARE_OP_LESS;
depth_stencil.depthBoundsTestEnable = VK_FALSE;
depth_stencil.stencilTestEnable = VK_FALSE;
VkPipelineColorBlendAttachmentState color_blend_attachment{};
color_blend_attachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
color_blend_attachment.blendEnable = VK_FALSE;
VkPipelineColorBlendStateCreateInfo color_blending{};
color_blending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
color_blending.logicOpEnable = VK_FALSE;
color_blending.logicOp = VK_LOGIC_OP_COPY;
color_blending.attachmentCount = 1;
color_blending.pAttachments = &color_blend_attachment;
color_blending.blendConstants[0] = 0.0f;
color_blending.blendConstants[1] = 0.0f;
color_blending.blendConstants[2] = 0.0f;
color_blending.blendConstants[3] = 0.0f;
VkPipelineLayoutCreateInfo pipeline_layout_info{};
pipeline_layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipeline_layout_info.setLayoutCount = 1;
pipeline_layout_info.pSetLayouts = &descriptor_set_layout_;
if (vkCreatePipelineLayout(device_, &pipeline_layout_info, nullptr, &pipeline_layout_) != VK_SUCCESS)
throw std::runtime_error("Failed to create pipeline layout!");
VkGraphicsPipelineCreateInfo pipeline_info{};
pipeline_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipeline_info.stageCount = 2;
pipeline_info.pStages = shader_stages;
pipeline_info.pVertexInputState = &vertex_input_info;
pipeline_info.pInputAssemblyState = &input_assembly;
pipeline_info.pViewportState = &viewport_state;
pipeline_info.pRasterizationState = &rasterizer;
pipeline_info.pMultisampleState = &multisampling;
pipeline_info.pDepthStencilState = &depth_stencil;
pipeline_info.pColorBlendState = &color_blending;
pipeline_info.layout = pipeline_layout_;
pipeline_info.renderPass = render_pass_;
pipeline_info.subpass = 0;
pipeline_info.basePipelineHandle = VK_NULL_HANDLE;
if (vkCreateGraphicsPipelines(device_, VK_NULL_HANDLE, 1, &pipeline_info, nullptr, &graphics_pipeline_) != VK_SUCCESS)
throw std::runtime_error("Failed to create graphics pipeline!");
vkDestroyShaderModule(device_, frag_shader_module, nullptr);
vkDestroyShaderModule(device_, vert_shader_module, nullptr);
}
VkShaderModule VulkanEngine::CreateShaderModule(const std::vector<char>& code)
{
VkShaderModuleCreateInfo create_info{};
create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
create_info.codeSize = code.size();
create_info.pCode = reinterpret_cast<const uint32_t*>(code.data());
VkShaderModule shader_module;
if (vkCreateShaderModule(device_, &create_info, nullptr, &shader_module) != VK_SUCCESS)
throw std::runtime_error("Failed to create shader module!");
return shader_module;
}
void VulkanEngine::CreateCommandPool()
{
QueueFamilyIndices queue_family_indices = FindQueueFamilies(physical_device_);
VkCommandPoolCreateInfo pool_info{};
pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
pool_info.queueFamilyIndex = queue_family_indices.graphics_family.value();
if (vkCreateCommandPool(device_, &pool_info, nullptr, &command_pool_) != VK_SUCCESS)
throw std::runtime_error("Failed to create graphics command pool!");
}
void VulkanEngine::CreateColorResources()
{
VkFormat color_format = swapchain_image_format_;
CreateImage(swapchain_extent_.width, swapchain_extent_.height, 1, msaa_samples_, color_format, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, color_image_, color_image_memory_);
color_image_view_ = CreateImageView(color_image_, color_format, VK_IMAGE_ASPECT_COLOR_BIT, 1);
}
void VulkanEngine::CreateDepthResources()
{
VkFormat depth_format = FindDepthFormat();
CreateImage(swapchain_extent_.width, swapchain_extent_.height, 1, msaa_samples_, depth_format, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, depth_image_, depth_image_memory_);
depth_image_view_ = CreateImageView(depth_image_, depth_format, VK_IMAGE_ASPECT_DEPTH_BIT, 1);
}
void VulkanEngine::CreateImage(uint32_t width, uint32_t height, uint32_t mip_levels, VkSampleCountFlagBits num_samples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties, VkImage& image, VkDeviceMemory& image_memory)
{
VkImageCreateInfo image_info{};
image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
image_info.imageType = VK_IMAGE_TYPE_2D;
image_info.extent.width = width;
image_info.extent.height = height;
image_info.extent.depth = 1;
image_info.mipLevels = mip_levels;
image_info.arrayLayers = 1;
image_info.format = format;
image_info.tiling = tiling;
image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
image_info.usage = usage;
image_info.samples = num_samples;
image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
if (vkCreateImage(device_, &image_info, nullptr, &image) != VK_SUCCESS)
throw std::runtime_error("Failed to create image!");
VkMemoryRequirements mem_requirements;
vkGetImageMemoryRequirements(device_, image, &mem_requirements);
VkMemoryAllocateInfo alloc_info{};
alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
alloc_info.allocationSize = mem_requirements.size;
alloc_info.memoryTypeIndex = FindMemoryType(mem_requirements.memoryTypeBits, properties);
if (vkAllocateMemory(device_, &alloc_info, nullptr, &image_memory) != VK_SUCCESS)
throw std::runtime_error("Failed to allocate image memory!");
vkBindImageMemory(device_, image, image_memory, 0);
}
uint32_t VulkanEngine::FindMemoryType(uint32_t type_filter, VkMemoryPropertyFlags properties)
{
VkPhysicalDeviceMemoryProperties mem_properties;
vkGetPhysicalDeviceMemoryProperties(physical_device_, &mem_properties);
for (uint32_t i = 0; i < mem_properties.memoryTypeCount; i++)
{
if ((type_filter & (1 << i)) && (mem_properties.memoryTypes[i].propertyFlags & properties) == properties)
return i;
}
throw std::runtime_error("Failed to find suitable memory type!");
}
void VulkanEngine::CreateFramebuffers()
{
swapchain_framebuffers_.resize(swapchain_image_views_.size(), nullptr);
for (size_t i = 0; i < swapchain_image_views_.size(); i++)
{
std::array<VkImageView, 3> attachments = {
color_image_view_,
depth_image_view_,
swapchain_image_views_[i]
};
VkFramebufferCreateInfo framebuffer_info{};
framebuffer_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
framebuffer_info.renderPass = render_pass_;
framebuffer_info.attachmentCount = static_cast<uint32_t>(attachments.size());
framebuffer_info.pAttachments = attachments.data();
framebuffer_info.width = swapchain_extent_.width;
framebuffer_info.height = swapchain_extent_.height;
framebuffer_info.layers = 1;
if (vkCreateFramebuffer(device_, &framebuffer_info, nullptr, &swapchain_framebuffers_[i]) != VK_SUCCESS)
throw std::runtime_error("Failed to create framebuffer!");
}
}
void VulkanEngine::CreateTextureImage(const std::string& texture_path)
{
int tex_width, tex_height, tex_channels;
stbi_uc* pixels = stbi_load(texture_path.c_str(), &tex_width, &tex_height, &tex_channels, STBI_rgb_alpha);
VkDeviceSize image_size = tex_width * tex_height * 4;
mip_levels_ = static_cast<uint32_t>(std::floor(std::log2(std::max(tex_width, tex_height)))) + 1;
if (!pixels)
throw std::runtime_error("Failed to load texture image!");
VkBuffer staging_buffer;
VkDeviceMemory staging_buffer_memory;
CreateBuffer(image_size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, staging_buffer, staging_buffer_memory);
void* data;
vkMapMemory(device_, staging_buffer_memory, 0, image_size, 0, &data);
memcpy(data, pixels, static_cast<size_t>(image_size));
vkUnmapMemory(device_, staging_buffer_memory);
stbi_image_free(pixels);
CreateImage(tex_width, tex_height, mip_levels_, VK_SAMPLE_COUNT_1_BIT, VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, texture_image_, texture_image_memory_);
TransitionImageLayout(texture_image_, VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, mip_levels_);
CopyBufferToImage(staging_buffer, texture_image_, static_cast<uint32_t>(tex_width), static_cast<uint32_t>(tex_height));
//transitioned to VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL while generating mipmaps
vkDestroyBuffer(device_, staging_buffer, nullptr);
vkFreeMemory(device_, staging_buffer_memory, nullptr);
GenerateMipmaps(texture_image_, VK_FORMAT_R8G8B8A8_SRGB, tex_width, tex_height, mip_levels_);
}
void VulkanEngine::CreateBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& buffer_memory)
{
VkBufferCreateInfo buffer_info{};
buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffer_info.size = size;
buffer_info.usage = usage;
buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
if (vkCreateBuffer(device_, &buffer_info, nullptr, &buffer) != VK_SUCCESS)
throw std::runtime_error("Failed to create buffer!");
VkMemoryRequirements mem_requirements;
vkGetBufferMemoryRequirements(device_, buffer, &mem_requirements);
VkMemoryAllocateInfo alloc_info{};
alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
alloc_info.allocationSize = mem_requirements.size;
alloc_info.memoryTypeIndex = FindMemoryType(mem_requirements.memoryTypeBits, properties);
if (vkAllocateMemory(device_, &alloc_info, nullptr, &buffer_memory) != VK_SUCCESS)
throw std::runtime_error("Failed to allocate buffer memory!");
vkBindBufferMemory(device_, buffer, buffer_memory, 0);
}
void VulkanEngine::TransitionImageLayout(VkImage image, VkFormat format, VkImageLayout old_layout, VkImageLayout new_layout, uint32_t mip_levels)
{
VkCommandBuffer command_buffer = BeginSingleTimeCommands();
VkImageMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = old_layout;
barrier.newLayout = new_layout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = mip_levels;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
VkPipelineStageFlags source_stage;
VkPipelineStageFlags destination_stage;
if (old_layout == VK_IMAGE_LAYOUT_UNDEFINED && new_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL)
{
barrier.srcAccessMask = 0;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
source_stage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
destination_stage = VK_PIPELINE_STAGE_TRANSFER_BIT;
}
else if (old_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && new_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)
{
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
source_stage = VK_PIPELINE_STAGE_TRANSFER_BIT;
destination_stage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
}
else
throw std::invalid_argument("unsupported layout transition!");
vkCmdPipelineBarrier(
command_buffer,
source_stage, destination_stage,
0,
0, nullptr,
0, nullptr,
1, &barrier
);
EndSingleTimeCommands(command_buffer);
}
VkCommandBuffer VulkanEngine::BeginSingleTimeCommands()
{
VkCommandBufferAllocateInfo alloc_info{};
alloc_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
alloc_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
alloc_info.commandPool = command_pool_;
alloc_info.commandBufferCount = 1;
VkCommandBuffer command_buffer;
vkAllocateCommandBuffers(device_, &alloc_info, &command_buffer);
VkCommandBufferBeginInfo begin_info{};
begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
begin_info.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(command_buffer, &begin_info);
return command_buffer;
}
void VulkanEngine::EndSingleTimeCommands(VkCommandBuffer command_buffer)
{
vkEndCommandBuffer(command_buffer);
VkSubmitInfo submit_info{};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &command_buffer;
vkQueueSubmit(graphics_queue_, 1, &submit_info, VK_NULL_HANDLE);
vkQueueWaitIdle(graphics_queue_);
vkFreeCommandBuffers(device_, command_pool_, 1, &command_buffer);
}
void VulkanEngine::CopyBufferToImage(VkBuffer buffer, VkImage image, uint32_t width, uint32_t height)
{
VkCommandBuffer command_buffer = BeginSingleTimeCommands();
VkBufferImageCopy region{};
region.bufferOffset = 0;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = 0;
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
region.imageOffset = { 0, 0, 0 };
region.imageExtent = {
width,
height,
1
};
vkCmdCopyBufferToImage(command_buffer, buffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion);
EndSingleTimeCommands(command_buffer);
}
void VulkanEngine::GenerateMipmaps(VkImage image, VkFormat image_format, int32_t tex_width, int32_t tex_height, uint32_t mip_levels)
{
// Check if image format supports linear blitting
VkFormatProperties format_properties;
vkGetPhysicalDeviceFormatProperties(physical_device_, image_format, &format_properties);
if (!(format_properties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT))
throw std::runtime_error("Texture image format does not support linear blitting!");
VkCommandBuffer command_buffer = BeginSingleTimeCommands();
VkImageMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.image = image;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
barrier.subresourceRange.levelCount = 1;
int32_t mip_width = tex_width;
int32_t mip_height = tex_height;
for (uint32_t i = 1; i < mip_levels; i++)
{
barrier.subresourceRange.baseMipLevel = i - 1;
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
vkCmdPipelineBarrier(command_buffer,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
0, nullptr,
0, nullptr,
1, &barrier
);
VkImageBlit blit{};
blit.srcOffsets[0] = { 0, 0, 0 };
blit.srcOffsets[1] = { mip_width, mip_height, 1 };
blit.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
blit.srcSubresource.mipLevel = i - 1;
blit.srcSubresource.baseArrayLayer = 0;
blit.srcSubresource.layerCount = 1;
blit.dstOffsets[0] = { 0, 0, 0 };
blit.dstOffsets[1] = { mip_width > 1 ? mip_width / 2 : 1, mip_height > 1 ? mip_height / 2 : 1, 1 };
blit.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
blit.dstSubresource.mipLevel = i;
blit.dstSubresource.baseArrayLayer = 0;
blit.dstSubresource.layerCount = 1;
vkCmdBlitImage(command_buffer,
image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1, &blit,
VK_FILTER_LINEAR);
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
vkCmdPipelineBarrier(command_buffer,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0,
0, nullptr,
0, nullptr,
1, &barrier);
if (mip_width > 1) mip_width /= 2;
if (mip_height > 1) mip_height /= 2;
}
barrier.subresourceRange.baseMipLevel = mip_levels - 1;
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
vkCmdPipelineBarrier(command_buffer,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0,
0, nullptr,
0, nullptr,
1, &barrier
);
EndSingleTimeCommands(command_buffer);
}
void VulkanEngine::CreateTextureImageView()
{
texture_image_view_ = CreateImageView(texture_image_, VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_ASPECT_COLOR_BIT, mip_levels_);
}
void VulkanEngine::CreateTextureSampler()
{
VkPhysicalDeviceProperties properties{};
vkGetPhysicalDeviceProperties(physical_device_, &properties);
VkSamplerCreateInfo sampler_info{};
sampler_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
sampler_info.magFilter = VK_FILTER_LINEAR;
sampler_info.minFilter = VK_FILTER_LINEAR;
sampler_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
sampler_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
sampler_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
sampler_info.anisotropyEnable = VK_TRUE;
sampler_info.maxAnisotropy = properties.limits.maxSamplerAnisotropy;
sampler_info.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
sampler_info.unnormalizedCoordinates = VK_FALSE;
sampler_info.compareEnable = VK_FALSE;
sampler_info.compareOp = VK_COMPARE_OP_ALWAYS;
sampler_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
sampler_info.minLod = 0.0f;
sampler_info.maxLod = static_cast<float>(mip_levels_);
sampler_info.mipLodBias = 0.0f;
if (vkCreateSampler(device_, &sampler_info, nullptr, &texture_sampler_) != VK_SUCCESS)
throw std::runtime_error("Failed to create texture sampler!");
}
void VulkanEngine::LoadModel(const std::string& obj_filename)
{
tinyobj::attrib_t attrib;
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
std::string warn, err;
if (!tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, obj_filename.c_str()))
throw std::runtime_error(warn + err);
std::unordered_map<Vertex, uint32_t, Vertex::Hash> unique_vertices{};
for (const auto& shape : shapes)
{
for (const auto& index : shape.mesh.indices)
{
Vertex vertex{};
vertex.pos = {
attrib.vertices[3 * index.vertex_index + 0],
attrib.vertices[3 * index.vertex_index + 1],
attrib.vertices[3 * index.vertex_index + 2]
};
vertex.texCoord = {
attrib.texcoords[2 * index.texcoord_index + 0],
1.0f - attrib.texcoords[2 * index.texcoord_index + 1]
};
vertex.color = { 1.0f, 1.0f, 1.0f };
if (unique_vertices.count(vertex) == 0)
{
unique_vertices[vertex] = static_cast<uint32_t>(vertices_.size());
vertices_.push_back(vertex);
}
indices_.push_back(unique_vertices[vertex]);
}
}
}
void VulkanEngine::CreateVertexBuffer()
{
VkDeviceSize buffer_size = sizeof(vertices_[0]) * vertices_.size();
VkBuffer staging_buffer;
VkDeviceMemory staging_buffer_memory;
CreateBuffer(buffer_size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, staging_buffer, staging_buffer_memory);
void* data;
vkMapMemory(device_, staging_buffer_memory, 0, buffer_size, 0, &data);
memcpy(data, vertices_.data(), (size_t)buffer_size);
vkUnmapMemory(device_, staging_buffer_memory);
CreateBuffer(buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, vertex_buffer_, vertex_buffer_memory_);
CopyBuffer(staging_buffer, vertex_buffer_, buffer_size);
vkDestroyBuffer(device_, staging_buffer, nullptr);
vkFreeMemory(device_, staging_buffer_memory, nullptr);
}
void VulkanEngine::CreateIndexBuffer()
{
VkDeviceSize buffer_size = sizeof(indices_[0]) * indices_.size();
VkBuffer staging_buffer;
VkDeviceMemory staging_buffer_memory;
CreateBuffer(buffer_size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, staging_buffer, staging_buffer_memory);
void* data;
vkMapMemory(device_, staging_buffer_memory, 0, buffer_size, 0, &data);
memcpy(data, indices_.data(), (size_t)buffer_size);
vkUnmapMemory(device_, staging_buffer_memory);
CreateBuffer(buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, index_buffer_, index_buffer_memory_);
CopyBuffer(staging_buffer, index_buffer_, buffer_size);
vkDestroyBuffer(device_, staging_buffer, nullptr);
vkFreeMemory(device_, staging_buffer_memory, nullptr);
}
void VulkanEngine::CopyBuffer(VkBuffer src_buffer, VkBuffer dst_buffer, VkDeviceSize size)
{
VkCommandBuffer command_buffer = BeginSingleTimeCommands();
VkBufferCopy copy_region{};
copy_region.size = size;
vkCmdCopyBuffer(command_buffer, src_buffer, dst_buffer, 1, ©_region);
EndSingleTimeCommands(command_buffer);
}
void VulkanEngine::CreateUniformBuffers()
{
VkDeviceSize buffer_size = sizeof(UniformBufferObject);
uniform_buffers_.resize(swapchain_images_.size());
uniform_buffers_memory_.resize(swapchain_images_.size());
for (size_t i = 0; i < swapchain_images_.size(); i++)
CreateBuffer(buffer_size, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, uniform_buffers_[i], uniform_buffers_memory_[i]);
}
void VulkanEngine::CreateDescriptorPool()
{
std::array<VkDescriptorPoolSize, 2> pool_sizes{};
pool_sizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
pool_sizes[0].descriptorCount = static_cast<uint32_t>(swapchain_images_.size());
pool_sizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
pool_sizes[1].descriptorCount = static_cast<uint32_t>(swapchain_images_.size());
VkDescriptorPoolCreateInfo pool_info{};
pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
pool_info.poolSizeCount = static_cast<uint32_t>(pool_sizes.size());
pool_info.pPoolSizes = pool_sizes.data();
pool_info.maxSets = static_cast<uint32_t>(swapchain_images_.size());
if (vkCreateDescriptorPool(device_, &pool_info, nullptr, &descriptor_pool_) != VK_SUCCESS)
throw std::runtime_error("Failed to create descriptor pool!");
}
void VulkanEngine::CreateDescriptorSets()
{
std::vector<VkDescriptorSetLayout> layouts(swapchain_images_.size(), descriptor_set_layout_);
VkDescriptorSetAllocateInfo alloc_info{};
alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
alloc_info.descriptorPool = descriptor_pool_;
alloc_info.descriptorSetCount = static_cast<uint32_t>(swapchain_images_.size());
alloc_info.pSetLayouts = layouts.data();
descriptor_sets_.resize(swapchain_images_.size());
if (vkAllocateDescriptorSets(device_, &alloc_info, descriptor_sets_.data()) != VK_SUCCESS)
throw std::runtime_error("failed to allocate descriptor sets!");
for (size_t i = 0; i < swapchain_images_.size(); i++)
{
VkDescriptorBufferInfo buffer_info{};
buffer_info.buffer = uniform_buffers_[i];
buffer_info.offset = 0;
buffer_info.range = sizeof(UniformBufferObject);
VkDescriptorImageInfo image_info{};
image_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
image_info.imageView = texture_image_view_;
image_info.sampler = texture_sampler_;
std::array<VkWriteDescriptorSet, 2> descriptor_writes{};
descriptor_writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptor_writes[0].dstSet = descriptor_sets_[i];
descriptor_writes[0].dstBinding = 0;
descriptor_writes[0].dstArrayElement = 0;
descriptor_writes[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptor_writes[0].descriptorCount = 1;
descriptor_writes[0].pBufferInfo = &buffer_info;
descriptor_writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptor_writes[1].dstSet = descriptor_sets_[i];
descriptor_writes[1].dstBinding = 1;
descriptor_writes[1].dstArrayElement = 0;
descriptor_writes[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptor_writes[1].descriptorCount = 1;
descriptor_writes[1].pImageInfo = &image_info;
vkUpdateDescriptorSets(device_, static_cast<uint32_t>(descriptor_writes.size()), descriptor_writes.data(), 0, nullptr);
}
}
void VulkanEngine::CreateCommandBuffers()
{
command_buffers_.resize(swapchain_framebuffers_.size());
VkCommandBufferAllocateInfo alloc_info{};
alloc_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
alloc_info.commandPool = command_pool_;
alloc_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
alloc_info.commandBufferCount = (uint32_t)command_buffers_.size();
if (vkAllocateCommandBuffers(device_, &alloc_info, command_buffers_.data()) != VK_SUCCESS)
throw std::runtime_error("Failed to allocate command buffers!");
for (size_t i = 0; i < command_buffers_.size(); i++)
{
VkCommandBufferBeginInfo begin_info{};
begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
if (vkBeginCommandBuffer(command_buffers_[i], &begin_info) != VK_SUCCESS)
throw std::runtime_error("Failed to begin recording command buffer!");
VkRenderPassBeginInfo render_pass_info{};
render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
render_pass_info.renderPass = render_pass_;
render_pass_info.framebuffer = swapchain_framebuffers_[i];
render_pass_info.renderArea.offset = { 0, 0 };
render_pass_info.renderArea.extent = swapchain_extent_;
std::array<VkClearValue, 2> clear_values{};
clear_values[0].color = { 0.0f, 0.0f, 0.0f, 1.0f };
clear_values[1].depthStencil = { 1.0f, 0 };
render_pass_info.clearValueCount = static_cast<uint32_t>(clear_values.size());
render_pass_info.pClearValues = clear_values.data();
vkCmdBeginRenderPass(command_buffers_[i], &render_pass_info, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(command_buffers_[i], VK_PIPELINE_BIND_POINT_GRAPHICS, graphics_pipeline_);
VkBuffer vertexBuffers[] = { vertex_buffer_ };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(command_buffers_[i], 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(command_buffers_[i], index_buffer_, 0, VK_INDEX_TYPE_UINT32);
vkCmdBindDescriptorSets(command_buffers_[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout_, 0, 1, &descriptor_sets_[i], 0, nullptr);
vkCmdDrawIndexed(command_buffers_[i], static_cast<uint32_t>(indices_.size()), 1, 0, 0, 0);
vkCmdEndRenderPass(command_buffers_[i]);
if (vkEndCommandBuffer(command_buffers_[i]) != VK_SUCCESS)
throw std::runtime_error("Failed to record command buffer!");
}
}
void VulkanEngine::CreateSyncObjects()
{
image_available_semaphores_.resize(max_frames_in_flight_);
render_finished_semaphores_.resize(max_frames_in_flight_);
in_flight_fences_.resize(max_frames_in_flight_);
images_in_flight_.resize(swapchain_images_.size(), VK_NULL_HANDLE);
VkSemaphoreCreateInfo semaphore_info{};
semaphore_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
VkFenceCreateInfo fence_info{};
fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
fence_info.flags = VK_FENCE_CREATE_SIGNALED_BIT;
for (size_t i = 0; i < max_frames_in_flight_; i++)
{
if (vkCreateSemaphore(device_, &semaphore_info, nullptr, &image_available_semaphores_[i]) != VK_SUCCESS ||
vkCreateSemaphore(device_, &semaphore_info, nullptr, &render_finished_semaphores_[i]) != VK_SUCCESS ||
vkCreateFence(device_, &fence_info, nullptr, &in_flight_fences_[i]) != VK_SUCCESS)
throw std::runtime_error("Failed to create synchronization objects for a frame!");
}
}
}
}
|
Java
|
UTF-8
| 461 | 3.171875 | 3 |
[] |
no_license
|
package TD;
public enum FruitType {
Apple,
Avocado,
Banana,
Coconut,
Grapes,
Lemon,
Orange,
Peaches,
Pear,
Pineapple;
public static FruitType getByIndex(int index) throws Exception {
return FruitType.values()[index];
}
public static void showTypes() {
for(int i = 0; i < FruitType.values().length; i++) {
System.out.println(i + " - " + FruitType.values()[i]);
}
}
}
|
C#
|
UTF-8
| 2,367 | 2.90625 | 3 |
[] |
no_license
|
using MySql.Data.MySqlClient;
using System.Collections.Generic;
using System.Data;
public class UsuarioDAO
{
MySqlCommand cmd;
MySqlDataReader dr;
public MySqlDataReader Dr
{
get
{
return dr;
}
set
{
dr = value;
}
}
public DataSet listadoUsuarios()
{
MySqlDataAdapter da = new MySqlDataAdapter("select * from usuarios", Conexion.ObtenerConexion());
DataSet ds = new DataSet();
da.Fill(ds);
Conexion.CerrarConexion();
return ds;
}
public List<Usuario> GetListaUsuariosPorNivel(int nivel)
{
List <Usuario> lista = new List<Usuario>();
Usuario nuevo;
cmd = new MySqlCommand("proc_get_usuario_nivel", Conexion.ObtenerConexion());
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("?n",MySqlDbType.Int32).Value=nivel;
cmd.Parameters["?n"].Direction = ParameterDirection.Input;
/*
* el nombre de la base de datos en la cadena tiene q estar en minuscula,
* de lo contrario se produce un error que no encuentra el procedimiento o funcion
*/
Dr = cmd.ExecuteReader();
Conexion.CerrarConexion();
while(Dr.Read())
{
int nroDoc = Dr.GetInt32(0);
string nombre = Dr.GetString(1);
string apellido = Dr.GetString(2);
int nivelID = Dr.GetInt32(3);
string password = Dr.GetString(4);
nuevo = new Usuario(nroDoc, nombre, apellido, nivelID, password);
lista.Add(nuevo);
}
return lista;
}
List<Usuario> lista;
public List<Usuario> ListaDeUsuarios()
{
lista = new List<Usuario>();
Usuario usuario;
cmd = new MySqlCommand("SELECT * FROM USUARIOS", Conexion.ObtenerConexion());
Dr = cmd.ExecuteReader();
Conexion.CerrarConexion();
while (Dr.Read())
{
int nroDoc = Dr.GetInt32(0);
string nombre = Dr.GetString(1);
string apellido = Dr.GetString(2);
int nivelID = Dr.GetInt32(3);
string password = Dr.GetString(4);
usuario = new Usuario(nroDoc, nombre, apellido, nivelID, password);
lista.Add(usuario);
}
return lista;
}
}
|
Ruby
|
UTF-8
| 559 | 3.71875 | 4 |
[] |
no_license
|
# Missão 2
# Siga a documentação da gem cpf_cnpj para criar um programa que recebe como entrada um número de cpf e em um método verifique se este número é válido.
#
# Link da documntação:
#
# https://github.com/fnando/cpf_cnpj
require "cpf_cnpj"
def validador_cpf(number)
CPF.valid?(number)
end
puts "Digite o número do CPF"
validacao = gets.chomp
result = validador_cpf(validacao)
def resultado_validacao(result)
if result == true
puts "CPF válido"
else
puts "CPF inválido"
end
end
resultado_validacao(result)
|
C
|
UTF-8
| 1,357 | 4.125 | 4 |
[] |
no_license
|
#include <stdio.h>
#include <windows.h>
int main()
{
int hours, employeeID; // Hours an employee worked and their ID
float rate, overTime; // Rate of pay and over time
float salary; // Salary to be paid
// Intro
printf("Welcome to the Salary Calculator\n\n\n");
Sleep(2000);
// Employee ID Variable
printf("Start by inputing the employee's ID# ");
scanf("%d", &employeeID);
// Program Loop
while (employeeID != -1)
{
printf("How many hours did the employee work? "); // Input for hours variable
scanf("%d", &hours);
printf("What is this employee's hourly wage? "); //Input for rate variable
scanf("%f", &rate);
if (hours <= 40)
{
// Salary if no over time worked
salary = hours * (float)rate;
printf("This employee's salary is $%.2f", salary);
}else
{
// Salary if over time worked
hours -= 40; // Finding number of overtime hours
overTime = (float)rate * 1.5; // Getting over time rate
salary = (40 * (float)rate) + (hours * (float)overTime);
printf("This employee's salary is $%.2f", salary);
}
// To restart loop
printf("\n\n\nPut in next employee's ID# or -1 to end ");
scanf("%d", &employeeID);
}
}
|
Markdown
|
UTF-8
| 11,460 | 2.609375 | 3 |
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: 'Samouczek: integracja SSO usługi Azure AD z zarządzaniem zmianami procesów'
description: Dowiedz się, jak skonfigurować Logowanie jednokrotne między Azure Active Directory i zmieniać zarządzanie procesami.
services: active-directory
author: jeevansd
manager: CelesteDG
ms.reviewer: celested
ms.service: active-directory
ms.subservice: saas-app-tutorial
ms.workload: identity
ms.topic: tutorial
ms.date: 05/07/2020
ms.author: jeedes
ms.openlocfilehash: 03c78f05566876356e4f486368dc2a5b3a29de43
ms.sourcegitcommit: f28ebb95ae9aaaff3f87d8388a09b41e0b3445b5
ms.translationtype: MT
ms.contentlocale: pl-PL
ms.lasthandoff: 03/29/2021
ms.locfileid: "92456262"
---
# <a name="tutorial-azure-active-directory-single-sign-on-sso-integration-with-change-process-management"></a>Samouczek Azure Active Directory: integracja z logowaniem jednokrotnym (SSO) przy użyciu zarządzania procesem zmiany
W tym samouczku dowiesz się, jak zintegrować zarządzanie procesem zmiany z usługą Azure Active Directory (Azure AD). W przypadku integrowania zarządzania zmianami procesów z usługą Azure AD można:
* Użyj usługi Azure AD, aby kontrolować, kto może uzyskać dostęp do zarządzania procesem zmiany.
* Zezwól użytkownikom na automatyczne logowanie się, aby zmienić zarządzanie procesem przy użyciu swoich kont usługi Azure AD.
* Zarządzaj kontami w jednej centralnej lokalizacji: Azure Portal.
Aby dowiedzieć się więcej na temat integracji aplikacji SaaS z usługą Azure AD, zobacz [Single sign-on to applications in Azure Active Directory (Logowanie jednokrotne do aplikacji w usłudze Azure Active Directory)](../manage-apps/what-is-single-sign-on.md).
## <a name="prerequisites"></a>Wymagania wstępne
Aby rozpocząć, potrzebne są następujące elementy:
* Subskrypcja usługi Azure AD. Jeśli nie masz subskrypcji, możesz uzyskać [bezpłatne konto](https://azure.microsoft.com/free/).
* Subskrypcja zarządzania procesem zmiany z włączonym logowaniem jednokrotnym (SSO).
## <a name="tutorial-description"></a>Opis samouczka
W tym samouczku skonfigurujesz i testujesz Logowanie jednokrotne usługi Azure AD w środowisku testowym.
Usługa Change Process Management obsługuje logowanie jednokrotne zainicjowane przez dostawcy tożsamości.
Po skonfigurowaniu zarządzania procesem zmiany można wymusić kontrolę sesji, co chroni eksfiltracji i niefiltrowanie danych poufnych organizacji w czasie rzeczywistym. Kontrolki sesji wykraczają poza dostęp warunkowy. [Dowiedz się, jak wymuszać kontrolę sesji za pomocą Microsoft Cloud App Security](/cloud-app-security/proxy-deployment-any-app).
## <a name="add-change-process-management-from-the-gallery"></a>Dodawanie zarządzania procesem zmiany z galerii
Aby skonfigurować integrację zarządzania procesem zmiany z usługą Azure AD, musisz dodać zarządzanie procesem zmiany z galerii do listy zarządzanych aplikacji SaaS.
1. Zaloguj się do [Azure Portal](https://portal.azure.com) przy użyciu konta służbowego lub konto Microsoft prywatnego.
1. W lewym okienku wybierz pozycję **Azure Active Directory**.
1. Przejdź do pozycji **aplikacje dla przedsiębiorstw** , a następnie wybierz pozycję **wszystkie aplikacje**.
1. Aby dodać aplikację, wybierz pozycję **Nowa aplikacja**.
1. W sekcji **Dodaj z galerii** wprowadź polecenie **Zmień zarządzanie procesem** w polu wyszukiwania.
1. Wybierz pozycję **Zmień zarządzanie procesem** w panelu wyników, a następnie Dodaj aplikację. Poczekaj kilka sekund, gdy aplikacja zostanie dodana do dzierżawy.
## <a name="configure-and-test-azure-ad-sso-for-change-process-management"></a>Skonfiguruj i przetestuj Logowanie jednokrotne usługi Azure AD na potrzeby zarządzania procesem zmiany
Skonfigurujesz i testujesz Logowanie jednokrotne usługi Azure AD za pomocą zarządzania procesem zmiany przy użyciu użytkownika testowego o nazwie B. Simon. Aby logowanie jednokrotne działało, należy ustanowić relację linku między użytkownikiem usługi Azure AD i odpowiednim użytkownikiem w ramach zarządzania procesami zmiany.
Aby skonfigurować i przetestować Logowanie jednokrotne usługi Azure AD za pomocą zarządzania procesem zmiany, należy wykonać następujące czynności:
1. **[Skonfiguruj Logowanie jednokrotne usługi Azure AD](#configure-azure-ad-sso)** , aby umożliwić użytkownikom korzystanie z tej funkcji.
1. **[Utwórz użytkownika testowego usługi Azure AD](#create-an-azure-ad-test-user)** , aby przetestować Logowanie jednokrotne w usłudze Azure AD.
1. **[Przyznaj użytkownikowi testowemu](#grant-access-to-the-test-user)** uprawnienia umożliwiające użytkownikowi korzystanie z logowania jednokrotnego w usłudze Azure AD.
1. **[Skonfiguruj zarządzanie procesem rejestracji jednokrotnej](#configure-change-process-management-sso)** w aplikacji.
1. **[Utwórz użytkownika testowego zarządzania procesem](#create-a-change-process-management-test-user)** , który jest odpowiednikiem reprezentacji usługi Azure AD użytkownika.
1. **[Przetestuj Logowanie jednokrotne](#test-sso)** , aby sprawdzić, czy konfiguracja działa.
## <a name="configure-azure-ad-sso"></a>Konfigurowanie rejestracji jednokrotnej w usłudze Azure AD
Wykonaj następujące kroki, aby włączyć logowanie jednokrotne usługi Azure AD w Azure Portal.
1. W [Azure Portal](https://portal.azure.com/)na stronie **Zarządzanie** integracją aplikacji **zarządzania procesem** wybierz pozycję **Logowanie jednokrotne** w sekcji Zarządzaj.
1. Na stronie **Wybierz metodę logowania jednokrotnego** wybierz pozycję **SAML**.
1. Na stronie **Konfigurowanie pojedynczej Sign-On przy użyciu języka SAML** wybierz przycisk ołówek dla **podstawowej konfiguracji SAML** , aby edytować ustawienia:

1. Na stronie **Konfigurowanie pojedynczego Sign-On przy użyciu języka SAML** wykonaj następujące czynności:
a. W polu **Identyfikator** wprowadź adres URL w następującym wzorcu: `https://<hostname>:8443/`
b. W polu **adres URL odpowiedzi** wprowadź adres URL w następującym wzorcu: `https://<hostname>:8443/changepilot/saml/sso`
> [!NOTE]
> Poprzedni **Identyfikator** i wartości **adresu URL odpowiedzi** nie są rzeczywistymi wartościami, których należy użyć. Aby uzyskać rzeczywiste wartości, skontaktuj się z [zespołem pomocy technicznej ds. zarządzania procesem zmiany](mailto:support@realtech-us.com) . Przydatne mogą się również okazać wzorce przedstawione w sekcji **Podstawowa konfiguracja protokołu SAML** w witrynie Azure Portal.
1. Na stronie **Konfigurowanie pojedynczej Sign-On przy użyciu języka SAML** w sekcji **certyfikat podpisywania SAML** wybierz link **pobierania** dla **certyfikatu (base64)** , aby pobrać certyfikat i zapisać go na komputerze:

1. W sekcji **Konfigurowanie zarządzania procesem** skopiuj odpowiedni adres URL lub adresy URL zgodnie z wymaganiami:

### <a name="create-an-azure-ad-test-user"></a>Tworzenie użytkownika testowego usługi Azure AD
W tej sekcji utworzysz użytkownika testowego o nazwie B. Simon w Azure Portal.
1. W lewym okienku Azure Portal wybierz pozycję **Azure Active Directory**. Wybierz pozycję **Użytkownicy**, a następnie wybierz pozycję **Wszyscy użytkownicy**.
1. Wybierz pozycję **nowy użytkownik** w górnej części ekranu.
1. We właściwościach **użytkownika** wykonaj następujące czynności:
1. W polu **Nazwa** wprowadź wartość **B. Simon**.
1. W polu **Nazwa użytkownika** wprowadź \<username> @ \<companydomain> . \<extension> . Na przykład `B.Simon@contoso.com`.
1. Wybierz pozycję **Pokaż hasło**, a następnie Zapisz wartość wyświetlaną w polu **hasło** .
1. Wybierz przycisk **Utwórz**.
### <a name="grant-access-to-the-test-user"></a>Udzielanie dostępu użytkownikowi testowemu
W tej sekcji włączysz usługę B. Simon, aby korzystać z logowania jednokrotnego na platformie Azure przez przyznanie temu użytkownikowi dostępu do zarządzania procesem zmian.
1. W Azure Portal wybierz pozycję **aplikacje dla przedsiębiorstw**, a następnie wybierz pozycję **wszystkie aplikacje**.
1. Na liście Aplikacje wybierz pozycję **Zmień proces zarządzania**.
1. Na stronie Przegląd aplikacji w sekcji **Zarządzanie** wybierz pozycję **Użytkownicy i grupy**:

1. Wybierz pozycję **Dodaj użytkownika**, a następnie **Użytkownicy i grupy** w oknie dialogowym **Dodawanie przypisania**.

1. W oknie dialogowym **Użytkownicy i grupy** wybierz pozycję **B. Simon** na liście **Użytkownicy** , a następnie kliknij przycisk **Wybierz** w dolnej części ekranu.
1. Jeśli oczekujesz dowolnej wartości roli w potwierdzeniu SAML, w oknie dialogowym **Wybierz rolę** wybierz odpowiednią rolę dla użytkownika z listy, a następnie kliknij przycisk **Wybierz** w dolnej części ekranu.
1. W oknie dialogowym **Dodawanie przypisania** wybierz pozycję **Przypisz**.
## <a name="configure-change-process-management-sso"></a>Skonfiguruj zarządzanie procesem rejestracji logowania jednokrotnego
Aby skonfigurować Logowanie jednokrotne na stronie Zarządzanie procesem zmiany, należy wysłać pobrany certyfikat base64 i odpowiednie adresy URL skopiowane z Azure Portal do [zespołu pomocy technicznej zarządzania procesem zmiany](mailto:support@realtech-us.com). Konfigurują połączenie SSO protokołu SAML, aby były poprawne po obu stronach.
### <a name="create-a-change-process-management-test-user"></a>Tworzenie użytkownika testowego zarządzania procesem zmiany
Aby dodać użytkownika o nazwie B. Simon w usłudze zarządzania procesami, należy skontaktować się z [zespołem pomocy technicznej zarządzania procesem zmiany](mailto:support@realtech-us.com) . Użytkownicy muszą być utworzeni i aktywowani przed rozpoczęciem korzystania z logowania jednokrotnego.
## <a name="test-sso"></a>Testuj Logowanie jednokrotne
W tej sekcji przedstawiono Testowanie konfiguracji logowania jednokrotnego usługi Azure AD za pomocą panelu dostępu.
Po wybraniu kafelka zarządzanie procesem w panelu dostępu należy automatycznie zalogować się do wystąpienia zarządzania procesem zmiany, dla którego skonfigurowano Logowanie jednokrotne. Aby uzyskać więcej informacji na temat panelu dostępu, zobacz [wprowadzenie do panelu dostępu](../user-help/my-apps-portal-end-user-access.md).
## <a name="additional-resources"></a>Dodatkowe zasoby
- [Samouczki dotyczące integracji aplikacji SaaS z usługą Azure Active Directory](./tutorial-list.md)
- [Czym jest dostęp do aplikacji i logowanie jednokrotne za pomocą usługi Azure Active Directory?](../manage-apps/what-is-single-sign-on.md)
- [Co to jest dostęp warunkowy w usłudze Azure Active Directory?](../conditional-access/overview.md)
- [Spróbuj zmienić zarządzanie procesem przy użyciu usługi Azure AD](https://aad.portal.azure.com/)
- [Co to jest kontrola sesji w Microsoft Cloud App Security?](/cloud-app-security/proxy-intro-aad)
- [Jak chronić zarządzanie procesami zmiany za pomocą zaawansowanej widoczności i kontrolek](/cloud-app-security/proxy-intro-aad)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.