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 |
|---|---|---|---|---|---|---|---|
Java | UTF-8 | 1,799 | 2.0625 | 2 | [] | no_license | package com.wtoutiao.auth.config;
import lombok.SneakyThrows;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
/**
* @author wulijun
* @date 2019/10/22 15:08
*/
@Primary
@Order(90)
@Configuration
@EnableAuthorizationServer
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
@SneakyThrows
protected void configure(HttpSecurity http) {
http
.formLogin()
.loginProcessingUrl("/form/token")
.and()
.authorizeRequests()
.antMatchers("/token/**").permitAll()
.anyRequest().authenticated()
.and().csrf().disable();
}
/**
* 不拦截静态资源
*
* @param web
*/
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/css/**");
}
/**
* @return PasswordEncoder
*/
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}
|
C# | UTF-8 | 4,581 | 3.15625 | 3 | [
"BSD-3-Clause"
] | permissive | using Models.Enumeration;
namespace Models
{
/// <summary>
/// Represents model class for navigation.
/// </summary>
public sealed class NavigationModel : ModelBase<NavigationModel>
{
#region Private Fields
/// <summary>
/// Gets or sets identification of the left navigation item.
/// </summary>
private NavigationLeftItem navigationLeftItemId;
/// <summary>
/// Gets or sets identification of the right navigation item.
/// </summary>
private NavigationRightItem navigationRightItemId;
/// <summary>
/// Name of the navigation.
/// </summary>
private string name;
/// <summary>
/// Style of the navigation.
/// </summary>
private string style;
#endregion
/// <summary>
/// Gets or sets identification of the left navigation item.
/// </summary>
public NavigationLeftItem NavigationLeftItemId
{
get
{
return this.navigationLeftItemId;
}
set
{
this.navigationLeftItemId = value;
this.OnPropertyChanged(() => this.NavigationLeftItemId);
}
}
/// <summary>
/// Gets or sets identification of the right navigation item.
/// </summary>
public NavigationRightItem NavigationRightItemId
{
get
{
return this.navigationRightItemId;
}
set
{
this.navigationRightItemId = value;
this.OnPropertyChanged(() => this.NavigationRightItemId);
}
}
/// <summary>
/// Gets or sets name of the navigation.
/// </summary>
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
this.OnPropertyChanged(() => this.Name);
}
}
/// <summary>
/// Gets or sets style of the navigation.
/// </summary>
public string Style
{
get
{
return this.style;
}
set
{
this.style = value;
this.OnPropertyChanged(() => this.Style);
}
}
/// <summary>
/// Override == operator.
/// </summary>
/// <param name="a">The object A.</param>
/// <param name="b">The object B.</param>
/// <returns>Return true if objects are equal, otherwise, false.</returns>
public static bool operator ==(NavigationModel a, NavigationModel b)
{
if (object.ReferenceEquals(a, null))
{
return object.ReferenceEquals(b, null);
}
return ModelBase<NavigationModel>.BaseEquals(a, b) && CompareObjects(a, b);
}
/// <summary>
/// Override != operator.
/// </summary>
/// <param name="a">The object A.</param>
/// <param name="b">The object B.</param>
/// <returns>Return true if objects aren't equal, otherwise, false.</returns>
public static bool operator !=(NavigationModel a, NavigationModel b)
{
return !(a == b);
}
/// <summary>
/// Serves as a hash function.
/// </summary>
/// <returns>A hash code for the current object.</returns>
public override int GetHashCode()
{
return this.Name.GetHashCode();
}
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// </summary>
/// <param name="obj">The object to compare with the current object.</param>
/// <returns>True if the specified object is equal to the current object otherwise, false.</returns>
public override bool Equals(object obj)
{
return this.ObjectEquals(obj) && CompareObjects(this, obj as NavigationModel);
}
/// <summary>
/// Compare objects.
/// </summary>
/// <param name="a">The object A.</param>
/// <param name="b">The object B.</param>
/// <returns>Return true if objects are equal, otherwise, false.</returns>
private static bool CompareObjects(NavigationModel a, NavigationModel b)
{
return a.Name == b.Name;
}
}
}
|
Markdown | UTF-8 | 4,286 | 2.53125 | 3 | [] | no_license | ## Advanced Event Sampling
PAPI is an API for performance counters.
Extreme scale? The bigger the machine, harder it is to gain insights.
### Current Counters
CPU counters:
* Cycles, instructions
* Cache hit/miss
* Branch predictors
* Typically aggregate counts
### Sampling
Target single program.
Periodically log performance info while running.
Statistically extrapolate to get entire program behavior.
Tradeoff between sampling rate.
### Example
Counter to overflow every 100,000 cycles.
Most hardware supports this.
Can be done with a timer instead.
### Advanced Features
Intel Precise Event-Based Sampling (PEBS)
AMD IBS.
### Low Latency Sampling
Hardware can write out data for you.
When the buffer is full, OS notifies you to handle it.
Intel PEBS supports. AMD does not.
### Hardware Profiling
* Regular intervals, random instructions are sampled and details logged.
* Register states.
* Transactional memory info.
* Load and stores
* TLB info
### Low-Skid Interrupts
Modern out-of-order processors take time to stop to handle interrupts.
Can lead to results being offset.
Low-skid support returns exact cause of overflow.
### Last branch sampling
Intel LBR (last branch record)
* Info on last 4 to 32 branches
* Basic block vectors.
### Intel PT
Record program execution traces.
* Power events
* Basic block vectors
Sizes are prohibitive.
### Linux perf_event
Support for most but not all.
Low latency sampling from PEBS.
Low-skid interrupts: set the "precise" value.
### New PAPI Interface?
Abstract everything to one "sample type" field.
If `perf_event` changes, may have to change the PAPI interface.
_Or_, could expose the `perf_event_attr` struct in PAPI. But...
1. Perf event is complex.
2. PAPI is supposed to be cross-platform.
First interface was chosen.
### Future
PAPI will output to `perf.data`. But, not well documented.
May try the lower-level interface too.
## ParLOT
Whole-program call tracing.
Mostly for debugging.
Trade-off between overhead and visibility.
Method:
* Binary instrumentation
* Compression
### Debugging
HPC bugs are **expensive**
### Goals
Always on tracing
No source-code modification
No recompilation
Dynamic instrumentation
Portability
Low overhead (runtime and storage)
### Contribution
* Use Pin, dynamic binary instrumentation tool.
* Incremental compression tool.
### Binary Instrumentation
* ParLOT:
- Every thread launch/terminate
- FUnction entry/exit
* Separate file for each thread.
Per thread:
* TID
* Function ID
* Call stack
* Current SP value
### Incremental Compression
COnventional approaches
* Written to buffer
* Sporadiacally thread blocks to compress - non-uniform latency
* Every trace element is compressed before writing to memory
* Predictable latency
### Compression
Used CRUSHER:
* Auto compression algorithm synthesis tool
* LZ followed by ZE
* High compression / low overhead
Trace entries:
* LZ is word level
* ZE is byte level
### Call-stack correction
PIN sometimes does not identify function exit.
Solution:
* Record stack-pointer
* Pop call stack until find a match
### Evaluation
Measured:
* Tracing overhead
* Tracing bandwidth
* Compression ratio
Compared with callgrind.
Compression massively reduces overhead (factor of 4).
But PIN init is still massive overhead.
Question mentioned some old work: using sequeter(?)
## Function Wrapping for HPC Tools
GOTCHA
Replacement for LD_PRELOAD
### Why wrapping?
Example of wrapping `MPI_Send()` to log extra information.
### LD_PRELOAD
Write a shared library matching functions they want to wrap.
Set LD_PRELOAD and run the application.
Dynamic linker prioritized.
### Issues
* ABI Compatibility
* "All or nothing". Has to be the entire library.
* Controlled by the person running the applicaiton, not the one building it.
Need a replacement.
### Elements
1. Name of function to wrap.
2. Wrapper function.
3. Way to call the original.
### GOTCHA
Has a C interface.
How does it work?
Libs have a global offset table. These structures are exposed and can be
modified.
### Multi-tool Support
GOTCHA supports multiple wrappers.
Can have priority, if order matters.
### Build
You can always build it into your application, even if you don't use it.
|
Java | UTF-8 | 634 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | package fr.univnantes.termsuite.ui.util.jface;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
public class IntegerValidator extends NumberValidator {
public IntegerValidator() {
super();
}
public IntegerValidator(Number min, Number max) {
super(min, max);
}
@Override
public IStatus validate(Object value) {
String s = String.valueOf(value);
if (s.matches("\\d+")) {
String msg = super.validate(Integer.parseInt(s));
return msg != null ? ValidationStatus.error(msg) : ValidationStatus.ok();
}
return ValidationStatus.error("Not a number");
}
}
|
PHP | UTF-8 | 775 | 3 | 3 | [
"MIT"
] | permissive | <?php
namespace App;
use Nette\Application\UI;
/**
* Komponenta pro demonstraci hierarchické struktury.
*/
class BoxControl extends UI\Control
{
/**
* Metody render() je automaticky volaná při vykreslování pomocí Latte makra {control}
*/
public function render()
{
// Stejně jako v presenteru je i v komponentě k dispozici šablona pomocí $this->template.
// Navíc je ale potřeba ručně nastavit cestku k šabloně a zavolat metodu render()
$this->template->setFile(__DIR__ . '/BoxControl.latte');
$this->template->render();
}
/**
* Továrnička na "foo". Bude automaticky zavolaná při pokusu o získání komponenty "foo".
*
* @return BoxControl
*/
protected function createComponentFoo()
{
return new BoxControl();
}
}
|
Java | UTF-8 | 723 | 2.375 | 2 | [] | no_license | package com.example.supermercadotico.Users;
import com.example.supermercadotico.Controlador;
public class Gerente extends Usuario{
public Gerente(String nombre, String contrasena, String direccion) {
super(nombre, contrasena, direccion);
}
public void registarEmpleado(String nombre, String id, String contrasena, String direccion, String edad)
{
Empleado empleado = new Empleado(nombre,contrasena,edad,direccion,id,controlador);
}
public void eliminarEmpleado(Empleado empleado)
{
controlador.eliminarEmpleado(empleado); //TODO: PARA todo cambio se necesita accesar la base de datos para actualizar
empleado.setEstado(EstadoDeEmpleado.DESPEDIDO);
}
}
|
Ruby | UTF-8 | 820 | 3.140625 | 3 | [] | no_license | require_relative 'menu'
require_relative 'order'
class Takeaway
attr_reader :menu, :order, :order_klass, :menu_name
def initialize(menu_klass: Menu, order_klass: Order, menu_name: :italian)
@menu = menu_klass.new(menu_name: menu_name)
@order_klass = order_klass
@order = order_klass.new (menu_instance: menu)
end
def show_menu
menu.show
end
def place_order(item, qty = 1)
@order ||= order_klass.new(menu_instance: menu)
return 'Please order 1 or more items' if qty < 1
return 'This item is not on the menu' unless available? item
order.add(item, qty)
end
def show_order
order.overview
end
def checkout_order(price = 0)
@oder.checkout(price)
end
def reset_order
order.reset
end
private
def available? item
menu.listed? item
end
end
|
JavaScript | UTF-8 | 2,605 | 3.828125 | 4 | [] | no_license | //06--functional spec
function doubler(n){
return n*2;
}
function map(arr, func){
var arr2=[];
for (i=0; i<arr.length; i++){
arr2.push(func(arr[i]));
}
return arr2;
}
function filter(arr, func){
var arr2=[];
for (var i=0; i<arr.length; i++){
if (func(arr[i])==true){
arr2.push(arr[i]);
}
}
return arr2;
}
var contains=function(arr, target){
for (key in arr){
if (arr.hasOwnProperty(key)){
if (arr[key]==target){
return true;
}
}
}
return false;
}
var countWords=function(str){
return str.split(" ").length;
}
var reduce=function(arr, init, func){
var sum=init;
for (var i=0; i<arr.length; i++){
res=func(res, arr[i]);
}
return res;
}
var countWordsInReduce=function(cur, str){
return cur+countWords(str);
}
var sum=function(arr){
var s=0;
s=reduce(arr, s, function(a,b){
return a+b;
});
return s;
}
var every=function(arr, func){
if (arr.length==0){
return true;
}
var res=true;
return reduce(arr, true, function(a,b){
return a&&b;
})
}
var any = function ( arr, checkTrue){
if (arr.length==0){
return false;
}
arr2=arr.map(checkTrue);
return reduce(arr2, false, function(a,b){
return a||b;
});
}
//07-prototypal inheritance
function Mammal(name){
this.name=name;
this.offspring=[];
}
Mammal.prototype.sayHello=function(){
return "My name is"+ this.name +"!";
}
Mammal.prototype.haveBaby=function(){
var child=Object.create(Mammal.prototype);
child.name="Baby"+this.name;
this.offspring.push([child]);
return child;
}
function Cat(name, color){
Mammal.call(this, name); //call func
this.color=color;
}
Cat.prototype=Object.create(Mammal.prototype);
Cat.prototype.constructor=Cat;
Cat.prototype.haveBaby=function(color){
var child=new Cat("Baby"+ this.name, color);
this.offspring.push(child);
return child;
}
//08 recursion
function factorialIterative(n){
var res=1;
for (var i=1; i<n; i++){
res*=1;
}
return res;
}
function factorial(n){
if (n==0){
return 1;
}
return n*factorial(n-1);
}
function fib(n){
if (n===0 || n===1){
return 1;
}
return fib(n-1)+fib(n-2)
}
function type(val){
return Object.prototype.toSpring.call(val).slice(8,-1);
}
function stringify(val){
if (type(val)==="String"){
return "'"+String(val)+"'";
}
else if (type(val)==="Array"){
var res=[];
for (var i=0; i<val.length; i++){
res.push(stringify(arr[i]));
}
return "["+res.join(",")+"]";
}
else if (type(val)==="Object"){
var res=[];
for (var key in val){
res.push('"'+key+'"'+":"+stringify(val[key]))
}
return "{"+res.join(",")+"}";
}
else{
return String(val);
}
}
|
Python | UTF-8 | 492 | 3.359375 | 3 | [] | no_license | import os
import zipfile
directory = raw_input("Enter the directory path to zip ")
dir_zip = zipfile.ZipFile('zip_directory.zip', 'w')
if os.path.isdir(directory):
for folder, subfolders, files in os.walk(directory):
for file in files:
dir_zip.write(os.path.join(folder, file), os.path.relpath(os.path.join(folder, file), directory),\
compress_type = zipfile.ZIP_DEFLATED)
dir_zip.close()
print("{} zipped successfully".format(directory))
else:
print("Directory not found")
|
Python | UTF-8 | 735 | 2.609375 | 3 | [
"MIT"
] | permissive | import os
import sys
import matplotlib.pyplot as plt
import numpy as np
# ------------------------------------------------------------
# Input
output = os.path.join(sys.argv[1], '')
# ------------------------------------------------------------
plot_dir = output+'plot/'
if not os.path.exists(plot_dir):
os.makedirs(plot_dir)
data = np.loadtxt(output+'output/spectrum.dat')
wavelength = data[:, 0]
flux = data[:, 1]
plt.plot(wavelength, flux, ls='-')
plt.xlim(np.amin(wavelength), np.amax(wavelength))
plt.ylim(1.e-27, 1.e-11)
plt.xscale('log')
plt.yscale('log')
plt.xlabel('Wavelength (um)', fontsize=12)
plt.ylabel('Flux (W/m$^2$/um)', fontsize=12)
plt.savefig(plot_dir+'spectrum_emission.pdf', bbox_inches='tight')
|
C++ | UTF-8 | 1,819 | 3.390625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
class Graph{
public:
int v;
list<int> *adj;
Graph(int v);
void printSCC();
void addEdge(int v,int w);
void fillOrder(int v,bool visited[],stack<int> &st);
void dfsutil(int v,bool visited[]);
Graph getTranspose();
};
Graph::Graph(int v){
this->v=v;
adj=new list<int>[v];
}
void Graph::addEdge(int v,int w){
adj[v].push_back(w);
}
Graph Graph::getTranspose(){
Graph gT(v);
for(int i=0;i<v;i++){
for(auto it=adj[i].begin();it!=adj[i].end();it++)
gT.adj[*it].push_back(i);
}
return gT;
}
void Graph::dfsutil(int v,bool visited[]){
visited[v]=true;
cout<<v<<" ";
for(auto i=adj[v].begin();i!=adj[v].end();i++){
if(!visited[*i])
dfsutil(*i,visited);
}
}
void Graph::fillOrder(int v,bool visited[],stack<int> &st){
visited[v]=true;
for(auto i=adj[v].begin();i!=adj[v].end();i++){
if(!visited[*i])
fillOrder(*i,visited,st);
}
st.push(v);
}
void Graph::printSCC(){
bool visited[v];
stack<int> st;
for(int i = 0; i < v; i++)
visited[i] = false;
for(int i=0;i<v;i++)
if(!visited[i])
fillOrder(i,visited,st);
Graph gT=getTranspose();
for(int i = 0; i < v; i++)
visited[i] = false;
while(!st.empty()){
int v=st.top();
st.pop();
if(!visited[v]){
gT.dfsutil(v,visited);
cout<<endl;}
}
}
int main()
{
// Create a graph given in the above diagram
Graph g(5);
g.addEdge(1, 0);
g.addEdge(0, 2);
g.addEdge(2, 1);
g.addEdge(0, 3);
g.addEdge(3, 4);
cout << "Following are strongly connected components in "
"given graph \n";
g.printSCC();
return 0;
}
|
Markdown | UTF-8 | 1,719 | 3.890625 | 4 | [
"MIT"
] | permissive | ---
layout: post
title: "Python学习日记(1)"
excerpt: "1.Python之“可变”的tuple 2.关于缩进"
categories: [Python]
comments: true
image:
feature:
---
## 1.Python之“可变”的tuple
前面我们看到了tuple一旦创建就不能修改。现在,我们来看一个“可变”的tuple:
t = ('a', 'b', ['A', 'B'])
注意到 t 有 3 个元素:'a','b'和一个list:['A', 'B']。list作为一个整体是tuple的第3个元素。list对象可以通过 t[2] 拿到:
L = t[2]
然后,我们把list的两个元素改一改:
L[0] = 'X'
L[1] = 'Y'
再看看tuple的内容:
>>> print t
('a', 'b', ['X', 'Y'])
不是说tuple一旦定义后就不可变了吗?怎么现在又变了?
别急,我们先看看定义的时候tuple包含的3个元素:

当我们把list的元素'A'和'B'修改为'X'和'Y'后,tuple变为:

表面上看,tuple的元素确实变了,但其实变的不是 tuple 的元素,而是list的元素。
tuple一开始指向的list并没有改成别的list,所以,tuple所谓的“不变”是说,tuple的每个元素,指向永远不变。即指向'a',就不能改成指向'b',指向一个list,就不能改成指向其他对象,但指向的这个list本身是可变的!
理解了“指向不变”后,要创建一个内容也不变的tuple怎么做?那就必须保证tuple的每一个元素本身也不能变。
## 2.关于缩进
缩进请严格按照Python的习惯写法:4个空格,不要使用Tab,更不要混合Tab和空格,否则很容易造成因为缩进引起的语法错误。
|
Python | UTF-8 | 1,461 | 2.953125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
# キーポイント性質比較用
import numpy as np
import cv2
import sys
# 引数の取得
argc = len(sys.argv)
argv = sys.argv
# 既定ファイルパス(エディタ実行用)
im_path = 'images/labo/IMG_5894.jpg'
# コマンドライン入力用(パスが上書きされる)
if argc == 2:
im_path = argv[1]
if not os.path.isfile(im_path):
print "given file(s) don't exist."
sys.exit()
# グレースケール画像を読み込む
im1 = cv2.imread(im_path, 0)
im1_gray = cv2.resize(im1, (800,600))
# SIFT detector
sift = cv2.SIFT()
kp_sift, des_sift = sift.detectAndCompute(im1_gray, None)
# SURF detector
surf = cv2.SURF()
surf.hessianThreshold = 1000
kp_surf, des_surf = surf.detectAndCompute(im1_gray, None)
# FAST detector
fast = cv2.FastFeatureDetector()
kp_fast = fast.detect(im1_gray, None)
print "keypoints(sift): {0}".format(len(kp_sift))
print "keypoints(surf): {0}".format(len(kp_surf))
print "surf.hessianThreshold: {0}".format(surf.hessianThreshold)
print "keypoints(fast): {0}".format(len(kp_fast))
im_result_sift = cv2.drawKeypoints(im1_gray, kp_sift, None, (255,0,0), 4)
im_result_surf = cv2.drawKeypoints(im1_gray, kp_surf, None, (255,0,0), 4)
im_result_fast = cv2.drawKeypoints(im1_gray, kp_fast, color=(0,0,255))
cv2.imshow('image_sift', im_result_sift)
cv2.imshow('image_surf', im_result_surf)
cv2.imshow('image_fast', im_result_fast)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
PHP | UTF-8 | 2,956 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Family;
use App\TableData;
class RecurringExpenseTables
{
/**
* @var RecurringExpense
*/
private $recurringExpense;
public function __construct(RecurringExpense $recurringExpense)
{
$this->recurringExpense = $recurringExpense;
}
public function monthlyAmountsByYearTableData()
{
$rowLabels = [
__('months.jan'),
__('months.feb'),
__('months.mar'),
__('months.apr'),
__('months.may'),
__('months.jun'),
__('months.jul'),
__('months.aug'),
__('months.sep'),
__('months.oct'),
__('months.nov'),
__('months.dec'),
__('recurring-expenses.total'),
];
$columnLabels = [''];
$columnData = [];
$instances = $this->recurringExpense->recurringExpenseInstances;
$instances = $instances->filter(function($instance, $key) {
return optional($instance->cashFlowPlan)->id;
});
if (!$instances->count()) {
return false;
}
$cfps = $instances->pluck('cashFlowPlan');
$years = $cfps->pluck('year')->unique()->sort();
$x = 0;
foreach ($years as $year) {
$columnLabels[] = $year;
$thisYearsTotal = 0;
$thisYearsCfps = $cfps->filter(function($cfp, $key) use ($year) {
return $cfp->year === $year;
});
foreach (range(1, 12) as $month) {
$thisMonthsCfp = $thisYearsCfps->firstWhere('month', $month);
if (!$thisMonthsCfp) {
$columnData[$x][] = '';
continue;
}
$thisMonthsInstance = $instances->firstWhere('cash_flow_plan_id', $thisMonthsCfp->id);
$thisMonthsActual = ($thisMonthsInstance) ? $thisMonthsInstance->actual : 0;
$columnData[$x][] = ($thisMonthsActual) ? \App\formatCurrency($thisMonthsActual, true) : '';
$thisYearsTotal += $thisMonthsActual;
}
$columnData[$x][] = \App\formatCurrency($thisYearsTotal, true);
$x++;
}
$tData = new TableData();
$tData->caption(__('recurring-expenses.recurring-expense-by-month', ['name' => $this->recurringExpense->name]))
->bordered(true)
->striped(true)
->highlightColumnHeaders(true)
->highlightRowHeaders(true)
->hoverable(true)
->responsive(true)
->addTableClass('text-right');
$tData->setHeaders($columnLabels);
for ($y = 0; $y < 13; $y++) {
$row = [$rowLabels[$y]];
for ($z = 0; $z < $x; $z++) {
$row[] = $columnData[$z][$y];
}
$tData->addRow($row);
}
return $tData;
}
}
|
PHP | UTF-8 | 1,966 | 2.90625 | 3 | [] | no_license | <?php
//入力チェック(受信確認処理追加)
if(
!isset($_POST["newsId"]) || $_POST["newsId"]=="" ||
!isset($_POST["newsTitle"]) || $_POST["newsTitle"]==""||
!isset($_POST["newsContents"]) || $_POST["newsContents"]==""
){
exit('ParamError');
}
//1. POSTデータ取得
$newsId = $_POST["newsId"];
$newsTitle = $_POST["newsTitle"];
$newsContents = $_POST["newsContents"];
//2. DB接続します(エラー処理追加)
include("functions.php");
$pdo = db_conn();
//3.データ登録SQL作成。bindValueさんはSQLインジェクション対策だよ。
$stmt = $pdo->prepare("UPDATE natalie_news_table SET news_id=:id, news_title=:title, news_contents=:contents WHERE news_id=:id");
$stmt->bindValue(':id', $newsId);
$stmt->bindValue(':title', $newsTitle);
$stmt->bindValue(':contents', $newsContents);
$status = $stmt->execute();
//4.データ登録処理後
$view = "";
if($status==false){
errorMsg($stmt);
}else{
$view .= '<p>ニュースID:'.$newsId.'<br>';
$view .= "タイトル:".$newsTitle.'<br>';
$view .= "のDB更新が完了したよ</p>";
}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
以下の内容でDBの更新が完了しました。
<form method="post" action="update.php">
<div class="jumbotron">
<fieldset>
<legend>ニュース記事の編集</legend>
<label>ID:<input type="text" name="newsId" value="<?= $newsId?>" readonly></label><br>
<label>記事:<textArea name="newsTitle" rows="1" cols="100" readonly><?= $newsTitle?></textArea></label><br>
<label>記事:<textArea name="newsContents" rows="10" cols="100" readonly><?= $newsContents?></textArea></label><br>
</fieldset>
</div>
</form>
<br>
<a href="menu.html">メニューに戻る</a>
</body>
</html> |
Markdown | UTF-8 | 37,134 | 3.484375 | 3 | [] | no_license | # Introduction
This is a small project I have thrown together to help students at LYIT with their exams in **Object Orientated Programming 3**. This tutorial deals with Java code, which is what is being used for the exam. If you are interested in Processing, check out my other projects [Asteroids Game](https://github.com/florianmoss/asteroidsGame-Java-Processing) and [Maze Solver](https://github.com/florianmoss/mazeSolver-Java-Processing). These will deal with an actual implementation whereas the goal for this project is to help you understand the underlying concepts. Feel free to share this resource with your friends and copy from it whenever you need it.

I will go through the following chapters in this tutorial:
1. [ArrayLists and Methods](#arraylists-and-methods)
2. [toString + enhanced for-Loop](#tostring--enhanced-for-loop)
3. [try-catch-Exceptions](#try-catch-exceptions)
4. [throw + user-Defined Exceptions](#throw--user-defined-exceptions)
5. [Composition](#composition)
6. [Inheritance](#inheritance)
7. [Override](#override)
8. [Polymorphism](#polymorphism)
9. [Overloading](#overloading)
10. [Wrapper Classes](#wrapper-classes)
11. [instanceOf Operator (not used in code)](#instanceof-operator-not-used-in-code)
12. [Casting](#casting)
13. [Abstract Classes](#abstract-classes)
14. [equals()](#equals)
15. [Interfaces](#interfaces)
16. [Comparable + compareTo()](#comparable--compareto)
17. [sort()](#sort)
18. [Comparator + compare()](#comparator--compare)
19. [Bubble Sort](#bubble-sort)
20. [Selection Sort](#selection-sort)
21. [Sequential Search](#sequential-search)
22. [Binary Search](#binary-search)
# ArrayLists-and-Methods
[Official Documentation](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html)
An ArrayList is a more complex Array. An array needs to be initialised with a fixed size, whereas an ArrayList has the capability to grow and shrink as needed. Unfortunately an ArrayList can't directly store primitive datatypes, but we can solve that with [Wrapper Classes](#wrapper-classes). Arrays are also embedded in the java.lang package and therefore doesn't neeed to be imported. To access functionality of ArrayLists we need to import it with:
```java
import java.util.ArrayList;
```
**Syntax: (declare and initialise)**
```java
ArrayList<Object> identifier = new ArrayList<Object>(size);
```
The size doesn't need to be declared, you can leave this empty in most cases.
Or you can declare an ArrayList first and then initialise:
```java
ArrayList<Object> identifier;
identifier = new ArrayList<Object>(size);
```
**Commonly used methods**
- Retrieve an object at position i:
```java
list.get(i) // Returns object
```
- Add an object, add an object at position:
```java
list.add(i) // Adds object i
list.add(index, i) // Adds object i at index
```
- Empty the ArrayList:
```java
list.clear() // Clears the ArrayList
```
- Remove an object, remove an object at position:
```java
list.remove(i) // remove object i
list.remove(index) // remove object at index
```
- Index of Object:
```java
list.indexOf(i) // Returns index of object i or -1 if not found
```
# toString + enhanced for-Loop
### toString()
What would happen if you would execute the following in Java?
```java
System.out.println(object);
```
You would get the hashCode that looks something like this:
```java
Console: @66fee51b
```
This is obviusly not very helpful for us, yet. What we want is to retrieve information from an object in a readable form, that's why we need to implement a method, the toString() method. As the name suggests, it formats an object to a string.
Let's look at a quick example from [Human.java](https://github.com/florianmoss/learn-oop-java/blob/master/Human.java):
```java
public String toString(){
return "Human{age="+getAge()+", name="+getName()+", armLeft="+armLeft+", armRight="+armRight+
", legLeft="+legLeft+", legRight="+legRight+", familyMembers="+familyMembers;
}
```
What would be the output for the following object?
```java
florian = new Human();
System.out.println(florian.toString()); // long way
System.out.println(florian); // short way
```
Hint: You will need to look at the [Existence Class](https://github.com/florianmoss/learn-oop-java/blob/master/Existence.java), the [Human Class](https://github.com/florianmoss/learn-oop-java/blob/master/Human.java) and the [Genitals Class](https://github.com/florianmoss/learn-oop-java/blob/master/Genitals.java).
Output:
```java
Human{age=0, name=none, armLeft=0 ,1 ,2 ,3 ,4, armRight=0 ,1 ,2 ,3 ,4, legLeft=0 ,1 ,2 ,3 ,4, legRight=0 ,1 ,2 ,3 ,4, familyMembers=[]
```
If you got it right, great you understood everything, move on! If not, here is the explanation..
1. **Start at the beginning**
We invoked the toString() Method for the Object **florian**. The object **florian** is a **human**, therefore we have to check the [Human Class](https://github.com/florianmoss/learn-oop-java/blob/master/Human.java) and look for the toString()-Method.
Go open it, and look at it.
2. **What now? Well there is a lot to take in, isn't it? So let's break it up**:
```java
"Human{age="+getAge()+",
```
The first part is easy enough, it returns a String, the second part invokes the **getAge()**-Method. Is there a **getAge()**-Method in Human?
No there isn't, so where can it be? In the [Existence Class](https://github.com/florianmoss/learn-oop-java/blob/master/Existence.java) of course! The human inheritated it from Existence. So the **getAge()**-Method returns an int value. What is the age? We have to check the constructor for that:
```java
florian = new Human();
```
Is there an empty constructor in the [Human Class](https://github.com/florianmoss/learn-oop-java/blob/master/Human.java)? Yes, great. The empty constructor chains to the second constructor, which then invokes the super class constructor. Constructor-inception basically.
In the end **florian** gets initialised with the age == 0.
Therefore **getAge()** returns 0. Exactly the output:
```java
Human{age=0, ...
```
3. **Now we have to break up the Genitals armLeft, armRight, legLeft and LegRight**
The first genital is armLeft, so we should check the [Arm Class](https://github.com/florianmoss/learn-oop-java/blob/master/Arm.java).
Go, have a look! Did you find a toString()-Method?
No, good. Where else can we check? Oh, yes sure the Arm inherits from the [Genitals Class](https://github.com/florianmoss/learn-oop-java/blob/master/Genitals.java).
Oh, there seems to be a toString()-Method!
```java
@Override
public String toString(){
String s = "";
for(Integer i : genitals){
s += " ,"+i;
}
return s.substring(2);
}
```
Looks complicated, but it is actually quite simple.
It loops through the amount of genitals of a genital and returns them without a leading **,** (This is what .substring() does).
Now it's quite easy, we have to check the constructor and see with how many genitals the leftArm has been initialised.
You have done that earlier with the age, it's the same principle.
And from here on the same concept applies to the other genitals.
4. **Putting it all together**
When you put all the partial outputs together, you will get exactly this:
Output:
```java
Human{age=0, name=none, armLeft=0 ,1 ,2 ,3 ,4, armRight=0 ,1 ,2 ,3 ,4, legLeft=0 ,1 ,2 ,3 ,4, legRight=0 ,1 ,2 ,3 ,4, familyMembers=[]
```
Not too bad, wasn't it!
### enhanced for-Loop
[Official Documentation](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html)
The enhanced for-Loop has the same functionality that your regular for-loop. With some small differences.
```java
for(int i=0; i<10; i++)
System.out.print(i+ " ");
Output: 0 1 2 3 4 5 6 7 8 9
```
This is your regular for-Loop, nothing really special.
Let's look at the enhanced for-Loop:
```java
for(int i : new int[10])
System.out.print(i+ " ");
Output: 0 0 0 0 0 0 0 0 0 0
```
The syntax is slightly different as you can see:
```java
for(type o : IterableObject)
System.out.print(o+ " ");
```
We can basically iterate through everything that allows us to iterate through, 2 concepts you definitely know of, right?
**Arrays and ArrayLists**. The enhanced for-loop allows us to iterate through all elements that are stored in an iterable object. Simple as that. The benefit is that you don't have to define the size or think about **OutOfBoundExceptions**, you can savely iterate through all elements. The drawback is that you can't return the position.
Maybe another example:
```java
ArrayList<Integer> oneToTen = new ArrayList<Integer>(); // ArrayList that stores Integer objects
for(int i=1; i<11; i++) // Store the values 1-10 in oneToTen ArrayList
oneToTen.add(i);
for(Integer i : oneToTen) // iterate through all objects in oneToTen of the type Integer
System.out.print(i+ " ");
Output: 1 2 3 4 5 6 7 8 9 10
```
# try-catch-Exceptions
[Official Documentation](https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html)
### What is an exception?
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.
We have already seen a few of these, let's say you have the following:
```java
int[] numbers = {1, 2, 3}
System.out.println(numbers[3]); // Leads into OutOfBound error
```
To prevent this you can use someting called try-catch. The name basically says what it does:
### Implementation of try-catch
```java
int[] numbers = {1, 2, 3}
try{
System.out.println(numbers[3]); // Leads into IndexOutOfBoundsException error
}catch(IndexOutOfBoundsException e){
System.out.println(e.getMessage());
}
```
In english: Dear compiler, please **TRY** to compile the line:
_ System.out.println(numbers[3]);_
If you find an error saying **IndexOutOfBoundsException**, go and execute what follows in the curly brackets.
Simple as that. You can also stack **catches**, for example:
```java
int[] numbers = {1, 2, 3}
try{
System.out.println(numbers[3]); // Leads into IndexOutOfBoundsException error
}catch(IndexOutOfBoundsException e){
System.out.println(e.getMessage());
}catch(IOException e){
// do nothing
}
```
Just remember, the moment you hit an error in your try-block, you will immediately jump into the catch-block and nothing else will be executed from try.
Most exceptions will be caught this way.
# throw + user-Defined Exceptions
This part will go further than what is needed for your exam, but you will learn some important things.
### the _throws_ Keyword
Every Method or Constructor can **throw** an Exception. This means, when you execute the code and an event occurs that you don't want to occur, you can go and say "Hey Java, throw an exception here and stop this non-sense!". One simple example would be a human with a negative age, we surely don't want that to happen. Go ahead and open the [Human Class](https://github.com/florianmoss/learn-oop-java/blob/master/Human.java).
```java
public Human() throws Exception{
this(5, 5, 5, 5, 0, "none");
}
public Human(int fingersLeft, int fingersRight, int toesLeft, int toesRight, int age, String name) throws Exception{
super(age, name);
this.armLeft = new Arm(fingersLeft);
this.armRight = new Arm(fingersRight);
this.legLeft = new Leg(toesLeft);
this.legRight = new Leg(toesRight);
this.familyMembers = new ArrayList<String>();
}
```
When you look closely at the Constructor signature you can spot the **throws Exception** part. We know now that our constructors can throw exceptions, but we don't know what exactly they are throwing, right? So we have to check our [Existence Class](https://github.com/florianmoss/learn-oop-java/blob/master/Existence.java).
```java
public Existence(int age, String name) throws Exception{
if(age>-1){
this.age = age;
this.name = name;
} else throw new AgeException();
}
```
What can we observe? We also have the **throws Exception** in the Constructor signature, that's obviuous. What else?
if the age is -1 or smaller the Constructor will throw a new AgeException()! So we have an event that we don't want to happen, and we go ahead and say: **"Hey Java, stop this non-sense and tell me what non-sense occured!"**.
At this point we don't really know what AgeException is, so let's check it out: [AgeException.java](https://github.com/florianmoss/learn-oop-java/blob/master/AgeException.java)
```java
public class AgeException extends java.lang.Exception{
public AgeException(){
}
public String getMessage(){
return "Age is not valid";
}
}
```
Looks like not much is going on actually, that's a relief isn't it?! It's a class that inherits from the java.lang.Exception package with an empty constructor and only one method. And the method only returns a String saying "Age is not valid."
So our constructor from the Existence class creates a new AgeException object of the type Exception and throws it. Think about it in a literal sense, when something is thrown, it needs to be caught as well, doesn't it? So where do we catch it?
Upon calling the constructor of course.
So where do we evoke the constructor from the [Existence Class](https://github.com/florianmoss/learn-oop-java/blob/master/Existence.java)? Right, in the [Human Class](https://github.com/florianmoss/learn-oop-java/blob/master/Human.java).
Our first instinct would be to write this in the Human class:
```java
public Human(){
try{
this(5, 5, 5, 5, 0, "none");
} catch(Exception e){
System.out.println(e.getMessage());
}
}
public Human(int fingersLeft, int fingersRight, int toesLeft, int toesRight, int age, String name) {
try{
super(age, name);
} catch(Exception e){
System.out.println(e.getMessage());
}
this.armLeft = new Arm(fingersLeft);
this.armRight = new Arm(fingersRight);
this.legLeft = new Leg(toesLeft);
this.legRight = new Leg(toesRight);
this.familyMembers = new ArrayList<String>();
}
```
Because we want to catch the thrown Exception immediately. I would encourage you to download the files and change the code in the human.java constructor to the above. Try it and see what happens!
**You had a compiler issue. But why is that?**
Whenever we invoke a super() constructor, more about that in the [Inheritance](#inheritance) section, we are forced to invoke the super() as the first line of code, so we can't use the **try{** -block. What a shame, the most intuitive solution doesn't work.
So what other option do we have? We can **throw** the exception even further down, so let's try that:
```java
public Human() throws Exception{
this(5, 5, 5, 5, 0, "none");
}
public Human(int fingersLeft, int fingersRight, int toesLeft, int toesRight, int age, String name) throws Exception{
super(age, name);
this.armLeft = new Arm(fingersLeft);
this.armRight = new Arm(fingersRight);
this.legLeft = new Leg(toesLeft);
this.legRight = new Leg(toesRight);
this.familyMembers = new ArrayList<String>();
}
```
Now, everytime the human constructor is being called, we will have to catch the exception. And where do we create a human? In the [Main Class](https://github.com/florianmoss/learn-oop-java/blob/master/main_starter.java) of course.
This is how it's gonna look:
```java
try{
max = new Human(5, 5, 5, 5, -2, "Max");
System.out.println(max);
}catch(Exception e){
System.out.println(e.getMessage());
}
```
When we run it, we will see the expected output.
Make sure you really understand what is happening, this is a bit tricky to understand at first, especially with throwing exceptions through 2 constructors.
# Composition
[Another explanation](https://www.journaldev.com/1325/composition-in-java-example)
Composition is a fancy word for Objects in Objects. Sounds a bit weird at first, but it's super simple, I promise!
Let's look at an example first:
```java
public class Human extends Existence{
private Arm armLeft;
private Arm armRight;
private Leg legLeft;
private Leg legRight;
....
```
As you can see, instead of having just primitive datatypes as fields, we now have objects as a field. This is composition.
Composition is also knows as a **has-a-Relationship**.
A human has an arm, or two at best.
A human has two legs.
A book has-a-Author
A computer has-a-motherboard
And so forth.
The same way you would write your **getter and setter - Methods** you can also write these for objects:
```java
// Gain access to composition objects
public Arm getLeftArm(){
return armLeft;
}
public Arm getRightArm(){
return armRight;
}
public Leg getLeftLeg(){
return legLeft;
}
public Leg getRightLeg(){
return legRight;
}
```
This way you can access all fields and methods from the Arm and Leg objects within your human.
Some examples you can find [here](https://github.com/florianmoss/learn-oop-java/blob/master/main_starter.java).
For the constructor we have a variety of options:
**Option 1 - call the constructor with primitive Datatypes - also my implementation**
```java
public Human(int fingersLeft, int fingersRight, int toesLeft, int toesRight, int age, String name) {
super(age, name);
this.armLeft = new Arm(fingersLeft); // initialise the object here
this.armRight = new Arm(fingersRight);
this.legLeft = new Leg(toesLeft);
this.legRight = new Leg(toesRight);
this.familyMembers = new ArrayList<String>();
}
```
Creating a human will work this way:
```java
Human h1 = new Human(5, 5, 5, 5, 0, "Test");
Human h2 = new Human();
```
**Option 2 - call the constructor with Objects - more Elegant way**
```java
public Human(Arm armLeft, Arm armRight, Leg legLeft, Leg legRight, int age, String name) {
super(age, name);
this.armLeft = armLeft;
this.armRight = armRight;
this.legLeft = legLeft;
this.legRight = legRight
this.familyMembers = new ArrayList<String>();
}
```
Creating a human will work this way:
```java
Human h1 = new Human(new Arm(5), new Arm(5), new Leg(5), new Leg(5), 0, "Test");
```
**Choose one of the two options and be consistent with it, it doesn't matter how you do choose to do it (Except when your boss tells you to do it one way).**
# Inheritance
Inheritance is important, make sure you really understand it. We just looked at [Composition](#composition), Inheritance is basically the same but different.
Composition means **has-a-Relationship**, a human has-a-Leg for example.
Inheritance means **is-a-Relationship**, a human is an Existence, or a Dog is an animal. A chair is furniture.
Remember the difference!!!
Inheritance means that you can reuse functionality very easily and you can extend it quite easy.
Let's again start with an example:
Inheritance means there is a **superclass** and a **subclass**. The superclass is as the name suggests a class that is above the subclass. Animal - Dog, Furniture - Chair, Existence - Human all have this relationship to each other.
### Syntax
```java
public class Human extends Existence{ // extends means that the Human upon creation is also an Existence
public Human(...){
super(); // super() needs to be called first in your constructor
...
}
}
```
### this vs. super
When you want to make it obvious that you are accessing a field from **this** class you use the **this** Keyword, by now you should know that. The **super** Keyword means that you are calling a field or method not from **this** but from **superclass**.
### Example
I will use a very simple example here, Animal and Dog.
Animal Class
```java
public class Animal{
private int age; // Every animal has an age.
private String name; // Every animal has a name.
public Animal(int age, String name){ // An animal we create has an age and a name
this.age = age;
this.name = name;
}
public void eat(){ // Every animal can eat
System.out.println("Animal eat() invoked");
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
}
```
Dog Class
```java
public class Dog extends Animal{ // A Dog is an animal but receives also all functionality from the Animal class
private int legs; // A Dog can have additional fields, but doesn't need to
public Dog(int age, String name, int legs){ //A Dog needs to have an Age, a Name (because he is an animal) and Legs (because he is a Dog)
super(age, name); // calls the Animal constructor with the paramters age and name
this.legs = legs; // initialises the legs
}
@Override
public void eat(){
System.out.println("Dog eat() invoked");
}
}
```
Tester class
```java
public class tester{
public static void main(String[] args){
Dog dog = new Dog(1, "Sergej", 4); // invokes constructor in Dog.java
Animal animal = new Animal(1, "Theresa"); // invokes constructor in Animal.java
dog.eat(); // Output: "Dog eat() invoked", calls eat() first from Dog class
dog.super.eat(); // Output: "Animal eat() invoked",specifically invokes from animal superclass
dog.age; // Compiler Error, age is private to Animal
dog.getAge(); // returns 1 because getAge() is a public method
dog.setAge(3); // works as well because setAge() is public
animal.age; // returns 1;
animal.getAge(); // returns 1 because getAge() an animal specific method
animal.setAge(3); // same as above
}
}
```
I would advise to look at [Existence Class](https://github.com/florianmoss/learn-oop-java/blob/master/Existence.java)and [Human Class](https://github.com/florianmoss/learn-oop-java/blob/master/Human.java).
Then go and try to reproduce the Animal - Dog relation in 2 classes and come up with more methods. What could be Dog specific? Maybe a race, a bark method and a drink method. Write a tester to invoke these methods and make sure you really understand what is going on.
You will understand it by doing, I promise.
# Override
[Another Documentation](https://www.geeksforgeeks.org/overriding-in-java/)
Override means that you are overwriting a method. You have seen the [toString()](#tostring--enhanced-for-loop) Method for example or the **Dog.eat()** Method in the [Inheritance section](#inheritance).
Both methods are already existent but have a form of return that we do not want, therefore we can change it.
You don't need to show in your code that you overwrote something, but you certainly can and you should - so other people know what you have done when they read your code.
### Syntax
```java
@Override
public String toString(){
return //whatever you need
}
```
# Polymorphism
Polymorphism is again, just a fancy word for saying:
**One line of code invokes different behaviour at runtime**
It often occurs when the sublclass overrides a method in the superclass. You can check out the [Inheritance section](#inheritance) and the the [Override section](#override) to find more about this.
In other words, Polymorphism is the result of Inheritance in combination with Override.
### Code Example
Open the [main_starter Class](https://github.com/florianmoss/learn-oop-java/blob/master/main_starter.java) at line 69.
```java
ArrayList<Existence> existenceList = new ArrayList<Existence>();
try{
for(int i=0; i<20; i++){
existenceList.add(new Human(5, 5, 5, 5, i, ("Name"+i)));
}
existenceList.add(new Cell());
existenceList.add(new Cell());
}catch(Exception e){
System.out.println(e.getMessage());
}
// --> This is Polymorphism, 1 Line of code but at execution with
// different execution/meaning.
for(Existence h : existenceList){
System.out.println(h);
}
```
What output do you expect for the second for-loop:
```java
for(Existence h : existenceList){
System.out.println(h);
}
```
First of all you need to understand the section about [toString() and enhanced for-loops](#tostring--enhanced-for-loop). Then we know, what to do, right? We need to check if the is a different implementation for **toString()** for the **Cell** and the **Human**, first we should check **Existence**, since it is the superclass for both.
Did you find a toString() Method in [Existence.java](https://github.com/florianmoss/learn-oop-java/blob/master/Existence.java)?
No, good. Let's move on then.
A [**Cell**](https://github.com/florianmoss/learn-oop-java/blob/master/Cell.java) seems to have no additional fields, only the name and age inherited from [**Existence**](https://github.com/florianmoss/learn-oop-java/blob/master/Existence.java).
```java
@Override
public String toString(){
return "Cell{age="+getAge()+", name="+getName()+"}";
}
```
A [**Human**](https://github.com/florianmoss/learn-oop-java/blob/master/Human.java) contains also a toString() Method, as we have discussed in detail [here](#tostring--enhanced-for-loop).
```java
public boolean equals(Human h){
return (this.getAge()==h.getAge() && this.getName().equals(h.getName()) &&
this.getLeftArm().equals(h.getLeftArm()) && this.getRightArm().equals(h.getRightArm()) &&
this.getLeftLeg().equals(h.getLeftLeg()) && this.getRightLeg().equals(h.getRightLeg()));
}
```
Back to our Loop, we are now able to say, that the Output is:
```java
Human{age=0, name=Name0, armLeft=0 ,1 ,2 ,3 ,4, armRight=0 ,1 ,2 ,3 ,4, legLeft=0 ,1 ,2 ,3 ,4, legRight=0 ,1 ,2 ,3 ,4, familyMembers=[]
Human{age=1, name=Name1, armLeft=0 ,1 ,2 ,3 ,4, armRight=0 ,1 ,2 ,3 ,4, legLeft=0 ,1 ,2 ,3 ,4, legRight=0 ,1 ,2 ,3 ,4, familyMembers=[]
Human{age=2, name=Name2, armLeft=0 ,1 ,2 ,3 ,4, armRight=0 ,1 ,2 ,3 ,4, legLeft=0 ,1 ,2 ,3 ,4, legRight=0 ,1 ,2 ,3 ,4, familyMembers=[]
Human{age=3, name=Name3, armLeft=0 ,1 ,2 ,3 ,4, armRight=0 ,1 ,2 ,3 ,4, legLeft=0 ,1 ,2 ,3 ,4, legRight=0 ,1 ,2 ,3 ,4, familyMembers=[]
Human{age=4, name=Name4, armLeft=0 ,1 ,2 ,3 ,4, armRight=0 ,1 ,2 ,3 ,4, legLeft=0 ,1 ,2 ,3 ,4, legRight=0 ,1 ,2 ,3 ,4, familyMembers=[]
Human{age=5, name=Name5, armLeft=0 ,1 ,2 ,3 ,4, armRight=0 ,1 ,2 ,3 ,4, legLeft=0 ,1 ,2 ,3 ,4, legRight=0 ,1 ,2 ,3 ,4, familyMembers=[]
Human{age=6, name=Name6, armLeft=0 ,1 ,2 ,3 ,4, armRight=0 ,1 ,2 ,3 ,4, legLeft=0 ,1 ,2 ,3 ,4, legRight=0 ,1 ,2 ,3 ,4, familyMembers=[]
Human{age=7, name=Name7, armLeft=0 ,1 ,2 ,3 ,4, armRight=0 ,1 ,2 ,3 ,4, legLeft=0 ,1 ,2 ,3 ,4, legRight=0 ,1 ,2 ,3 ,4, familyMembers=[]
Human{age=8, name=Name8, armLeft=0 ,1 ,2 ,3 ,4, armRight=0 ,1 ,2 ,3 ,4, legLeft=0 ,1 ,2 ,3 ,4, legRight=0 ,1 ,2 ,3 ,4, familyMembers=[]
Human{age=9, name=Name9, armLeft=0 ,1 ,2 ,3 ,4, armRight=0 ,1 ,2 ,3 ,4, legLeft=0 ,1 ,2 ,3 ,4, legRight=0 ,1 ,2 ,3 ,4, familyMembers=[]
Human{age=10, name=Name10, armLeft=0 ,1 ,2 ,3 ,4, armRight=0 ,1 ,2 ,3 ,4, legLeft=0 ,1 ,2 ,3 ,4, legRight=0 ,1 ,2 ,3 ,4,familyMembers=[]
Human{age=11, name=Name11, armLeft=0 ,1 ,2 ,3 ,4, armRight=0 ,1 ,2 ,3 ,4, legLeft=0 ,1 ,2 ,3 ,4, legRight=0 ,1 ,2 ,3 ,4,familyMembers=[]
Human{age=12, name=Name12, armLeft=0 ,1 ,2 ,3 ,4, armRight=0 ,1 ,2 ,3 ,4, legLeft=0 ,1 ,2 ,3 ,4, legRight=0 ,1 ,2 ,3 ,4,familyMembers=[]
Human{age=13, name=Name13, armLeft=0 ,1 ,2 ,3 ,4, armRight=0 ,1 ,2 ,3 ,4, legLeft=0 ,1 ,2 ,3 ,4, legRight=0 ,1 ,2 ,3 ,4,familyMembers=[]
Human{age=14, name=Name14, armLeft=0 ,1 ,2 ,3 ,4, armRight=0 ,1 ,2 ,3 ,4, legLeft=0 ,1 ,2 ,3 ,4, legRight=0 ,1 ,2 ,3 ,4,familyMembers=[]
Human{age=15, name=Name15, armLeft=0 ,1 ,2 ,3 ,4, armRight=0 ,1 ,2 ,3 ,4, legLeft=0 ,1 ,2 ,3 ,4, legRight=0 ,1 ,2 ,3 ,4,familyMembers=[]
Human{age=16, name=Name16, armLeft=0 ,1 ,2 ,3 ,4, armRight=0 ,1 ,2 ,3 ,4, legLeft=0 ,1 ,2 ,3 ,4, legRight=0 ,1 ,2 ,3 ,4,familyMembers=[]
Human{age=17, name=Name17, armLeft=0 ,1 ,2 ,3 ,4, armRight=0 ,1 ,2 ,3 ,4, legLeft=0 ,1 ,2 ,3 ,4, legRight=0 ,1 ,2 ,3 ,4,familyMembers=[]
Human{age=18, name=Name18, armLeft=0 ,1 ,2 ,3 ,4, armRight=0 ,1 ,2 ,3 ,4, legLeft=0 ,1 ,2 ,3 ,4, legRight=0 ,1 ,2 ,3 ,4,familyMembers=[]
Human{age=19, name=Name19, armLeft=0 ,1 ,2 ,3 ,4, armRight=0 ,1 ,2 ,3 ,4, legLeft=0 ,1 ,2 ,3 ,4, legRight=0 ,1 ,2 ,3 ,4,familyMembers=[]
Cell{age=0, name=Cell}
Cell{age=0, name=Cell}
```
### Why is that so fascinating?
Well let's look again at the loop:
```java
for(Existence h : existenceList){
System.out.println(h);
}
```
We have one line of code **System.out.println(h)** but at execution it invokes different toString() Methods. From a **Human** and from a **Cell**. That's pretty cool isn't it?
# Overloading
- MUST change the argument list
- CAN change the return type
That's all you need to remember basically. Overloading means that you can have multiple constructors and/or methods with the same name.
### Code Example
```java
// Constructor Overloading
public Human() throws Exception{
this(5, 5, 5, 5, 0, "none");
}
public Human(int fingersLeft, int fingersRight, int toesLeft, int toesRight, int age, String name) throws Exception{
super(age, name);
this.armLeft = new Arm(fingersLeft);
this.armRight = new Arm(fingersRight);
this.legLeft = new Leg(toesLeft);
this.legRight = new Leg(toesRight);
this.familyMembers = new ArrayList<String>();
}
// Method Overloading
public void eat(){
System.out.println("Human eats.");
}
// Invalid, because we MUST change the argument list !!!
// public String eat(){
// return "Human eats."
// }
// Valid
public String eat(String food){
return "Human eats " + food;
}
// Valid
public void eat(String food, int amount){
System.out.println("Human eats " + food + ", " + amount + " times.");
}
```
# Wrapper Classes
| Primitive Type | Wrapper Class |
| -------------- | :-----------: |
| boolean | Boolean |
| byte | Byte |
| char | Character |
| float | Float |
| int | Integer |
| long | Long |
| short | Short |
| double | Double |
Primitive datatypes limit us in their functionality. As the name suggest they are primitive - therefore they are not good for much because they can't do much.
Why not create an object that is an int with more functionality? And call it [Integer](https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html).
Can you think of a simple usecase for this?
```java
ArrayList<Integer> numbers = new ArrayList<Integer>();
```
...well we know that we can't use ArrayLists with primitive datatypes, hence we need to use an object, here: Integer.
Not needed for this class, but I think you should know of is [Autoboxing and Unboxing](https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html). Take 5 min to read the official documentation and it will all make a lot more sense.
# instanceOf Operator (not used in code)
Let's start this again with an example, since the name basically says what it does.
```java
Existence e;
e = new Human();
if(e instanceof Human)
System.out.println("I'm a human");
else
System.out.println("I'm not a human");
```
**instanceof** just checks if a variable that is declared as a superclass is an instance of a certain subclass.
# Casting
For casting, please remember the following: **You can go always from subclass to superclass, but not the other way around.**.
### Code Example
```java
// All 4 are valid declarations and initialisations
Existence c = new Cell();
Existence h = new Human();
Cell c2 = new Cell();
Human h2 = new Human();
// Now, where do we need casting and where not:
Existence h3 = c2; // works because we are going from subclass to superclass.
// Cell c3 = c; // Doesn't work, because we are going from superclass to subclass. "c" is an Existence.
// Solution:
Cell c3 = (Cell)c2; // We can cast, and then assign the value.
```
You can also use the **instanceof** Keyword in combination with casting to avoid any compiler errors, for example:
```java
Existence c = new Cell();
if(c instanceof Cell)
Cell c2 = (Cell)c;
```
# Abstract Classes
Abstract classes are more or less an evolution of [Inheritance](#inheritance). Let's look at our example, we have an Existence class from where the Human class and the Cell class inherit from. But do we actually want to be able to create an Existence object? Not really, we just want the subclasses to have certain properties, but an Existence itself doesn't exist, so we wan't to prevent this, this is where we can use **Abstract Classes**.
### Syntax
```java
public abstract class Existence{
// code
}
```
The **abstract** Keyword indicated that you can't create an object of the form Existence. But it can still work as a superclass.
### Abstract Methods
You can also provide abstract methods, these methods are meant to be implemanted by the subclass. They **HAVE** to be implemented by any subclass in fact. Abstract methods only have a method signature but no method body. Abstract methods also **HAVE** to be **public**, for obvious reasons. An Example will explain it best though:
Existence Class:
```java
// Abstract Class Methods
public abstract int calcApproxDeath();
public abstract void deleteExistence();
```
Human Class:
```java
@Override
public int calcApproxDeath(){
return 80 - getAge();
}
@Override
public void deleteExistence(){
setAge(999);
setName("Human dead");
}
```
Cell Class:
```java
@Override
public int calcApproxDeath(){
return 5 - getAge();
}
@Override
public void deleteExistence(){
setAge(999);
setName("Cell dead");
}
```
# equals()
We have covered the equals() method in the first year already, that's why I will keep it short here and give you only an example.
### Syntax
```java
public boolean equals(Object o){
return //compare all fields
}
```
### Example
Cell Class:
```java
public boolean equals(Cell c){
return (this.getAge()==c.getAge() && this.getName().equals(c.getName()));
}
```
Human Class:
```java
public boolean equals(Human h){
return (this.getAge()==h.getAge() && this.getName().equals(h.getName()) &&
this.getLeftArm().equals(h.getLeftArm()) && this.getRightArm().equals(h.getRightArm()) &&
this.getLeftLeg().equals(h.getLeftLeg()) && this.getRightLeg().equals(h.getRightLeg()));
}
```
# Interfaces
Interfaces are a natural evolution of inheritance. The problem with inheritance is, that a class can only inherit from one superclass. This is obviously quite limiting. Let's think about a **Human**, a human is an **Existence** but at the same time a human is also **learnable**, this applies to a lot of existences, but how can we share this functionality between a variety of subclasses, if we can only inherit from one superclass? We can't and that's why we use interfaces.
Remember the following: **All interfaces are a description of promised behaviour.**.
### Syntax
The interface:
```java
public interface InterfaceName<T>{ // don't worry about the <T> here. It's a generic and is a placeholder for all possible types.
public returnType methodName(T obj);
// more methods possibly
}
```
The implementation in our class:
```java
public class ClassName implements InterfaceName<T>{
// code
}
```
We can implement more than one interface, just put a ',' between them.
# Comparable + compareTo()
### Comparable Interface
```java
public interface Comparable<T>{
public int compareTo(T obj);
}
```
Implementation in our Existence Class:
```java
public abstract class Existence implements Comparable<Existence>{
@Override
public int compareTo(Existence obj){
if(this.getAge() > obj.getAge()) return 1;
if(this.getAge() < obj.getAge()) return -1;
return 0;
}
}
```
When we compare two Existence objects, we compare them based on their age to create a natural hierachy based on the age.
# sort()
# Comparator + compare()
# Bubble Sort
# Selection Sort
# Sequential Search
# Binary Search
|
C++ | UTF-8 | 983 | 2.65625 | 3 | [] | no_license | #include <iostream>
#define forn(i, n) for (long long i = 0; i < n; i++)
using namespace std;
typedef long long ll;
ll mdm[100000];
bool mdmb[100000];
ll diamonds[100000];
ll N;
ll kadane(ll v) {
ll re;
if (v == -1) {
re = 0;
} else {
if (!mdmb[v]) {
mdm[v] = max(kadane(v-1) + diamonds[v], diamonds[v]);
mdmb[v] = true;
}
re = mdm[v];
}
return re;
}
int main() {
cin >> N;
forn (i, N) {
cin >> diamonds[i];
}
ll sumV = 0;
forn (i, N) {
sumV += diamonds[i];
}
ll maxV = 0;
forn (i, N) {
if (kadane(i) > maxV) {
maxV = kadane(i);
}
}
// flip and reset
forn(i, N) {
diamonds[i] = -diamonds[i];
}
forn(i, N) {
mdmb[i] = false;
}
ll minV = 0;
forn (i, N) {
if (kadane(i) > minV) {
minV = kadane(i);
}
}
cout << max(maxV, sumV + minV) << endl;
} |
C# | UTF-8 | 670 | 2.671875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
namespace MvcIoC.Models
{
public class ProteinRespository : IProteinRespository
{
private ProteinData service=new ProteinData();
public ProteinRespository()
{
service.Goal = 0;
service.Total = 0;
service.TimeCreated = new DateTime().Date;
}
public ProteinData GetData(DateTime date)
{
return service;
}
public void SetTotal(DateTime date, int value)
{
service.Total = value;
service.TimeCreated = date;
}
public void SetGoal(DateTime date, int value)
{
service.Goal = value;
service.TimeCreated = date;
}
}
} |
PHP | UTF-8 | 4,740 | 3 | 3 | [] | no_license | <?php
namespace Phug\Lexer\Scanner;
use Phug\Lexer\ScannerInterface;
use Phug\Lexer\State;
use Phug\Lexer\Token\IndentToken;
use Phug\Lexer\Token\InterpolationEndToken;
use Phug\Lexer\Token\InterpolationStartToken;
use Phug\Lexer\Token\NewLineToken;
use Phug\Lexer\Token\OutdentToken;
use Phug\Lexer\Token\TagInterpolationEndToken;
use Phug\Lexer\Token\TagInterpolationStartToken;
use Phug\Lexer\Token\TextToken;
class MultilineScanner implements ScannerInterface
{
protected function unEscapedToken(State $state, $buffer)
{
/** @var TextToken $token */
$token = $state->createToken(TextToken::class);
$token->setValue(preg_replace('/\\\\([#!]\\[|#\\{)/', '$1', $buffer));
return $token;
}
protected function getUnescapedLines(State $state, $lines)
{
$buffer = '';
$interpolationLevel = 0;
foreach ($lines as $number => $lineValues) {
if ($number) {
$buffer .= "\n";
}
foreach ($lineValues as $value) {
if (is_string($value)) {
if ($interpolationLevel) {
yield $this->unEscapedToken($state, $value);
continue;
}
$buffer .= $value;
continue;
}
if (!$interpolationLevel) {
yield $this->unEscapedToken($state, $buffer);
$buffer = '';
}
yield $value;
if ($value instanceof TagInterpolationStartToken || $value instanceof InterpolationStartToken) {
$interpolationLevel++;
}
if ($value instanceof TagInterpolationEndToken || $value instanceof InterpolationEndToken) {
$interpolationLevel--;
}
}
}
//TODO: $state->endToken
yield $this->unEscapedToken($state, $buffer);
}
public function scan(State $state)
{
$reader = $state->getReader();
foreach ($state->scan(TextScanner::class) as $token) {
yield $token;
}
if ($reader->peekNewLine()) {
yield $state->createToken(NewLineToken::class);
$reader->consume(1);
$lines = [];
$level = $state->getLevel();
$newLevel = $level;
$maxIndent = INF;
while ($reader->hasLength()) {
$indentationScanner = new IndentationScanner();
$newLevel = $indentationScanner->getIndentLevel($state, $level);
if (!$reader->peekChars([' ', "\t", "\n"])) {
break;
}
if ($newLevel < $level) {
if ($reader->match('[ \t]*\n')) {
$reader->consume(mb_strlen($reader->getMatch(0)));
$lines[] = [];
continue;
}
$state->setLevel($newLevel);
break;
}
$line = [];
$indent = $reader->match('[ \t]+(?=\S)') ? mb_strlen($reader->getMatch(0)) : INF;
if ($indent < $maxIndent) {
$maxIndent = $indent;
}
foreach ($state->scan(InterpolationScanner::class) as $subToken) {
$line[] = $subToken instanceof TextToken ? $subToken->getValue() : $subToken;
}
$text = $reader->readUntilNewLine();
$line[] = $text;
$lines[] = $line;
if (!$reader->peekNewLine()) {
break;
}
$reader->consume(1);
}
if (count($lines)) {
yield $state->createToken(IndentToken::class);
if ($maxIndent > 0 && $maxIndent < INF) {
foreach ($lines as &$line) {
if (count($line) && is_string($line[0])) {
$line[0] = mb_substr($line[0], $maxIndent) ?: '';
}
}
}
foreach ($this->getUnescapedLines($state, $lines) as $token) {
yield $token;
}
if ($reader->hasLength()) {
yield $state->createToken(NewLineToken::class);
$state->setLevel($newLevel)->indent($level + 1);
while ($state->nextOutdent() !== false) {
yield $state->createToken(OutdentToken::class);
}
}
}
}
}
}
|
C++ | UTF-8 | 18,524 | 2.625 | 3 | [
"MIT"
] | permissive | // This file is a part of WCPSP_Stereo. License is MIT.
// Copyright (c) Qingqing Yang
// Description : Cost propagation on a simple tree for stereo matching.
#ifndef HORIZ_TREE_COST_AGGREGATION_H_
#define HORIZ_TREE_COST_AGGREGATION_H_
#include <cstdint>
#include <cmath>
#include "image.h"
#include "image_proc-inl.h"
namespace cvlab {
template<typename CostType>
class HTreeCostPropagation {
public:
HTreeCostPropagation();
HTreeCostPropagation(ImageU8& image,
Image<CostType>& cost_vol,
CostType sigma_r = 0.1,
CostType p_smooth = 5.0);
~HTreeCostPropagation();
void cost_propagate();
void cost_propagate_with_smooth_prior();
void compute_normalization_factor(Image<CostType>& norm_factor);
void compute_norm_factor_h(Image<CostType>& norm_factor);
void compute_norm_factor_v(Image<CostType>& norm_factor);
void update_lut(CostType sigma_r); // update LUT
void set_p_smooth(CostType p_smooth) { p_smooth_ = p_smooth; }
protected:
void propagate(Image<CostType>& cost_vol,
bool with_normalization = false);
void propagate_with_smooth_prior(Image<CostType>& cost_vol,
bool with_normalization = false);
void compute_propagation_coeff(ImageU8& image);
protected:
ImageU8* image_;
Image<CostType>* cost_vol_;
Image<int>* propagation_coeff_x_;
Image<int>* propagation_coeff_y_;
int img_width_;
int img_height_;
CostType sigma_r_;
CostType p_smooth_;
CostType lut_[256]; // LUT for propagation weight
};
template<typename CostType>
HTreeCostPropagation<CostType>::HTreeCostPropagation() :
image_(NULL),
cost_vol_(NULL),
propagation_coeff_x_(NULL),
propagation_coeff_y_(NULL),
img_width_(0),
img_height_(0),
sigma_r_(0),
p_smooth_(0) { }
template<typename CostType>
HTreeCostPropagation<CostType>::~HTreeCostPropagation() {
delete propagation_coeff_x_;
delete propagation_coeff_y_;
}
template<typename CostType>
HTreeCostPropagation<CostType>::
HTreeCostPropagation(ImageU8& image,
Image<CostType>& cost_vol,
CostType sigma_r,
CostType p_smooth) :
image_(&image),
cost_vol_(&cost_vol),
sigma_r_(sigma_r),
p_smooth_(p_smooth) {
img_width_ = image.width();
img_height_ = image.height();
propagation_coeff_x_ = new Image<int>(img_width_, img_height_, 1);
propagation_coeff_y_ = new Image<int>(img_width_, img_height_, 1);
compute_propagation_coeff(image);
update_lut(sigma_r);
}
template<typename CostType>
void HTreeCostPropagation<CostType>::
cost_propagate() {
propagate(*cost_vol_);
}
template<typename CostType>
void HTreeCostPropagation<CostType>::
cost_propagate_with_smooth_prior() {
propagate_with_smooth_prior(*cost_vol_);
}
template<typename CostType>
void HTreeCostPropagation<CostType>::
compute_normalization_factor(Image<CostType>& norm_factor) {
// propagate(norm_factor, false);
compute_norm_factor_h(norm_factor);
compute_norm_factor_v(norm_factor);
}
template<typename CostType>
void HTreeCostPropagation<CostType>::
update_lut(CostType sigma_r) {
sigma_r = std::max(sigma_r, static_cast<CostType>(0.01));
// TODO: replace 256 with a configurable value
for(int i = 0; i < 256; i++) {
lut_[i] = exp(-static_cast<CostType>(i) / (255*sigma_r));
}
}
// protected functions
template<typename CostType>
void HTreeCostPropagation<CostType>::
propagate(Image<CostType>& cost_vol, bool with_normalization) {
int width = img_width_, height = img_height_;
int disp_range = cost_vol.channels();
Image<CostType> cost_vol_temp(cost_vol);
// horizontal phase
// forward-backward algorithm
// forward pass
CostType* ptr_pre_node = cost_vol_temp.ptr_pixel(0, 0);
CostType* ptr_cur_node = cost_vol_temp.ptr_pixel(1, 0);
CostType* ptr_end_node =
cost_vol_temp.ptr_pixel(width-1, height-1) + (disp_range-1);
int* ptr_coeff = propagation_coeff_x_->ptr_pixel(1, 0);
CostType weight = 0.0;
while(ptr_cur_node <= ptr_end_node) {
weight = lut_[*ptr_coeff++];
for(int d = 0; d < disp_range; d++) { // only for loop counting
*ptr_cur_node++ += weight * (*ptr_pre_node++);
}
}
// backward pass
ptr_pre_node = cost_vol.ptr_pixel(width-1, height-1) + (disp_range-1);
ptr_cur_node = cost_vol.ptr_pixel(width-2, height-1) + (disp_range-1);
ptr_end_node = cost_vol.ptr_pixel(0, 0);
ptr_coeff = propagation_coeff_x_->ptr_pixel(width-1, height-1);
while(ptr_cur_node >= ptr_end_node) {
weight = lut_[*ptr_coeff--];
for(int d = 0; d < disp_range; d++) { // only for loop counting
*ptr_cur_node-- += weight * (*ptr_pre_node--);
}
}
// compute temp result of horizontal phase
CostType* ptr_cost = cost_vol.data();
CostType* end_cost = cost_vol.ptr_pixel(width-1, height-1) + (disp_range-1);
CostType* ptr_cost_temp = cost_vol_temp.data();
while(ptr_cost <= end_cost) {
for(int d = 0; d < disp_range; d++) {
*ptr_cost++ += *ptr_cost_temp++;
}
} // to save memory, we did not minus the cost in place, this will not
// change the result much
// normalize cost value
if (with_normalization) {
Image<CostType> norm_factor(width, height, 1);
norm_factor.dataset(1.0);
compute_norm_factor_h(norm_factor);
ptr_cost = cost_vol.data();
end_cost = cost_vol.ptr_pixel(width-1, height-1) + (disp_range-1);
CostType* ptr_norm_factor = norm_factor.data();
while(ptr_cost <= end_cost) {
CostType norm = *ptr_norm_factor++;
for(int d = 0; d < disp_range; d++) {
*ptr_cost++ /= norm;
}
} // to save memory, we did not minus the cost in place, this will not
// change the result much
}
memcpy(cost_vol_temp.data(), cost_vol.data(),
sizeof(CostType)*width*height*disp_range);
// update_lut(sigma_r_ / 1.5); // optional, I did not find much improvement
// vertical phase
// forward pass
// in fact, ptr_pre_node does not point to the "node" but cost values
ptr_pre_node = cost_vol_temp.ptr_pixel(0, 0);
ptr_cur_node = cost_vol_temp.ptr_pixel(0, 1); // the next row
ptr_end_node = cost_vol_temp.ptr_pixel(width-1, height-1) + (disp_range-1);
ptr_coeff = propagation_coeff_y_->ptr_pixel(0, 1);
while(ptr_cur_node <= ptr_end_node) {
weight = lut_[*ptr_coeff++];
for(int d = 0; d < disp_range; d++) {
*ptr_cur_node++ += weight * (*ptr_pre_node++);
}
}
// backward pass
ptr_pre_node = cost_vol.ptr_pixel(width-1, height-1) + (disp_range-1);
ptr_cur_node = cost_vol.ptr_pixel(width-1, height-2) + (disp_range-1);
ptr_end_node = cost_vol.data();
ptr_coeff = propagation_coeff_y_->ptr_pixel(width-1, height-1);
while(ptr_cur_node >= ptr_end_node) {
weight = lut_[*ptr_coeff--];
for(int d = 0; d < disp_range; d++) { // only for loop counting
*ptr_cur_node-- += weight * (*ptr_pre_node--);
}
}
// get the final result
ptr_cost = cost_vol.data();
end_cost = cost_vol.ptr_pixel(width-1, height-1) + (disp_range-1);
ptr_cost_temp = cost_vol_temp.data();
while(ptr_cost <= end_cost) {
*ptr_cost++ += *ptr_cost_temp++;
} // again to save memory, we did not minus the cost in place, this will not
// change the result much
}
template<typename CostType>
void HTreeCostPropagation<CostType>::
propagate_with_smooth_prior(Image<CostType>& cost_vol,
bool with_normalization) {
using std::min;
int width = img_width_, height = img_height_;
int disp_range = cost_vol.channels();
CostType p_smooth = p_smooth_;
Image<CostType> cost_vol_temp(cost_vol);
// horizontal phase
// forward-backward algorithm
// forward pass
CostType* ptr_pre_node = cost_vol_temp.ptr_pixel(0, 0);
CostType* ptr_cur_node = cost_vol_temp.ptr_pixel(1, 0);
CostType* ptr_end_node = cost_vol_temp.ptr_pixel(width-1, height-1);
int* ptr_coeff = propagation_coeff_x_->ptr_pixel(1, 0);
CostType weight = 0.0;
while(ptr_cur_node <= ptr_end_node) {
weight = lut_[*ptr_coeff++];
int d = 0;
ptr_cur_node[d] += weight * min(ptr_pre_node[d],
ptr_pre_node[d+1] + p_smooth);
for(d = 1; d < disp_range-1; d++) {
ptr_cur_node[d] += weight * min(ptr_pre_node[d],
min(ptr_pre_node[d-1],
ptr_pre_node[d+1]) + p_smooth);
}
// d = disp_range-1
ptr_cur_node[d] += weight * min(ptr_pre_node[d],
ptr_pre_node[d-1] + p_smooth);
ptr_cur_node += disp_range;
ptr_pre_node += disp_range;
}
// backward pass
ptr_pre_node = cost_vol.ptr_pixel(width-1, height-1);
ptr_cur_node = cost_vol.ptr_pixel(width-2, height-1);
ptr_end_node = cost_vol.ptr_pixel(0, 0);
ptr_coeff = propagation_coeff_x_->ptr_pixel(width-1, height-1);
while(ptr_cur_node >= ptr_end_node) {
weight = lut_[*ptr_coeff--];
int d = 0;
ptr_cur_node[d] += weight * min(ptr_pre_node[d],
ptr_pre_node[d+1] + p_smooth);
for(d = 1; d < disp_range-1; d++) {
ptr_cur_node[d] += weight * min(ptr_pre_node[d],
min(ptr_pre_node[d-1],
ptr_pre_node[d+1]) + p_smooth);
}
// d = disp_range-1
ptr_cur_node[d] += weight * min(ptr_pre_node[d],
ptr_pre_node[d-1] + p_smooth);
ptr_cur_node -= disp_range;
ptr_pre_node -= disp_range;
}
CostType* ptr_cost = cost_vol.data();
CostType* end_cost = cost_vol.ptr_pixel(width-1, height-1) + (disp_range-1);
CostType* ptr_cost_temp = cost_vol_temp.data();
while(ptr_cost <= end_cost) {
*ptr_cost++ += *ptr_cost_temp++;
}
// to save memory, we did not minus the cost in place, this will not
// change the result much
if (with_normalization) {
// compute temp result of horizontal phase and normalize
Image<CostType> norm_factor(width, height, 1);
compute_norm_factor_h(norm_factor);
ptr_cost = cost_vol.data();
end_cost = cost_vol.ptr_pixel(width-1, height-1);
CostType* ptr_norm_factor = norm_factor.data();
while (ptr_cost <= end_cost) {
CostType norm = *ptr_norm_factor++;
for (int d = 0; d < disp_range; ++d) {
ptr_cost[d] /= norm;
}
ptr_cost += disp_range;
}
}
memcpy(cost_vol_temp.data(), cost_vol.data(),
sizeof(CostType)*width*height*disp_range);
// update_lut(sigma_r_ / 2); // optional, I did not file much improvement
// p_smooth_ /= 2;
// vertical phase
// forward pass
// infact, ptr_pre_node does not point to the "node" but cost values
ptr_pre_node = cost_vol_temp.ptr_pixel(0, 0);
ptr_cur_node = cost_vol_temp.ptr_pixel(0, 1); // the next row
ptr_end_node = cost_vol_temp.ptr_pixel(width-1, height-1);
ptr_coeff = propagation_coeff_y_->ptr_pixel(0, 1);
while(ptr_cur_node <= ptr_end_node) {
weight = lut_[*ptr_coeff++];
int d = 0;
ptr_cur_node[d] += weight * min(ptr_pre_node[d],
ptr_pre_node[d+1] + p_smooth);
for(d = 1; d < disp_range-1; d++) {
ptr_cur_node[d] += weight * min(ptr_pre_node[d],
min(ptr_pre_node[d-1],
ptr_pre_node[d+1]) + p_smooth);
}
// d = disp_range-1
ptr_cur_node[d] += weight * min(ptr_pre_node[d],
ptr_pre_node[d-1] + p_smooth);
ptr_cur_node += disp_range;
ptr_pre_node += disp_range;
}
// backward pass
ptr_pre_node = cost_vol.ptr_pixel(width-1, height-1);
ptr_cur_node = cost_vol.ptr_pixel(width-1, height-2);
ptr_end_node = cost_vol.data();
ptr_coeff = propagation_coeff_y_->ptr_pixel(width-1, height-1);
while(ptr_cur_node >= ptr_end_node) {
weight = lut_[*ptr_coeff--];
int d = 0;
ptr_cur_node[d] += weight * min(ptr_pre_node[d],
ptr_pre_node[d+1] + p_smooth);
for(d = 1; d < disp_range-1; d++) {
ptr_cur_node[d] += weight * min(ptr_pre_node[d],
min(ptr_pre_node[d-1],
ptr_pre_node[d+1]) + p_smooth);
}
// d = disp_range-1
ptr_cur_node[d] += weight * min(ptr_pre_node[d],
ptr_pre_node[d-1] + p_smooth);
ptr_cur_node -= disp_range;
ptr_pre_node -= disp_range;
}
// get the final result
ptr_cost = cost_vol.data();
end_cost = cost_vol.ptr_pixel(width-1, height-1) + (disp_range-1);
ptr_cost_temp = cost_vol_temp.data();
while(ptr_cost <= end_cost) {
*ptr_cost++ += *ptr_cost_temp++;
} // again to save memory, we did not minus the cost in place, this will not
// change the result much
}
template<typename CostType>
void HTreeCostPropagation<CostType>::
compute_propagation_coeff(ImageU8& image) {
ImageU8 smoothed(image);
int width = img_width_, height = img_height_;
int channels = image.channels();
int* ptr_coeff_x = NULL;
int* ptr_coeff_y = NULL;
unsigned char* ptr_img_idx0 = NULL;
unsigned char* ptr_img_idx1 = NULL;
// left -> right
for(int y = 0; y < height; y++) {
ptr_img_idx0 = smoothed.ptr_pixel(0, y);
ptr_img_idx1 = smoothed.ptr_pixel(1, y);
ptr_coeff_x = propagation_coeff_x_->ptr_pixel(0, y);
// deal with x = 0;
ptr_coeff_x[0] =
pixel_abs_diff_max_in_channel<int, unsigned char> (
ptr_img_idx1, ptr_img_idx0, channels);
ptr_coeff_x[1] = ptr_coeff_x[0];
ptr_img_idx0 += channels;
ptr_img_idx1 += channels;
for(int x = 2; x < width; x++) {
ptr_coeff_x[x] = pixel_abs_diff_max_in_channel<int, unsigned char> (
ptr_img_idx1, ptr_img_idx0, channels);
ptr_img_idx0 += channels;
ptr_img_idx1 += channels;
}
}
// up -> down
for(int y = 1; y < height; y++) {
ptr_img_idx0 = smoothed.ptr_pixel(0, y-1);
ptr_img_idx1 = smoothed.ptr_pixel(0, y);
ptr_coeff_y = propagation_coeff_y_->ptr_pixel(0, y);
for(int x = 0; x < width; x++) {
*ptr_coeff_y++ =
pixel_abs_diff_max_in_channel<int, unsigned char> (
ptr_img_idx1, ptr_img_idx0, channels);
ptr_img_idx0 += channels;
ptr_img_idx1 += channels;
}
}
// copy to y = 0
memcpy(propagation_coeff_y_->ptr_pixel(0, 0),
propagation_coeff_y_->ptr_pixel(0, 1), sizeof(int)*width);
}
template<typename CostType>
void HTreeCostPropagation<CostType>::
compute_norm_factor_h(Image<CostType>& norm_factor) {
int width = img_width_, height = img_height_;
norm_factor.dataset(1.0);
Image<CostType> norm_factor_temp(norm_factor);
// horizontal phase
// forward-backward algorithm
// forward pass
CostType* ptr_pre_node = norm_factor_temp.ptr_pixel(0, 0);
CostType* ptr_cur_node = norm_factor_temp.ptr_pixel(1, 0);
CostType* ptr_end_node = norm_factor_temp.ptr_pixel(width-1, height-1);
int* ptr_coeff = propagation_coeff_x_->ptr_pixel(1, 0);
CostType weight = 0.0;
while(ptr_cur_node <= ptr_end_node) {
weight = lut_[*ptr_coeff++];
*ptr_cur_node++ += weight * (*ptr_pre_node++);
}
// backward pass
ptr_pre_node = norm_factor.ptr_pixel(width-1, height-1);
ptr_cur_node = norm_factor.ptr_pixel(width-2, height-1);
ptr_end_node = norm_factor.ptr_pixel(0, 0);
ptr_coeff = propagation_coeff_x_->ptr_pixel(width-1, height-1);
while(ptr_cur_node >= ptr_end_node) {
weight = lut_[*ptr_coeff--];
*ptr_cur_node-- += weight * (*ptr_pre_node--);
}
CostType* ptr_norm = norm_factor.data();
CostType* end_norm = norm_factor.ptr_pixel(width-1, height-1);
CostType* ptr_norm_temp = norm_factor_temp.data();
while(ptr_norm <= end_norm) {
*ptr_norm++ += (*ptr_norm_temp++ - 1.0);
}
}
template<typename CostType>
void HTreeCostPropagation<CostType>::
compute_norm_factor_v(Image<CostType>& norm_factor) {
int width = img_width_, height = img_height_;
// norm_factor.dataset(1.0);
Image<CostType> norm_factor_temp(norm_factor);
Image<CostType> norm_factor_back(norm_factor);
// vertical phase
// forward-backward algorithm
// forward pass
CostType* ptr_pre_node = norm_factor_temp.ptr_pixel(0, 0);
CostType* ptr_cur_node = norm_factor_temp.ptr_pixel(0, 1); // the next row
CostType* ptr_end_node = norm_factor_temp.ptr_pixel(width-1, height-1);
int* ptr_coeff = propagation_coeff_y_->ptr_pixel(0, 1);
CostType weight = 0.0;
while(ptr_cur_node <= ptr_end_node) {
weight = lut_[*ptr_coeff++];
*ptr_cur_node++ += weight * (*ptr_pre_node++);
}
// backward pass
ptr_pre_node = norm_factor.ptr_pixel(width-1, height-1);
ptr_cur_node = norm_factor.ptr_pixel(width-1, height-2);
ptr_end_node = norm_factor.data();
ptr_coeff = propagation_coeff_y_->ptr_pixel(width-1, height-1);
while(ptr_cur_node >= ptr_end_node) {
weight = lut_[*ptr_coeff--];
*ptr_cur_node-- += weight * (*ptr_pre_node--);
}
CostType* ptr_norm = norm_factor.data();
CostType* end_norm = norm_factor.ptr_pixel(width-1, height-1);
CostType* ptr_norm_temp = norm_factor_temp.data();
CostType* ptr_norm_back = norm_factor_back.data();
while(ptr_norm <= end_norm) {
*ptr_norm++ += (*ptr_norm_temp++ - *ptr_norm_back++);
}
}
} // namespace cvlab
#endif // HORIZ_TREE_COST_AGGREGATION_H_
|
JavaScript | UTF-8 | 323 | 2.515625 | 3 | [] | no_license | const express = require('express');
const app = express();
const port = 3000;
app.get('/', function(request, response) {
response.send('<h1>hello coderx</h1>');
})
app.get('/user', function(req, res) {
res.send('user list');
})
app.listen(port, function() {
console.log('sever listening on port ' + port);
}) |
Python | UTF-8 | 1,059 | 2.9375 | 3 | [] | no_license | import heapq
class Solution(object):
def nthSuperUglyNumber(self, n, primes):
"""
:type n: int
:type primes: List[int]
:rtype: int
"""
# if not primes:
# return 0
# if n == 1:
# return 1
# heap = []
# for i in xrange(len(primes)):
# heapq.heappush(heap, (primes[i], i))
# num = 0
# while n > 1:
# num, level = heapq.heappop(heap)
# for i in xrange(level, len(primes)):
# heapq.heappush(heap, (num * primes[i], i))
# n -= 1
# return num
ug,ct, max_n=[0,1],1,float('inf')
pr=[1 for i in range(len(primes))]
while ct<=n:
x=max_n
for i in range(len(primes)):
while primes[i]*ug[pr[i]]<=ug[-1]:
pr[i]+=1
x=min(x,primes[i]*ug[pr[i]])
ug.append(x)
ct+=1
return ug[n]
|
Shell | UTF-8 | 1,095 | 3.5625 | 4 | [] | no_license | #!/bin/sh
basePath=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
parentBasePath=$( cd $basePath/.. && pwd )
LOG_PATH=$(cat $parentBasePath/docker.conf | grep "LOG1_PATH1" | awk -F '=' '{print $2}')
installPath=/usr/local
installLocalService(){
echo `date +'%Y-%m-%d %H:%M:%S'`": Start cp visitor-wechat file .."
cp -r $parentBasePath/apps/visitor-wechat $installPath
cp $parentBasePath/package/visitor-wechat*.jar $installPath/visitor-wechat
echo `date +'%Y-%m-%d %H:%M:%S'`": Ended cp visitor-wechat file .."
}
docker_start(){
echo `date +'%Y-%m-%d %H:%M:%S'`": Start create visitor-wechat container of docker .."
docker start visitor-wechat
echo `date +'%Y-%m-%d %H:%M:%S'`": Endded create visitor-wechat container of docker .."
}
updataContainer(){
docker_Container=`docker ps -a |grep visitor-wechat |awk '{print $1}'`
if [ -n "$docker_Container" ]; then
docker stop $docker_Container
rm -rf $installPath/visitor-wechat
fi
}
#Main function
updataContainer
installLocalService
docker_start
|
Java | UTF-8 | 9,051 | 2.1875 | 2 | [] | no_license | package org.fenixedu.ulisboa.specifications.ui.firstTimeCandidacy.forms.motivations;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.fenixedu.bennu.TupleDataSourceBean;
import org.fenixedu.ulisboa.specifications.domain.UniversityChoiceMotivationAnswer;
import org.fenixedu.ulisboa.specifications.domain.UniversityDiscoveryMeansAnswer;
import org.fenixedu.ulisboa.specifications.ui.firstTimeCandidacy.forms.CandidancyForm;
public class MotivationsExpectationsForm implements CandidancyForm {
private List<UniversityDiscoveryMeansAnswer> universityDiscoveryMeansAnswers = new ArrayList<>();
private String otherUniversityDiscoveryMeans;
private List<UniversityChoiceMotivationAnswer> universityChoiceMotivationAnswers = new ArrayList<>();
private String otherUniversityChoiceMotivation;
private boolean firstYearRegistration;
private boolean answered;
private boolean otherDiscoveryAnswer;
private boolean otherChoiceAnswer;
private List<AnswerOptionForm> universityDiscoveryMeansAnswerValues;
private List<TupleDataSourceBean> universityChoiceMotivationAnswerValues;
private List<String> otherUniversityDiscoveryMeansAnswerValues;
private List<String> otherUniversityChoiceMotivationAnswerValues;
public MotivationsExpectationsForm() {
setUniversityDiscoveryMeansAnswerValues(UniversityDiscoveryMeansAnswer.readAll().sorted().collect(Collectors.toList()));
setUniversityChoiceMotivationAnswerValues(
UniversityChoiceMotivationAnswer.readAll().sorted().collect(Collectors.toList()));
setOtherUniversityDiscoveryMeansAnswerValues(UniversityDiscoveryMeansAnswer.readAll().collect(Collectors.toList()));
setOtherUniversityChoiceMotivationAnswerValues(UniversityChoiceMotivationAnswer.readAll().collect(Collectors.toList()));
updateLists();
}
@Override
public void updateLists() {
boolean otherDiscoveryAnswer = false;
boolean otherChoiceAnswer = false;
for (UniversityDiscoveryMeansAnswer answer : universityDiscoveryMeansAnswers) {
if (answer.isOther()) {
otherDiscoveryAnswer = true;
break;
}
}
setOtherDiscoveryAnswer(otherDiscoveryAnswer);
for (UniversityChoiceMotivationAnswer answer : universityChoiceMotivationAnswers) {
if (answer.isOther()) {
otherChoiceAnswer = true;
break;
}
}
setOtherChoiceAnswer(otherChoiceAnswer);
}
public List<UniversityDiscoveryMeansAnswer> getUniversityDiscoveryMeansAnswers() {
return universityDiscoveryMeansAnswers;
}
public void setUniversityDiscoveryMeansAnswers(List<UniversityDiscoveryMeansAnswer> universityDiscoveryMeansAnswers) {
this.universityDiscoveryMeansAnswers = universityDiscoveryMeansAnswers;
}
public List<UniversityChoiceMotivationAnswer> getUniversityChoiceMotivationAnswers() {
return universityChoiceMotivationAnswers;
}
public void setUniversityChoiceMotivationAnswers(List<UniversityChoiceMotivationAnswer> universityChoiceMotivationAnswers) {
this.universityChoiceMotivationAnswers = universityChoiceMotivationAnswers;
}
public String getOtherUniversityDiscoveryMeans() {
return otherUniversityDiscoveryMeans;
}
public void setOtherUniversityDiscoveryMeans(String otherUniversityDiscoveryMeans) {
this.otherUniversityDiscoveryMeans = otherUniversityDiscoveryMeans;
}
public String getOtherUniversityChoiceMotivation() {
return otherUniversityChoiceMotivation;
}
public void setOtherUniversityChoiceMotivation(String otherUniversityChoiceMotivation) {
this.otherUniversityChoiceMotivation = otherUniversityChoiceMotivation;
}
private void populateFormValues(HttpServletRequest request) {
for (UniversityDiscoveryMeansAnswer answer : UniversityDiscoveryMeansAnswer.readAll().collect(Collectors.toList())) {
if (request.getParameter("universityDiscoveryMeans_" + answer.getExternalId()) != null) {
getUniversityDiscoveryMeansAnswers().add(answer);
}
}
for (UniversityChoiceMotivationAnswer answer : UniversityChoiceMotivationAnswer.readAll().collect(Collectors.toList())) {
if (request.getParameter("universityChoiceMotivation_" + answer.getExternalId()) != null) {
getUniversityChoiceMotivationAnswers().add(answer);
}
}
}
private void populateRequestCheckboxes(HttpServletRequest request) {
for (UniversityDiscoveryMeansAnswer answer : UniversityDiscoveryMeansAnswer.readAll().collect(Collectors.toList())) {
boolean checked = getUniversityDiscoveryMeansAnswers().contains(answer);
request.setAttribute("universityDiscoveryMeans_" + answer.getExternalId(), checked);
}
for (UniversityChoiceMotivationAnswer answer : UniversityChoiceMotivationAnswer.readAll().collect(Collectors.toList())) {
boolean checked = getUniversityChoiceMotivationAnswers().contains(answer);
request.setAttribute("universityChoiceMotivation_" + answer.getExternalId(), checked);
}
}
public boolean isFirstYearRegistration() {
return firstYearRegistration;
}
public void setFirstYearRegistration(boolean firstYearRegistration) {
this.firstYearRegistration = firstYearRegistration;
}
public boolean isAnswered() {
return answered;
}
public void setAnswered(boolean answered) {
this.answered = answered;
}
public boolean isOtherDiscoveryAnswer() {
return otherDiscoveryAnswer;
}
public void setOtherDiscoveryAnswer(boolean otherDiscoveryAnswer) {
this.otherDiscoveryAnswer = otherDiscoveryAnswer;
}
public boolean isOtherChoiceAnswer() {
return otherChoiceAnswer;
}
public void setOtherChoiceAnswer(boolean otherChoiceAnswer) {
this.otherChoiceAnswer = otherChoiceAnswer;
}
public List<AnswerOptionForm> getUniversityDiscoveryMeansAnswerValues() {
return universityDiscoveryMeansAnswerValues;
}
public void setUniversityDiscoveryMeansAnswerValues(
List<UniversityDiscoveryMeansAnswer> universityDiscoveryMeansAnswerValues) {
this.universityDiscoveryMeansAnswerValues = universityDiscoveryMeansAnswerValues.stream().map(a -> {
AnswerOptionForm tuple = new AnswerOptionForm();
tuple.setId(a.getExternalId());
tuple.setText(a.getDescription().getContent());
tuple.setCode(a.getCode());
if (tuple.getCode().contains(".")) {
String[] tokens = tuple.getCode().split("\\.");
UniversityDiscoveryMeansAnswer parent = UniversityDiscoveryMeansAnswer.findByCode(tokens[0]);
if (parent != null) {
tuple.setParentId(parent.getExternalId());
}
}
return tuple;
}).collect(Collectors.toList());
}
public List<TupleDataSourceBean> getUniversityChoiceMotivationAnswerValues() {
return universityChoiceMotivationAnswerValues;
}
public void setUniversityChoiceMotivationAnswerValues(
List<UniversityChoiceMotivationAnswer> universityChoiceMotivationAnswerValues) {
this.universityChoiceMotivationAnswerValues = universityChoiceMotivationAnswerValues.stream()
.filter(a -> !UniversityChoiceMotivationAnswer.LEGACY_CODES.contains(a.getCode())).map(a -> {
TupleDataSourceBean tuple = new TupleDataSourceBean();
tuple.setId(a.getExternalId());
tuple.setText(a.getDescription().getContent());
return tuple;
}).collect(Collectors.toList());
}
public List<String> getOtherUniversityDiscoveryMeansAnswerValues() {
return otherUniversityDiscoveryMeansAnswerValues;
}
public void setOtherUniversityDiscoveryMeansAnswerValues(
List<UniversityDiscoveryMeansAnswer> otherUniversityDiscoveryMeansAnswerValues) {
this.otherUniversityDiscoveryMeansAnswerValues = otherUniversityDiscoveryMeansAnswerValues.stream()
.filter(a -> a.isOther()).map(a -> a.getExternalId()).collect(Collectors.toList());;
}
public List<String> getOtherUniversityChoiceMotivationAnswerValues() {
return otherUniversityChoiceMotivationAnswerValues;
}
public void setOtherUniversityChoiceMotivationAnswerValues(
List<UniversityChoiceMotivationAnswer> otherUniversityChoiceMotivationAnswerValues) {
this.otherUniversityChoiceMotivationAnswerValues = otherUniversityChoiceMotivationAnswerValues.stream()
.filter(a -> a.isOther()).map(a -> a.getExternalId()).collect(Collectors.toList());;
}
}
|
Java | UTF-8 | 9,958 | 1.75 | 2 | [] | no_license | /*******************************************************************************
* Copyright (c) 2012 Secure Software Engineering Group at EC SPRIDE.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors: Christian Fritz, Steven Arzt, Siegfried Rasthofer, Eric
* Bodden, and others.
******************************************************************************/
package soot.jimple.infoflow.solver.heros;
import com.google.common.collect.Table;
import heros.EdgeFunction;
import heros.FlowFunction;
import heros.edgefunc.EdgeIdentity;
import heros.solver.*;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.infoflow.data.Abstraction;
import soot.jimple.infoflow.memory.IMemoryBoundedSolver;
import soot.jimple.infoflow.problems.AbstractInfoflowProblem;
import soot.jimple.infoflow.solver.IFollowReturnsPastSeedsHandler;
import soot.jimple.infoflow.solver.IInfoflowSolver;
import soot.jimple.infoflow.solver.executors.InterruptableExecutor;
import soot.jimple.infoflow.solver.functions.SolverCallFlowFunction;
import soot.jimple.infoflow.solver.functions.SolverCallToReturnFlowFunction;
import soot.jimple.infoflow.solver.functions.SolverNormalFlowFunction;
import soot.jimple.infoflow.solver.functions.SolverReturnFlowFunction;
import soot.jimple.infoflow.solver.memory.IMemoryManager;
import soot.jimple.toolkits.ide.icfg.BiDiInterproceduralCFG;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* We are subclassing the JimpleIFDSSolver because we need the same executor for both the forward and the backward analysis
* Also we need to be able to insert edges containing new taint information
*
*/
public class InfoflowSolver extends PathTrackingIFDSSolver<Unit, Abstraction, SootMethod, BiDiInterproceduralCFG<Unit, SootMethod>>
implements IInfoflowSolver, IMemoryBoundedSolver {
private IFollowReturnsPastSeedsHandler followReturnsPastSeedsHandler = null;
private Set<IMemoryBoundedSolverStatusNotification> notificationListeners = new HashSet<>();
private boolean killFlag = false;
private final AbstractInfoflowProblem problem;
public InfoflowSolver(AbstractInfoflowProblem problem, InterruptableExecutor executor) {
super(problem);
this.problem = problem;
this.executor = executor;
problem.setSolver(this);
}
@Override
protected CountingThreadPoolExecutor getExecutor() {
return executor;
}
public boolean processEdge(PathEdge<Unit, Abstraction> edge, Unit defStmt){
return false;
}
public boolean processEdge(PathEdge<Unit, Abstraction> edge){
// We are generating a fact out of thin air here. If we have an
// edge <d1,n,d2>, there need not necessarily be a jump function
// to <n,d2>.
if (!jumpFn.forwardLookup(edge.factAtSource(), edge.getTarget()).containsKey(edge.factAtTarget())) {
propagate(edge.factAtSource(), edge.getTarget(), edge.factAtTarget(),
EdgeIdentity.<IFDSSolver.BinaryDomain>v(), null, false);
return true;
}
return false;
}
@Override
public void injectContext(IInfoflowSolver otherSolver, SootMethod callee, Abstraction d3,
Unit callSite, Abstraction d2, Abstraction d1) {
if (!(otherSolver instanceof InfoflowSolver))
throw new RuntimeException("Other solver must be of same type");
synchronized (incoming) {
for (Unit sP : icfg.getStartPointsOf(callee))
addIncoming(sP, d3, callSite, d2);
}
// First, get a list of the other solver's jump functions.
// Then release the lock on otherSolver.jumpFn before doing
// anything that locks our own jumpFn.
final Set<Abstraction> otherAbstractions;
final InfoflowSolver solver = (InfoflowSolver) otherSolver;
synchronized (solver.jumpFn) {
otherAbstractions = new HashSet<Abstraction>
(solver.jumpFn.reverseLookup(callSite, d2).keySet());
}
for (Abstraction dx1: otherAbstractions)
if (!dx1.getAccessPath().isEmpty() && !dx1.getAccessPath().isStaticFieldRef())
processEdge(new PathEdge<Unit, Abstraction>(d1, callSite, d2));
}
@Override
protected Set<Abstraction> computeReturnFlowFunction(
FlowFunction<Abstraction> retFunction,
Abstraction d1,
Abstraction d2,
Unit callSite,
Set<Abstraction> callerSideDs) {
if (retFunction instanceof SolverReturnFlowFunction) {
// Get the d1s at the start points of the caller
Set<Abstraction> d1s = new HashSet<Abstraction>(callerSideDs.size() * 5);
for (Abstraction d4 : callerSideDs)
if (d4 == zeroValue)
d1s.add(d4);
else
synchronized (jumpFn) {
d1s.addAll(jumpFn.reverseLookup(callSite, d4).keySet());
}
return ((SolverReturnFlowFunction) retFunction).computeTargets(d2, d1, d1s);
}
else
return retFunction.computeTargets(d2);
}
@Override
protected Set<Abstraction> computeNormalFlowFunction
(FlowFunction<Abstraction> flowFunction, Abstraction d1, Abstraction d2) {
if (flowFunction instanceof SolverNormalFlowFunction)
return ((SolverNormalFlowFunction) flowFunction).computeTargets(d1, d2);
else
return flowFunction.computeTargets(d2);
}
@Override
protected Set<Abstraction> computeCallToReturnFlowFunction
(FlowFunction<Abstraction> flowFunction, Abstraction d1, Abstraction d2) {
if (flowFunction instanceof SolverCallToReturnFlowFunction)
return ((SolverCallToReturnFlowFunction) flowFunction).computeTargets(d1, d2);
else
return flowFunction.computeTargets(d2);
}
@Override
protected Set<Abstraction> computeCallFlowFunction
(FlowFunction<Abstraction> flowFunction, Abstraction d1, Abstraction d2) {
if (flowFunction instanceof SolverCallFlowFunction)
return ((SolverCallFlowFunction) flowFunction).computeTargets(d1, d2);
else
return flowFunction.computeTargets(d2);
}
@Override
protected void propagate(Abstraction sourceVal, Unit target, Abstraction targetVal, EdgeFunction<BinaryDomain> f,
/* deliberately exposed to clients */ Unit relatedCallSite,
/* deliberately exposed to clients */ boolean isUnbalancedReturn) {
// Check whether we already have an abstraction that entails the new one.
// In such a case, we can simply ignore the new abstraction.
boolean noProp = false;
/*
for (Abstraction abs : new HashSet<Abstraction>(jumpFn.forwardLookup(sourceVal, target).keySet()))
if (abs != targetVal) {
if (abs.entails(targetVal)) {
noProp = true;
break;
}
if (targetVal.entails(abs)) {
jumpFn.removeFunction(sourceVal, target, abs);
}
}
*/
if (!noProp)
super.propagate(sourceVal, target, targetVal, f, relatedCallSite, isUnbalancedReturn);
}
/**
* Cleans up some unused memory. Results will still be available afterwards,
* but no intermediate computation values.
*/
public void cleanup() {
this.jumpFn.clear();
this.incoming.clear();
this.endSummary.clear();
this.val.clear();
this.cache.clear();
}
@Override
public Set<Pair<Unit, Abstraction>> endSummary(SootMethod m, Abstraction d3) {
Set<Pair<Unit, Abstraction>> res = null;
for (Unit sP : icfg.getStartPointsOf(m)) {
Set<Table.Cell<Unit,Abstraction,EdgeFunction<IFDSSolver.BinaryDomain>>> endSum =
super.endSummary(sP, d3);
if (endSum == null || endSum.isEmpty())
continue;
if (res == null)
res = new HashSet<>();
for (Table.Cell<Unit,Abstraction,EdgeFunction<IFDSSolver.BinaryDomain>> cell : endSum)
res.add(new Pair<>(cell.getRowKey(), cell.getColumnKey()));
}
return res;
}
@Override
protected void processExit(PathEdge<Unit, Abstraction> edge) {
super.processExit(edge);
if (followReturnsPastSeeds && followReturnsPastSeedsHandler != null) {
final Abstraction d1 = edge.factAtSource();
final Unit u = edge.getTarget();
final Abstraction d2 = edge.factAtTarget();
final SootMethod methodThatNeedsSummary = icfg.getMethodOf(u);
for (Unit sP : icfg.getStartPointsOf(methodThatNeedsSummary)) {
final Map<Unit, Set<Abstraction>> inc = incoming(d1, sP);
if (inc == null || inc.isEmpty())
followReturnsPastSeedsHandler.handleFollowReturnsPastSeeds(d1, u, d2);
}
}
}
@Override
public void setFollowReturnsPastSeedsHandler(IFollowReturnsPastSeedsHandler handler) {
this.followReturnsPastSeedsHandler = handler;
}
@Override
public IMemoryManager<Abstraction, Unit> getMemoryManager() {
return null;
}
@Override
public void setMemoryManager(IMemoryManager<Abstraction, Unit> memoryManager) {
//
}
@Override
public void setJumpPredecessors(boolean setJumpPredecessors) {
//
}
@Override
public long getPropagationCount() {
return propagationCount;
}
@Override
public void setSolverId(boolean solverId) {
// TODO Auto-generated method stub
}
@Override
public void forceTerminate() {
this.killFlag = true;
((InterruptableExecutor) this.executor).interrupt();
this.executor.shutdown();
}
@Override
public boolean isTerminated() {
return false;
}
@Override
public boolean isKilled() {
return killFlag;
}
@Override
public void reset() {
this.killFlag = false;
}
@Override
public AbstractInfoflowProblem getTabulationProblem() {
return this.problem;
}
@Override
public void setSingleJoinPointAbstraction(boolean singleJoinPointAbstraction) {
// not supported
}
@Override
public void solve() {
// Notify the listeners that the solver has been started
for (IMemoryBoundedSolverStatusNotification listener : notificationListeners)
listener.notifySolverStarted(this);
super.solve();
// Notify the listeners that the solver has been terminated
for (IMemoryBoundedSolverStatusNotification listener : notificationListeners)
listener.notifySolverTerminated(this);
}
@Override
public void addStatusListener(IMemoryBoundedSolverStatusNotification listener) {
this.notificationListeners.add(listener);
}
}
|
JavaScript | UTF-8 | 510 | 3.578125 | 4 | [] | no_license | var button = document.getElementById("b1");
button.addEventListener("click", buttonPress);
var counter = 0;
function buttonPress() {
counter++;
var scriptableDiv = document.getElementById("scriptable");
console.log(Math.random() * 5);
scriptableDiv.style.color = "blue";
document.body.style.backgroundColor = "red";
scriptableDiv.innerHTML = "You pushed the button " + counter + " times.";
if(counter == 1) {
scriptableDiv.innerHTML = "You pushed the button 1 time.";
}
}
|
Java | UTF-8 | 1,012 | 3.046875 | 3 | [] | no_license | import java.io.*;
import java.util.*;
class Ovation
{
public static void main(String args[]) throws IOException
{
String s;
BufferedReader f = new BufferedReader(new FileReader("A-large.in"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("test.out")));
StringTokenizer st = new StringTokenizer(f.readLine());
int n = Integer.parseInt(st.nextToken());
for(int i=0;i<n;i++){
st = new StringTokenizer(f.readLine());
int num = Integer.parseInt(st.nextToken());
int[] mat = new int[num+1];
s = st.nextToken();
for(int j=0;j<=num;j++)
mat[j] = Integer.parseInt(s.substring(j, j+1));
int extra = 0,stand = 0;
for(int j=0;j<=num;j++){
if(j>stand){
extra+=j-stand;
stand+=j-stand;
}
stand+=mat[j];
}
out.format("Case #%d: %d\n",i+1,extra);
}
out.close();
System.exit(0);
}
} |
C# | UTF-8 | 2,368 | 2.6875 | 3 | [
"MIT"
] | permissive | using System;
using System.Threading;
using System.Threading.Tasks;
namespace Podcasts.ViewModels
{
using Dom;
public class EpisodeViewModel : BaseViewModel
{
#region Readonly Properties
public Uri Source { get; private set; }
public string Guid { get; private set; }
public string Title { get; private set; }
public Uri Image { get; private set; }
#endregion Readonly Properties
#region Awaits additional information
private TimeSpan? _duration;
public TimeSpan? Duration
{
get
{
return _duration;
}
private set
{
_duration = value;
NotifyPropertyChanged();
}
}
private bool _isUpdating = false;
public bool IsUpdating
{
get
{
return _isUpdating;
}
private set
{
_isUpdating = value;
NotifyPropertyChanged();
}
}
#endregion Awaits additional information
public EpisodeViewModel(PodcastFeedItem item)
{
Guid = item.Guid;
Title = item.Title;
Image = item.ITunes?.Image?.Href;
Source = item.Enclosure.Url;
}
private Task<TimeSpan?> GetDurationAsync(CancellationToken token)
{
return Task.Run<TimeSpan?>(async () =>
{
if (token.IsCancellationRequested) return null;
using (var sourceReader = await MediaFoundation.SourceReader.CreateFromUriAsync(Source))
{
if (token.IsCancellationRequested) return null;
return sourceReader.GetDurationBlocking();
}
});
}
internal async Task UpdateEpisodeAsync(CancellationToken token)
{
if (IsUpdating)
{
return;
}
IsUpdating = true;
try
{
if (!Duration.HasValue)
{
Duration = await GetDurationAsync(token);
}
}
finally
{
IsUpdating = false;
}
}
}
} |
Python | UTF-8 | 1,137 | 3.109375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 17-8-23 下午2:28
# @Author : xiongzhibiao
# @Email : 158349411@qq.com
# @File : 高级_server.py
# @Software: PyCharm
import socketserver
import time
class MyTCPHandler(socketserver.BaseRequestHandler):
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print("{} wrote:".format(self.client_address[0]))
print(self.data)
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
time.sleep(5)
if __name__ == "__main__":
HOST, PORT = "localhost", 9998
# Create the server, binding to localhost on port 9999
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
|
SQL | UTF-8 | 264 | 2.765625 | 3 | [] | no_license | SELECT t.rescode FROM fsboss_ser_instance t
minus
SELECT s.resourcecodestr FROM instanceen i,subscriberaddonen s WHERE i.productchildtypeid = 1
and s.instanceid_pk = i.instanceid_pk;
select * from phyresourceen p where p.resourcecodestr = '000F1E0B8765';
|
Markdown | UTF-8 | 3,741 | 2.796875 | 3 | [] | no_license | # -ourier
Упрощение процесса коммуникации между заказчиком, диспетчером и курьером
Общие сведения
1. Наименование работ
1.1. Разработка Telegram Bot API
2. Назначение разработки
2.1. Упрощение процесса коммуникации между заказчиком, диспетчером и курьером;
2.2. Предоставление заказчику возможности контроля статуса процесса доставки;
2.3. Ведение учета статистических данных заказов
Telegram Bot
Необходимые для реализации функции:
Заказчик
Активные (функции, используемые заказчиком напрямую) Пассивные
Формирование заказа, соответствующего примерному шаблону* Получение состояния выполнения заказа:
• “Курьер “xxx” выдвигается” – после назначения курьера диспетчером и дальнейшим подтверждением заказа со стороны самого курьера
• “Заказ №xxx выполнен” – после завершения процесса доставки
• Иные изменения в состоянии статуса заказа
Запрос статуса определенного заказа:
Заказчик – “cтатус 547”
Бот – “статус заказа 547 – в пути, текущее время с начала исполнения – 27 минут”
Запрос статистики выполненных заказов за день/неделю/месяц
*Для унификации общего вида заказов, сформированных разными заказчиками, необходимо наличие сопровождающего сообщения в чате с ботом (как минимум на этапе первичного подключения заказчика к боту), содержащего в себе примерные правила составления закакза: “Для составления заказа укажите следующие данные: Название организации*, адрес доставки, способ оплаты, примечания…”
Диспетчер
Активные Пассивные
Назначение определенного курьера для выполнения заказа Получение новых заказов, сформированных заказчиками, со всей информацией
Запрос общей статистики по заказам (день/неделя/месяц), в том числе и среднее время выполнения заказа Своевременное информирование в случае отклонения заказа курьером с возможностью переназначить заказ
Запрос статуса определенного заказа:
Диспетчер – “cтатус 547”
Бот – “статус заказа 547 – в пути, текущее время с начала исполнения – 27 минут”
Курьер
Активные Пассивные
Подтверждение/отклонение (с указанием причины) полученного заказа Получение заказа от диспетчера
|
JavaScript | UTF-8 | 738 | 3.421875 | 3 | [] | no_license | "use strict";
if (4==9) {
console.log("ok");
} else{
console.log("error");
}
// if (num<49){
// console.log('Error');
// } else if (num>100){
// console.log("много");
// } else{
// console.log("Ok");
// }
// (num===50)? console.log('OK'):console.log('Error');
//тернарное условые если условые в () правыльное то выполняется после ? еслы нет то после :
const num=50;
switch (num){
case 49:
console.log("Error");
break;
case 100:
console.log("Error");
break;
case 50:
console.log("В точку");
break;
default:
console.log("не в этот раз");
break;
} |
Java | UTF-8 | 2,929 | 2.3125 | 2 | [
"MIT"
] | permissive | package com.bitmovin.api.sdk.model;
import java.util.Objects;
import java.util.Arrays;
import com.bitmovin.api.sdk.model.Filter;
import com.bitmovin.api.sdk.model.InterlaceMode;
import com.bitmovin.api.sdk.model.VerticalLowPassFilteringMode;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
/**
* InterlaceFilter
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = false, defaultImpl = InterlaceFilter.class)
public class InterlaceFilter extends Filter {
@JsonProperty("mode")
private InterlaceMode mode;
@JsonProperty("verticalLowPassFilteringMode")
private VerticalLowPassFilteringMode verticalLowPassFilteringMode;
/**
* Get mode
* @return mode
*/
public InterlaceMode getMode() {
return mode;
}
/**
* Set mode
*
* @param mode
*/
public void setMode(InterlaceMode mode) {
this.mode = mode;
}
/**
* Get verticalLowPassFilteringMode
* @return verticalLowPassFilteringMode
*/
public VerticalLowPassFilteringMode getVerticalLowPassFilteringMode() {
return verticalLowPassFilteringMode;
}
/**
* Set verticalLowPassFilteringMode
*
* @param verticalLowPassFilteringMode
*/
public void setVerticalLowPassFilteringMode(VerticalLowPassFilteringMode verticalLowPassFilteringMode) {
this.verticalLowPassFilteringMode = verticalLowPassFilteringMode;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InterlaceFilter interlaceFilter = (InterlaceFilter) o;
return Objects.equals(this.mode, interlaceFilter.mode) &&
Objects.equals(this.verticalLowPassFilteringMode, interlaceFilter.verticalLowPassFilteringMode) &&
super.equals(o);
}
@Override
public int hashCode() {
return Objects.hash(mode, verticalLowPassFilteringMode, super.hashCode());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class InterlaceFilter {\n");
sb.append(" ").append(toIndentedString(super.toString())).append("\n");
sb.append(" mode: ").append(toIndentedString(mode)).append("\n");
sb.append(" verticalLowPassFilteringMode: ").append(toIndentedString(verticalLowPassFilteringMode)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
Java | UTF-8 | 1,755 | 2.546875 | 3 | [] | no_license | package tr2sql.db;
public enum KiyasTipi {
ESIT,
ESIT_DEGIL,
BASI_BENZER,
BASI_BENZEMEZ,
SONU_BENZER,
SONU_BENZEMEZ,
KUCUK,
BUYUK,
KUCUK_ESIT,
BUYUK_ESIT,
NULL,
NULL_DEGIL;
public KiyasTipi tersi() {
switch (this) {
case BUYUK:
return KUCUK_ESIT;
case KUCUK:
return BUYUK_ESIT;
case BUYUK_ESIT:
return KUCUK;
case KUCUK_ESIT:
return BUYUK;
case ESIT:
return ESIT_DEGIL;
case ESIT_DEGIL:
return ESIT;
case NULL:
return NULL_DEGIL;
case NULL_DEGIL:
return NULL;
case BASI_BENZER:
return BASI_BENZEMEZ;
case BASI_BENZEMEZ:
return BASI_BENZER;
case SONU_BENZER:
return SONU_BENZEMEZ;
case SONU_BENZEMEZ:
return SONU_BENZER;
}
throw new IllegalArgumentException("beklenmeyen deger!");
}
public static KiyasTipi kavramdanTipBul(Kavram kavram) {
String ad = kavram.getAd();
if (ad.equals("BUYUK"))
return BUYUK;
else if (ad.equals("KUCUK"))
return KUCUK;
else if (ad.equals("ESIT"))
return ESIT;
else if (ad.equals("ESIT_DEGIL"))
return ESIT_DEGIL;
else if (ad.equals("BASLAMAK"))
return BASI_BENZER;
else if (ad.equals("BITMEK"))
return SONU_BENZER;
else if (ad.equals("NULL"))
return NULL;
else return null;
}
}
|
Java | UTF-8 | 4,005 | 2.171875 | 2 | [
"MIT"
] | permissive | package com.rto.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.rto.bean.*;
import com.rto.util.DataUtility;
import com.rto.util.DataValidator;
import com.rto.util.ServletUtility;
@WebServlet("/BaseCtl")
public abstract class BaseCtl extends HttpServlet {
private static final Logger log = Logger.getLogger(BaseCtl.class);
private static final long serialVersionUID = 1L;
public static final String OP_SAVE = "Save";
public static final String OP_CANCEL = "Cancel";
public static final String OP_DELETE = "Delete";
public static final String OP_LIST = "List";
public static final String OP_SEARCH = "Search";
public static final String OP_VIEW = "View";
public static final String OP_NEXT = "Next";
public static final String OP_PREVIOUS = "Previous";
public static final String OP_NEW = "New";
public static final String OP_GO = "Go";
public static final String OP_BACK = "Back";
public static final String OP_LOG_OUT = "Logout";
public static final String OP_RESET = "Reset";
public static final String MSG_SUCCESS = "success";
public static final String MSG_ERROR = "error";
public BaseCtl() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
log.debug("BaseCtl service method start");
// Load the preloaded data required to display at HTML form
preload(request);
String op = DataUtility.getString(request.getParameter("operation"));
// Check if operation is not DELETE, VIEW, CANCEL, and NULL then
// perform input data validation
System.out.println("operation =" + op);
if (DataValidator.isNotNull(op) && !OP_CANCEL.equalsIgnoreCase(op) && !OP_VIEW.equalsIgnoreCase(op)
&& !OP_DELETE.equalsIgnoreCase(op) && !OP_RESET.equalsIgnoreCase(op)) {
// Check validation, If fail then send back to page with error
// messages
if (!validate(request)) {
BaseBean bean = (BaseBean) populateBean(request);
ServletUtility.setBean(bean, request);
ServletUtility.forward(getView(), request, response);
return;
}
}
log.debug("BaseCtl service method end");
super.service(request, response);
}
protected BaseBean populateBean(HttpServletRequest request) {
return null;
}
protected boolean validate(HttpServletRequest request) {
return true;
}
protected void preload(HttpServletRequest request) {
}
protected com.rto.bean.BaseBean populateDTO(BaseBean dto, HttpServletRequest request) {
log.debug("BaseCtl populate DTO method start");
String createdBy = request.getParameter("createdBy");
String modifiedBy = null;
UserBean userbean = (UserBean) request.getSession().getAttribute("user");
if (userbean == null) {
// If record is created without login
createdBy = "root";
modifiedBy = "root";
} else {
modifiedBy = userbean.getUserName();
// If record is created first time
if ("null".equalsIgnoreCase(createdBy) || DataValidator.isNull(createdBy)) {
createdBy = modifiedBy;
}
}
dto.setCreatedBy(createdBy);
dto.setModifiedBy(modifiedBy);
long cdt = DataUtility.getLong(request.getParameter("createdDatetime"));
if (cdt > 0) {
dto.setCreatedDateTime(DataUtility.getTimestamp(cdt));
} else {
dto.setCreatedDateTime(DataUtility.getCurrentTimestamp());
}
dto.setModifiedDateTime(DataUtility.getCurrentTimestamp());
log.debug("BaseCtl populate DTO method end");
return dto;
}
protected abstract String getView();
}
|
Java | UTF-8 | 1,500 | 3.796875 | 4 | [] | no_license | package assignment;
public class Prob2 {
public static void main(String[] args) {
System.out.println("<과제 1>");
solution1();
System.out.println();
System.out.println("<과제 2>");
solution2();
}
public static void solution1() {
String sourceString = "everyday we have is one more than we deserve";
String encodedString = "";
// 프로그램을 구현부 시작.
// 참고 : 문자 'a'의 정수값은 97이며, 'z'는 122입니다.
String[] source = sourceString.split(" ");
String[] result = new String[source.length];
for (int i=0; i<source.length; i++) {
char[] temp = source[i].toCharArray();
char[] temp2 = new char[temp.length];
for (int j=0; j<temp.length; j++) {
if (temp[j] == 'x' || temp[j] == 'y' || temp[j] == 'z') {
temp2[j] = (char) ((temp[j] + 3) - 26);
} else {
temp2[j] = (char) (temp[j] + 3);
}
}
result[i] = String.copyValueOf(temp2);
// System.out.println(result[i].toString());
}
for (int k=0; k<result.length; k++) {
encodedString += result[k];
encodedString += " ";
}
// 프로그램 구현부 끝.
System.out.println("암호화할 문자열 : " + sourceString);
System.out.println("암호화된 문자열 : " + encodedString);
}
public static void solution2() {
int sum = 0;
for (int i=1; i<=10; i++) {
for (int j=1; j<=i; j++) {
// System.out.println(j);
sum = sum + j;
}
}
System.out.println(sum);
}
}
|
Java | UTF-8 | 2,802 | 2.34375 | 2 | [] | no_license | package com.linkage.mobile72.sh.adapter;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.linkage.mobile72.sh.R;
import com.linkage.mobile72.sh.data.AccountChild;
import com.linkage.mobile72.sh.widget.CircularImage;
import com.linkage.mobile72.sh.Consts;
import com.linkage.lib.util.LogUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
public class PersonalInfoStrangerAdapter extends BaseAdapter {
private List<AccountChild> infos;
private LayoutInflater inflater;
private Context context;
private ImageLoader imageLoader;
public PersonalInfoStrangerAdapter(List<AccountChild> infos, Context context, ImageLoader imageLoader) {
this.infos = infos;
this.context = context;
this.imageLoader = imageLoader;
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return infos.size();
}
@Override
public AccountChild getItem(int position) {
LogUtils.e(position + " getItem");
return infos.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LogUtils.e(position + " getView");
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.personal_stranger_list_item,
parent, false);
holder = new ViewHolder();
holder.nameText = (TextView) convertView
.findViewById(R.id.user_name);
holder.nameText.setText(infos.get(position).getName());
holder.idText = (TextView) convertView
.findViewById(R.id.user_id);
// holder.schoolText = (TextView) convertView
// .findViewById(R.id.personal_info_school_text);
// holder.schoolText.setText(infos.get(position).getSchoolName());
// holder.schoolTypeText = (TextView) convertView
// .findViewById(R.id.personal_info_schooltype_text);
// holder.schoolTypeText.setText(infos.get(position).getSchoolType());
// holder.gradeText = (TextView) convertView
// .findViewById(R.id.personal_info_grade_text);
// holder.gradeText.setText(infos.get(position).getGrade());
holder.image = (CircularImage) convertView
.findViewById(R.id.user_avater);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
AccountChild child = getItem(position);
if(child != null) {
holder.idText.setText(child.getId()+"");
imageLoader.displayImage(Consts.SERVER_HOST + child.getPicture(), holder.image);
}
return convertView;
}
class ViewHolder {
private TextView nameText, idText, schoolText, schoolTypeText, gradeText;
private CircularImage image;
}
}
|
Java | UTF-8 | 1,646 | 3.640625 | 4 | [] | no_license | package xu.dfs.solutions;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Solution491 {
/*
* 递增子序列
*
* 这道题目就是数组中的深度优先搜索,需要注意以下几点:
*
* 1.整个数组可能是无序的,不能进行排序,比如 4 6 3 2 7
* 2.数组中可能会存在重复的数字,比如 1,2,3,1,1,1,因此在每一层递归的时候,使用一个 set 来保存当前这一层递归已经遍历过的数字,从而避免对
* 数组中的相同数字进行重复遍历。
*
*/
private List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
if (nums == null || nums.length == 0)
return ans;
func(nums, 0, new ArrayList<>(), nums[0]);
return ans;
}
// val 表示当前递增序列中最大的那一个值
private void func(int[] nums, int index, List<Integer> path, int val) {
if (path.size() >= 2)
ans.add(new ArrayList<>(path));
if (index == nums.length + 1)
return;
// 避免在同一层中多次遍历相同的数字
Set<Integer> visited = new HashSet<>();
for (int i = index; i < nums.length; i++) {
if (visited.contains(nums[i]))
continue;
visited.add(nums[i]);
if (nums[i] >= val || index == 0){
path.add(nums[i]);
func(nums, i + 1, path, nums[i]);
path.remove(path.size() - 1);
}
}
}
}
|
Markdown | UTF-8 | 3,172 | 4.03125 | 4 | [] | no_license | #
## 3.1 布尔表达式和判断
Python 中的布尔类型值:True 和 Flase 其中,注意这两个都是首字母大写。
但凡能够产生一个布尔值的表达式为**布尔表达式**:
```
1 > 2 # False
1 < 2 <3 # True
42 != '42' # True
'Name' == 'name' # False
'M' in 'Magic' # True
number = 12
number is 12 # True
```
>注1:不同类型的对象不能使用<、>、<=、=>进行比较,却可以使用==和!=。
>注2:浮点类型和整数类型虽然是不同类型,但不影响比较运算。还有,不等于!= 可以写作<> 。
话说,布尔类型可以比较吗?如:True > Flase,回答是可以的,Ture 和 Flase 对于计算机就像是 1 和 0 一样,所以结果是真,即True。
## 3.2 条件控制
定义格式:

用一句话该结构作用:如果...条件是成立的,就做...;反之,就做...
>所谓条件成立,指的是**返回值为****True****的布尔表达式。**
## 3.3 循环
**① for 循环**

把 for 循环所的事情概括成一句话就是:**于...其中的每一个元素,做...事情。**
打印九九乘法表:
```
for i in range(1, 10):
for j in range(1, i+1):
print('{}x{}={}\t'.format(i, j, i*j), end='')
print()
```
运行结果:
```
1x1=1
2x1=2 2x2=4
3x1=3 3x2=6 3x3=9
4x1=4 4x2=8 4x3=12 4x4=16
5x1=5 5x2=10 5x3=15 5x4=20 5x5=25
6x1=6 6x2=12 6x3=18 6x4=24 6x5=30 6x6=36
7x1=7 7x2=14 7x3=21 7x4=28 7x5=35 7x6=42 7x7=49
8x1=8 8x2=16 8x3=24 8x4=32 8x5=40 8x6=48 8x7=56 8x8=64
9x1=9 9x2=18 9x3=27 9x4=36 9x5=45 9x6=54 9x7=63 9x8=72 9x9=81
```
**② while 循环**

总结:只要...条件一成立,就一直做...
在循环过程中,可以使用 **break** 跳过循环,使用 **continue** 跳过该次循环。
在 Python 的 while 循环中,可以使用 else 语句,while … else 在循环条件为 false 时执行 else 语句块。如:
```
count = 0
while count < 3:
print (count)
count = count + 1
else:
print (count)
```
运行结果:
```
0
1
2
3
```
有 while … else 语句,当然也有 for … else 语句,for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,while … else 也是一样。如:
```
for num in range(10,20): # 迭代 10 到 20 之间的数字
for i in range(2,num): # 根据因子迭代
if num%i == 0: # 确定第一个因子
j=num/i # 计算第二个因子
print ('%d 是一个合数' % num)
break # 跳出当前循环
else: # 循环的 else 部分
print ('%d 是一个质数' % num)
```
运行结果:
```
10 是一个合数
11 是一个质数
12 是一个合数
13 是一个质数
14 是一个合数
15 是一个合数
16 是一个合数
17 是一个质数
18 是一个合数
19 是一个质数
```
|
Python | UTF-8 | 2,420 | 2.65625 | 3 | [] | no_license |
#pytesseract.pytesseract.tesseract_cmd = "C:\\Users\\Ashish.Gupta\\AppData\\Local\\Tesseract-OCR\\tesseract.exe"
from PIL import Image, ImageFile
import pytesseract
#import argparse
import cv2
import numpy as np
import re
#ap = argparse.ArgumentParser()
#ap.add_argument("-i", "--image", required=True,
# help="path to input image to be OCR'd")
#ap.add_argument("-p", "--preprocess", type=str, default="thresh",
# help="type of preprocessing to be done")
#args = vars(ap.parse_args())
ImageFile.LOAD_TRUNCATED_IMAGES = True
im = Image.open('D:\Personal\Machine Learning\PAN CARD\pancard11.jpg') # Can be many different formats.
pix = im.load()
# Get the width and hight of the image for iterating over
#print pix[x,y]
#print (im.size)
# load the example image and convert it to grayscale
image = cv2.imread('D:\Personal\Machine Learning\PAN CARD\pancard11.jpg')
img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply dilation and erosion to remove some noise
kernel = np.ones((1, 1), np.uint8)
img = cv2.dilate(img, kernel, iterations=2)
img = cv2.erode(img, kernel, iterations=2)
# Write image after removed noise
cv2.imwrite("removed_noise.png", img)
bad_chars =['~','`','!','@','#','$','%','^','&','*','(',')','{','}',"'",'[',']','|',':',';',',','<','>','.','?','/','+','=','_']
# Apply threshold to get image with only black and white
#img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)
# Write the image after apply opencv to do some ...
cv2.imwrite("thres.jpg", img)
pytesseract.pytesseract.tesseract_cmd = 'C:\\Users\\Ashish.Gupta\\AppData\\Local\\Tesseract-OCR\\tesseract.exe'
result = pytesseract.image_to_string(Image.open("thres.jpg"))
#print(result)
for i in bad_chars :
result = result.replace(i, '')
#new_line = result.split('\n')
print((result))
#r'\d{5}[a-zA-Z]\d{5}[a-zA-Z0-9]'
#[a-zA-Z0-9]{10,}
r1 = re.findall(r'\w{2}[a-zA-Z]\w{0}[P,C,H,A,B,G,J,L,F,T]\w{0}[A-Z]\w{3}[0-9]\w{0}[A-Z]',result)
#print(r1)
#for element in result:
# m = re.match("[a-zA-Z]{5,}", element)
# if m:
# print("START:", element)
l = [x for x in result if x.strip()]
#l = [w.replace(')', '') for w in l]
#print(l)
#cv2.imshow('Original image',image)
#cv2.imshow('Gray image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
Markdown | UTF-8 | 4,764 | 2.734375 | 3 | [] | no_license | ---
description: "Recette de Favoris Cookies banane chocolat"
title: "Recette de Favoris Cookies banane chocolat"
slug: 841-recette-de-favoris-cookies-banane-chocolat
date: 2020-05-23T20:52:07.920Z
image: https://img-global.cpcdn.com/recipes/7c1cd3f92d9968bf/751x532cq70/cookies-banane-chocolat-photo-principale-de-la-recette.jpg
thumbnail: https://img-global.cpcdn.com/recipes/7c1cd3f92d9968bf/751x532cq70/cookies-banane-chocolat-photo-principale-de-la-recette.jpg
cover: https://img-global.cpcdn.com/recipes/7c1cd3f92d9968bf/751x532cq70/cookies-banane-chocolat-photo-principale-de-la-recette.jpg
author: Della Conner
ratingvalue: 3.1
reviewcount: 9
recipeingredient:
- " bananes bien mres"
- " farine"
- " sucre"
- " beurre fondu"
- " ppites de chocolat"
- " oeuf"
- " sachet de levure chimique"
recipeinstructions:
- "Préchauffer le four à 190°c."
- "Écraser les bananes dans un bol. Ajouter l’œuf, le beurre puis le sucre et fouetter."
- "Incorporer tout en remuant la farine et la levure."
- "Terminer par ajouter les pépites de chocolat."
- "Faire de petites boules et les déposer sur une plaque de cuisson. Enfourner pour 6 à 8 minutes. Laisser refroidir pour qu’ils durcissent et déguster."
categories:
- Recette
tags:
- cookies
- banane
- chocolat
katakunci: cookies banane chocolat
nutrition: 217 calories
recipecuisine: French
preptime: "PT27M"
cooktime: "PT47M"
recipeyield: "4"
recipecategory: Déjeuner
---

Encore une fois à la recherche de recettes uniques d'inspiration cookies banane chocolat? La méthode de fabrication est pas trop difficile mais pas facile non plus. Si faux processus alors le résultat ne sera pas satisfaisant et même désagréable. Alors que le délicieux cookies banane chocolat devrait avoir un arôme et un goût qui obtenir provoquer notre appétit.
nombreuses choses qui plus ou moins affectent la qualité gustative de cookies banane chocolat, start du type d'ingrédients, puis la sélection des ingrédients frais, jusqu'à comment faire et servir. Pas besoin étourdi si veux prépare cookies banane chocolat délicieux à chez vous, car tant que vous connaissez le truc, ce plat peut être être plat spécial.
These cookies were very moist, very cakelike and gone very quickly! You will not like these if you like gooey cookies. Moins de beurre dans ces cookies avec de la banane et du chocolat, je les ai sur-dosé en pépites de chocolate t ca m'a fait un coeur coulant de ouf!
Eh bien, cette fois, nous essayons, nous allons, créer cookies banane chocolat vous-même à la maison. Gardez ingrédients qui sont simples, ce plat peut fournir des avantages en aidant à maintenir un corps sain pour vous et votre famille. Vous pouvez préparer Cookies banane chocolat utiliser 7 type de matériau et 5 étapes création. Voici les comment dans préparer le plat.
<!--inarticleads1-->
##### Les ingrédients nécessaires pour faire Cookies banane chocolat:
1. Fournir bananes bien mûres
1. farine
1. Obtenir sucre
1. Prenez beurre fondu
1. Utiliser pépites de chocolat
1. Fournir oeuf
1. Prenez sachet de levure chimique
Ajoute les pépites de chocolat (ou des carrés de chocolat concassés). Termine par ajouter la Cookies banane réalisés avec qq modifications en fonction de ce que j'avais dans le placard. Cookies petit déj banane-choco-flocon d'avoine Voir la recette. Ajoutez les flocons d'avoines et mélangez.
<!--inarticleads2-->
##### Étapes Pour faire Cookies banane chocolat:
1. Préchauffer le four à 190°c.
1. Écraser les bananes dans un bol. Ajouter l’œuf, le beurre puis le sucre et fouetter.
1. Incorporer tout en remuant la farine et la levure.
1. Terminer par ajouter les pépites de chocolat.
1. Faire de petites boules et les déposer sur une plaque de cuisson. Enfourner pour 6 à 8 minutes. Laisser refroidir pour qu’ils durcissent et déguster.
Faites des pépites avec les carrés de chocolat et incorporez-les à la préparation.. Cookies chocolat banane. bonjour tout le monde, voila de sublimes Cookies au chocolat et a la banane qu'a partager avec nous mon amie Lunetoiles Cette recette de cookies banane chocolat et flocons d'avoine est une très belle surprise ! Je vous présente aujourd'hui une valeur sûre en matière de biscuits. La recette provient de la bible "biscuits, sablés, cookies" de Martha Stewart. Voici la recette des cookies à la banane et au chocolat.
Comment allez-vous? Facile n'est-ce pas? Voilà comment set up cookies banane chocolat que vous pouvez pratiquer à la maison. J'espère que c'est utile et bonne chance!
|
Java | UTF-8 | 3,020 | 2.40625 | 2 | [
"Apache-2.0"
] | permissive | /* vim: set ts=2 et sw=2 cindent fo=qroca: */
package com.globant.katari.user.view;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractCommandController;
import com.globant.katari.hibernate.coreuser.SecurityUtils;
import com.globant.katari.user.application.UserFilterCommand;
import com.globant.katari.user.domain.User;
/** Spring MVC controller to show users.
*
* Subclasses need to override <code>createCommandBean</code> to retrieve
* a backing object for the current form. Use method injection to override
* <code>createCommandBean</code>.
*/
public abstract class UsersController extends AbstractCommandController {
/** The class logger.
*/
private static Logger log = LoggerFactory.getLogger(UsersController.class);
/** Default initialization for the controller.
*/
public UsersController() {
setCommandName("userFilter");
}
/** Process the request and return a <code>ModelAndView</code> instance
* describing where and how control should be forwarded.
*
* Populate the ModelAndView model with the command under the specified
* command name, as expected by the "spring:bind" tag.
*
* @param request The HTTP request we are processing.
*
* @param response The HTTP response we are creating.
*
* @param command The populated command object.
*
* @param error Validation errors holder.
*
* @exception Exception if the application logic throws an exception.
*
* @return the ModelAndView for the next view.
*/
protected final ModelAndView handle(final HttpServletRequest request,
final HttpServletResponse response, final Object command,
final BindException error) throws Exception {
log.trace("Entering handleRequestInternal");
UserFilterCommand userFilterCommand = (UserFilterCommand) command;
List<User> users = userFilterCommand.execute();
ModelAndView mav = new ModelAndView("users");
mav.addObject("users", users);
mav.addObject("command", userFilterCommand);
mav.addObject("currentUserId", SecurityUtils.getCurrentUser().getId());
mav.addObject("request", request);
log.trace("Leaving handleRequestInternal");
return mav;
}
/** Retrieve a backing object for the current form from the given request.
*
* @param request The HTTP request we are processing.
*
* @exception Exception if the application logic throws an exception.
*
* @return The command bean object.
*/
@Override
protected Object getCommand(final HttpServletRequest request)
throws Exception {
return createCommandBean();
}
/** This method is injected by AOP.
*
* @return Returns the command bean injected.
*/
protected abstract UserFilterCommand createCommandBean();
}
|
Python | UTF-8 | 1,497 | 2.625 | 3 | [] | no_license | import requests
import glob
import sys
import json
import io
import os.path
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("-f", "--folder", required=True,
help="images folder")
args = vars(ap.parse_args())
FOLDER=args["folder"]
def readFileFolder(strFolderName, suffix):
print strFolderName
file_list = []
st=strFolderName+"*."+suffix
for filename in glob.glob(st): #assuming gif
file_list.append(filename)
return file_list
def readBaseNameFolder(strFolderName, suffix):
print strFolderName
file_list = []
st=strFolderName+"*."+suffix
for filename in glob.glob(st): #assuming gif
basename=os.path.splitext(os.path.basename(filename))[0]
file_list.append(basename)
return file_list
def removeFileText(ls_imageFile, ls_txtFile):
for filetext in ls_txtFile:
if filetext not in ls_imageFile:
file_name=os.path.join(FOLDER, filetext+".txt")
os.remove(file_name)
for fileimage in ls_imageFiles:
if fileimage not in ls_txtFile:
file_name=os.path.join(FOLDER, fileimage+".png")
os.remove(file_name)
def display_lose_file(ls_imageFile, ls_txtFile):
for filetext in ls_txtFile:
if filetext not in ls_imageFile:
print filetext
for fileimage in ls_imageFiles:
if fileimage not in ls_txtFile:
print fileimage
ls_imageFiles=readBaseNameFolder(FOLDER, "png")
print ls_imageFiles
ls_txtFiles=readBaseNameFolder(FOLDER,"txt")
print ls_txtFiles
removeFileText(ls_imageFiles, ls_txtFiles)
#display_lose_file(ls_imageFiles, ls_txtFiles) |
Java | UTF-8 | 1,142 | 3.4375 | 3 | [] | no_license | import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
public class GoatLatin {
public String toGoatLatin(String S) {
String[] words = S.split(" ");
Character[] vowels = {'a','e','i','o','u','A','E','I','O','U'};
HashSet<Character> set = new HashSet<Character>(Arrays.asList(vowels));
List<String> out = new LinkedList<>();
for(int i = 0; i < words.length; i++) {
StringBuilder sb = new StringBuilder();
if(set.contains(words[i].charAt(0)))
sb.append(words[i]);
else
sb.append(words[i].substring(1)).append(words[i].charAt(0));
sb.append("ma");
for(int n = 0; n <= i; n++) sb.append('a');
out.add(sb.toString());
}
return String.join(" " , out);
}
public static void main(String[] args) {
String S = "I speak Goat Latin";
GoatLatin sol = new GoatLatin();
System.out.println(sol.toGoatLatin(S));
String[] test = {"a", "b", "c"};
System.out.println(String.join(" ", test));
}
}
|
Shell | UTF-8 | 1,480 | 3.25 | 3 | [] | no_license | #!/usr/bin/env bash
#
# This file has executed each time when container's starts
#
# tech-stack: ubuntu / nginx
#
# @author demmonico
# @image ubuntu-nginx
# @version v3.3
##### run once
if [ -f "${DMC_RUN_ONCE_FLAG}" ]; then
# run script once
source /run_once.sh
# rm flag
/bin/rm -f ${DMC_RUN_ONCE_FLAG}
fi
### prepare proxy.conf
NGINX_CONF_DIR="/etc/nginx/conf.d"
PROXY_TEMPLATE="${NGINX_CONF_DIR}/proxy.template"
PROXY_CONF="${NGINX_CONF_DIR}/proxy.conf"
PROXY_CUSTOM="${NGINX_CONF_DIR}/proxy.custom"
# copy conf file from custom file
if [ -f ${PROXY_CUSTOM} ]; then
yes | cp -rf ${PROXY_CUSTOM} ${PROXY_CONF}
# copy conf file from template
elif [ -f ${PROXY_TEMPLATE} ]; then
yes | cp -rf ${PROXY_TEMPLATE} ${PROXY_CONF}
# prepare upstream var
DMC_NGINX_APPUPSTREAM=${DMC_NGINX_APPUPSTREAM:-"server app:80;"}
# replace env vars
for i in _ {a..z} {A..Z}; do
for ENV_VAR in `eval echo "\\${!$i@}"`; do
if [ ${ENV_VAR} != 'ENV_VAR' ] && [ ${ENV_VAR} != 'i' ]; then
sed -i "s/{{ \$${ENV_VAR} }}/${!ENV_VAR}/" ${PROXY_CONF}
fi
done
done
fi
### run custom script if exists
CUSTOM_SCRIPT="${DMC_INSTALL_DIR}/custom.sh"
if [ -f ${CUSTOM_SCRIPT} ]; then
chmod +x ${CUSTOM_SCRIPT} && source ${CUSTOM_SCRIPT}
fi
if [ ! -z "${DMC_CUSTOM_RUN_COMMAND}" ]; then
eval ${DMC_CUSTOM_RUN_COMMAND}
fi
### FIX cron start
cron
### run supervisord
exec /usr/bin/supervisord -n
|
Python | UTF-8 | 4,098 | 3.953125 | 4 | [] | no_license | import time
import threading
# project #3 Choose Your Own Adventure Game, From CSV.file Story
# load story from filename
def loadStory(filename):
#put story into list
story = []
for line in open(filename):
#remove leading and trailing characters for nice output, break the string with seperator
story.append(line.strip().split(","))
return story
# Method to print main menu
def MainMenu():
print("****** Text Adventury Game v1.0 ******")
print("* *")
print("* 1 - New Game *")
print("* 2 - Load Game *")
print("* 3 - Quit *")
print("* *")
print("**************************************")
#load game from save.txt by row you are on
def loadGame(filename):
#index is the line user will be on
index = 1
try:
#open previously saved game
f = open(filename)
index = int(f.readline())
f.close()
# close when finished
except:
print("Error: No game could be found\n")
return index
# save game to saved.txt, saves by row # you are on
def saveGame(filename, index):
#open saved file and write to it by row num user is currently on
try:
f = open(filename, "w")
f.write(str(index))
#closer file when finished saving
f.close()
print(">>> Game Saved\n")
except:
print("Error saving game\n")
# options menu to print 3 choices for the user, decision 1 or 2 to continue with story or save game and continue playing
def OptionsMenu(option1, option2):
print("What do you want to do?")
#decision one to play game
print("1 - " + option1)
#decision two play game
print("2 - " + option2)
# decision 3 save game and continue playing
print("3 - Save Game")
# Main is where the game plays, user plays through and makes choices
def main():
#load story file
story = loadStory("story.csv")
#display main menu with 3 options
MainMenu()
index = 1
while True:
choice = input("> ")
print("")
#new game
if choice == "1":
index = 1
break
#load game from saved..txt
elif choice == "2":
index = loadGame("saved.txt")
break
#quit game
elif choice == "3":
exit(0)
else:
print("Error: Invalid choice, choose number between 1-3\n")
MainMenu()
while True:
#value1, value2, value3, value4,value5. From columns in each row in list/csv.file
#option refrences index for decision points to go to correct row and print
# options are the choices the user can take to continue in story
# read last line in list
question, option1, option2, index1, index2 = story[index-1]
print(question)
#
if (option1 == "") or (option2 == ""):
print(" ")
time.sleep(2)
main()
main().start()
#print choices for user while playing game
OptionsMenu(option1, option2)
while True:
#choice as users input
choice = input("> ")
print("")
# if user enters one display the next line by proper index
if choice == "1":
index = int(index1)
break
# if user enters 2 display the next line by proper index
elif choice == "2":
index = int(index2)
break
# if user enters 3 save game and continue playing, save into save.txt by row
elif choice == "3":
saveGame("saved.txt", index)
break
#if users choice is invalid reprent question and decisions
else:
print("Error: Invalid choice, choose number between 1-3\n")
print(",".join(story[index-1][:1]))
OptionsMenu(option1, option2)
# display main
main() |
Java | UTF-8 | 3,296 | 2.625 | 3 | [] | no_license | package com.freeman.httpurlconnection.httpurlconnection;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by Freeman on 10.01.2017.
*/
// Singletone
public class HttpProvider {
private static final String BASE_URL = "http://jsonplaceholder.typicode.com";
public static final String BASE_URL_HOME_TASK = "https://telranstudentsproject.appspot.com/_ah/api/contactsApi/v1";
private static HttpProvider provider;
private HttpProvider() {
}
public static HttpProvider getProvider(){
if (provider == null)
provider = new HttpProvider();
return provider;
}
public String get(String link) throws IOException {
String result = "";
URL url = new URL(BASE_URL + link);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(15000);
connection.setConnectTimeout(15000);
connection.setRequestProperty("Content-Type", "application/json");
connection.connect();
if (connection.getResponseCode() < 400) {
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader br = new BufferedReader(isr);
String line = "";
while ((line = br.readLine()) != null) {
result += line;
}
br.close();
}else {
InputStreamReader eisr = new InputStreamReader(connection.getErrorStream());
BufferedReader ebr = new BufferedReader(eisr);
String eLine = "";
while ((eLine = ebr.readLine()) != null){
result += eLine;
}
ebr.close();
}
return result;
}
public String post(String link, String data) throws IOException {
String result = "";
URL url = new URL(BASE_URL_HOME_TASK + link);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setReadTimeout(15000);
connection.setConnectTimeout(15000);
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoInput(true);
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
bw.write(data);
bw.flush();
bw.close();
os.close();
//Answer
BufferedReader br;
String line = "";
if (connection.getResponseCode() < 400){
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
}else {
br = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}
while ((line = br.readLine()) != null){
result += line;
}
br.close();
return result;
}
}
|
Java | UTF-8 | 2,320 | 2.28125 | 2 | [
"MIT"
] | permissive | package pl.java.borowiec.controller.test;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import pl.java.borowiec.performance_problem.Car;
import pl.java.borowiec.performance_problem.Person;
import pl.java.borowiec.service.performance.N1PerformanceService;
/**
* @author Sławomir Borowiec
* Module name : personalBlogCore
* Creating time : 14-04-2013 10:50:56
*/
@Controller
@RequestMapping("n1")
public class N1Controller {
private static final String VIEW_NAME = "performance/n1";
private Person slawek, pawel;
private Car ferrari, porsche, suzuki, fiat, polonez;
private void init() {
polonez = new Car("polonez", 17);
suzuki = new Car("suzuki", 5);
fiat = new Car("fiat", 12);
ferrari = new Car("ferrari", 1);
porsche = new Car("porsche", 2);
List<Car> pawelCars = new ArrayList<Car>();
List<Car> slawekCars = new ArrayList<Car>();
slawekCars.add(polonez);
slawekCars.add(fiat);
slawekCars.add(suzuki);
pawelCars.add(ferrari);
pawelCars.add(porsche);
slawek = new Person("slawek", "warszawa", slawekCars);
pawel = new Person("pawel", "gdansk", pawelCars);
}
@Autowired
private N1PerformanceService n1PerformanceService;
@RequestMapping(value = "/", method = RequestMethod.GET)
public String view(Model model) {
if (n1PerformanceService.countPerson() == 0) {
init();
n1PerformanceService.savePerson(slawek);
n1PerformanceService.savePerson(pawel);
}
List<Person> persons = new ArrayList<Person>();
persons.add(n1PerformanceService.lastNameIsLike("slawek").get(0));
model.addAttribute("persons", persons);
return VIEW_NAME;
}
@RequestMapping(value = "/problem", method = RequestMethod.GET)
public String viewProblem(Model model) {
if (n1PerformanceService.countPerson() == 0) {
init();
n1PerformanceService.savePerson(slawek);
n1PerformanceService.savePerson(pawel);
}
List<Person> persons = new ArrayList<Person>();
persons.add(n1PerformanceService.findByName("slawek"));
model.addAttribute("persons", persons);
return VIEW_NAME;
}
}
|
Java | UTF-8 | 625 | 2.8125 | 3 | [] | no_license | package jpu2016.dogfight.modele;
public class Plane extends Mobile{
private static int SPEED = 2;
private static int WIDTH = 100;
private static int HEIGHT = 30;
private static final String IMAGE = "plane.png";
private int player;
public Plane(int player, Direction direction, Position position, String image) {
super(direction, position, new Dimension(WIDTH, HEIGHT), SPEED, IMAGE);
this.player = player;
}
public boolean isPlayer(int player){
return player == this.player;
}
public boolean hit(){
this.getDogfightModel().removeMobile((IMobile) this);
return true;
}
} |
C# | UTF-8 | 504 | 2.9375 | 3 | [] | no_license | using System.Text;
namespace ChatRoomService.Infrastructure
{
static class ObjectHelper
{
public static string Dump<T>(this T x)
{
var t = typeof(T);
var props = t.GetProperties();
StringBuilder sb = new StringBuilder();
foreach (var item in props)
{
sb.Append($"{item.Name}:{item.GetValue(x, null)}; ");
}
sb.AppendLine();
return sb.ToString();
}
}
}
|
JavaScript | UTF-8 | 2,735 | 3.03125 | 3 | [] | no_license | document.addEventListener('DOMContentLoaded', function () { // Wait for Page to load.
var yourUrl = '/learnword';
var wordlist = sessionStorage.getItem("wordlist", wordlist);
if (wordlist == null) {
wordlist = document.getElementById("Select").value
} else {
document.getElementById("Select").value = wordlist;
};
// FUNCTIONS :
var setAudioClick = function (sw, data) { // Click event for replaying the test word.
sw.addEventListener('click', function() {
data.load();
data.play();
});
};
var setElementClick = function (data) { // Click event for selecting the answer boxes.
data.addEventListener('click', function () {
location.reload();
})
};
document.getElementById("Select").addEventListener("change", function () {
wordlist = document.getElementById("Select").value;
sessionStorage.setItem("wordlist", wordlist);
location.reload();
});
// Build the game table.
$(function(){
$.ajax({
url: yourUrl, //the URL to your node.js server that has data
dataType: 'json',
cache: false,
data: {select: wordlist}
}).done(function(data){ //"data" will be JSON. Do what you want with it.
var gameTable = document.getElementById('GameWords');
// var div = document.createElement('div');
if (data[0].image) {
var img = document.createElement('img');
img.setAttribute('src', data[0].image);
gameTable.appendChild(img);
} else {
var text = document.createTextNode(data[0].English);
gameTable.appendChild(text);
}
setElementClick(gameTable);
var sw = document.getElementById('Shawnee-Word');
var swel = document.createElement('input');
swel.setAttribute('type', 'text');
swel.setAttribute('id', 'Shawnee');
swel.setAttribute('disabled', true);
swel.setAttribute('style', 'width:'+data[0].Shawnee.length*30+'px');
swel.setAttribute('value', data[0].Shawnee)
sw.appendChild(swel);
if (data[0].audio) {
var audioel = document.createElement('audio');
audioel.setAttribute('id', 'audioel');
audioel.setAttribute('src', data[0].audio);
audioel.setAttribute('preload', 'auto');
sw.appendChild(audioel);
var audio = document.getElementById('audioel');
setAudioClick(sw, audio);
audio.load();
audio.play();
};
});
});
});
|
C++ | UTF-8 | 1,127 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
using namespace std;
int main() {
//freopen("2520.in", "r", stdin);
int l, c;
while(cin >> l >> c) {
int cidade[l][c];
int pos_treinador[2], pos_pokemon[2];
int distancia = 0;
for(int i = 0; i < l; i++) {
for(int j = 0; j < c; j++) {
cin >> cidade[i][j];
if(cidade[i][j] == 1) {
pos_treinador[0] = i;
pos_treinador[1] = j;
}
if(cidade[i][j] == 2) {
pos_pokemon[0] = i;
pos_pokemon[1] = j;
}
}
}
if(pos_treinador[0] > pos_pokemon[0]) {
distancia += pos_treinador[0] - pos_pokemon[0];
} else {
distancia += pos_pokemon[0] - pos_treinador[0];
}
if(pos_treinador[1] > pos_pokemon[1]) {
distancia += pos_treinador[1] - pos_pokemon[1];
} else {
distancia += pos_pokemon[1] - pos_treinador[1];
}
cout << distancia << endl;
}
return 0;
}
|
Java | UTF-8 | 1,119 | 2.203125 | 2 | [] | no_license | package com.vitamojo.Demo_API_RestAssured.TestCases;
import java.util.HashMap;
import java.util.Hashtable;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.vitamojo.Demo_API_RestAssured.API.UpdateCustomerAPI;
import com.vitamojo.Demo_API_RestAssured.TestSetup.TestSetup;
import com.vitamojo.Demo_API_RestAssured.TestUtils.Data;
import com.vitamojo.Demo_API_RestAssured.TestUtils.TestUtil;
import io.restassured.response.Response;
public class ValidateUpdateCustomerAPI extends TestSetup{
@Test(dataProviderClass=Data.class,dataProvider="data")
public void validateUpdateCustomerAPIWithValidAuthKey(Hashtable<String,String> data)
{
testLevelLog.get().assignAuthor("Ankit Singh");
HashMap mapOfField=new HashMap();
mapOfField.put("name",data.get("name"));
mapOfField.put("balance",Integer.parseInt(data.get("balance")));
Response response = UpdateCustomerAPI.sendRequestToUpdateCustomerWithValidAuthKey("cus_GRDnYilwrt5hsI", mapOfField);
TestUtil.logResponseInReport(response);
Assert.assertEquals(response.getStatusCode(),Integer.parseInt(data.get("expectedStatusCode")));
}
}
|
Java | UTF-8 | 394 | 3.125 | 3 | [] | no_license | package EstructurasJava;
public class Persona{
private String nombre;
private int edad;
private String direccion;
public Persona(String nombre, int edad, String direccion){
this.nombre = nombre;
this.edad = edad;
this.direccion = direccion;
}
public String toString(){
return nombre + ", "+ edad + " anios, vive en " + direccion;
}
} |
PHP | UTF-8 | 3,153 | 2.578125 | 3 | [] | no_license |
<html>
<head>
<title>Pet Shop</title>
<link href="style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<?php
include 'koneksi.php';
$id_nota=$_GET['id_nota'];
$tunai=$_GET['bayar'];
$kembalian=$_GET['kembalian'];
$query=mysql_query("SELECT id_nota_perawatan, nama_lengkap, tgl_transaksi, id_detail_perawatan, nama_perawatan,nama_kategori_hewan, kuantiti, detail_perawatan.harga_perawatan, detail_perawatan.diskon, subtotal, total_harga
FROM USER JOIN transaksi_perawatan USING (id_user)
JOIN detail_transaksi_perawatan USING (id_nota_perawatan)
JOIN detail_perawatan USING (id_detail_perawatan)
JOIN kategori_hewan USING (id_kategori_hewan)
JOIN perawatan USING (id_perawatan) WHERE id_nota_perawatan='$id_nota'");
$data=mysql_fetch_array($query);
?>
<center><h3>Struk Belanja - One Stop Pet Shop </h3></center>
<table border="0" width="50%" style="border-collapse:collapse;" align="left">
<tr>
<td>Id Nota</td>
<td>:</td>
<td><?php echo $id_nota;?></td>
</tr>
<tr>
<td>Tanggal</td>
<td>:</td>
<td><?php echo $data['tgl_transaksi'];?></td>
</tr>
<tr>
<td>Nama Pelanggan</td>
<td>:</td>
<td><?php echo $data['nama_lengkap'];?></td>
</tr>
</table>
<br>
<br>
<br>
<br>
<table width=90% align="left" border=1>
<tr>
<td>ID Detail Perawatan</td>
<td>Perawatan</td>
<td>Kategori Hewan</td>
<td>Kuantiti</td>
<td>Harga</td>
<td>Diskon(%)</td>
<td>Subtotal</td>
</tr>
<?php
$query1=mysql_query("SELECT id_nota_perawatan, nama_lengkap, tgl_transaksi, id_detail_perawatan, nama_perawatan,nama_kategori_hewan, kuantiti, detail_perawatan.harga_perawatan, detail_perawatan.diskon, subtotal, total_harga
FROM USER JOIN transaksi_perawatan USING (id_user)
JOIN detail_transaksi_perawatan USING (id_nota_perawatan)
JOIN detail_perawatan USING (id_detail_perawatan)
JOIN kategori_hewan USING (id_kategori_hewan)
JOIN perawatan USING (id_perawatan) WHERE id_nota_perawatan='$id_nota'");
$no=1;
while($data1=mysql_fetch_array($query1)){
$diskon=$data1['diskon']*100;
?>
<tr>
<td width="10%"><?php echo $data1['id_detail_perawatan']; ?></td>
<td width="20%"><?php echo $data1['nama_perawatan']; ?></td>
<td width="20%"><?php echo $data1['nama_kategori_hewan']; ?></td>
<td width="10%" ><?php echo $data1['kuantiti']; ?></td>
<td width="10%" ><?php echo $data1['harga_perawatan']; ?></td>
<td width="10%" ><?php echo $diskon; ?></td>
<td width="10%" ><?php echo $data1['subtotal']; ?></td>
</tr>
<?php $no++; } ?>
</table>
<br>
<br>
<br>
<br>
<BR>
<table width="50%" align=right>
<tr>
<td>Total</td>
<td>:</td>
<td><?php echo "Rp. $data[total_harga]";?></td>
</tr>
<tr>
<td>Tunai</td>
<td>:</td>
<td><?php echo "Rp. $tunai ";?></td>
</tr>
<tr>
<td>Kembalian</td>
<td>:</td>
<td><?php echo "Rp. $kembalian ";?></td>
</tr>
</table>
<script>
window.load = print_d();
function print_d(){
window.print();
}
</script>
</body>
</html> |
Python | UTF-8 | 536 | 3.671875 | 4 | [] | no_license | #!/usr/bin/python
# -*- coding: UTF-8 -*-
a = 2
b = 3
c = 2
if(a == c) :
print "a == 777c"
if(a == b):
print "xxxx"
raw_input("number end...")
a = "aaa"
b = "bbb"
c = "aaa"
if(a == c) :
print "a == c"
if(a == b):
print "xxxx"
raw_input("string end...")
list1 = [ 'runoob', 786 , 2.23, 'john', 70.2 ]
list2 = [ 'runoob', 786 , 2.23, 'john', 70.2 ]
list3 = [ 'runoob', 786 , 2.323, 'john', 70.2 ]
if(list1 == list2) :
print "list1 == list2"
if(list1 == list3):
print "list1 == list3"
raw_input("list1 end...")
|
C++ | UTF-8 | 1,502 | 2.9375 | 3 | [] | no_license | #include<cstdio>
#include<algorithm>
using namespace std;
const int N = 111;
int ori[N],tempOri[N],changed[N];
int n;
bool issame(int a[],int b[]) {
for(int i=1;i<=n;i++) {
if(a[i]!=b[i]) return false;
}
return true;
}
bool showarray(int a[]) {
for(int i=1;i<=n;i++) {
printf("%d",a[i]);
if(i<n)printf(" ");
}
printf("\n");
}
bool insertsort() {
bool flag = false;
for(int i=2;i<=n;i++) {
if(i!=2 && issame(tempOri,changed)) {
flag = true;
}
sort(tempOri,tempOri+i+1);
if(flag == true) {
return true;
}
}
return false;
}
void downjust(int low,int high) {
int i = low,j = i*2;
while(j<=high) {
if(j+1 <= high && tempOri[j+1] > tempOri[j]) {
j = j+1;
}
if(tempOri[j] > tempOri[i]) {
swap(tempOri[j],tempOri[i]);
i = j;
j = i*2;
}else{
break;
}
}
}
void heapsort() {
bool flag = false;
for(int i=n/2;i>=1;i--) {
downjust(i,n);
}
for(int i=n;i>1;i--) {
if(i != n && issame(tempOri,changed)) {
flag = true;
}
swap(tempOri[i],tempOri[1]);
downjust(1,i-1);
if(flag == true) {
showarray(tempOri);
return;
}
}
}
int main() {
scanf("%d",&n);
for(int i = 1;i<=n;i++) {
scanf("%d",&ori[i]);
tempOri[i] = ori[i];
}
for(int i=1;i<=n;i++) {
scanf("%d",&changed[i]);
}
if(insertsort()) {
printf("Insertion Sort\n");
showarray(tempOri);
} else {
printf("Heap Sort\n");
for(int i=1;i<=n;i++) {
tempOri[i] = ori[i];
}
heapsort();
}
return 0;
} |
C | UTF-8 | 378 | 2.71875 | 3 | [] | no_license | #include <stdio.h>
#include <conio.h>
void about(bool *isGameActiveP)
{
system("cls");
printf("The game was developed for programming coursework.\n");
printf("\nCreated by Ilya Konnov.\n");
printf("For more information check out my github profile: \nhttps://github.com/konnov-007");
printf("\n\nPress any key to return to main menu...");
getch();
*isGameActiveP = true;
}
|
Java | UTF-8 | 1,782 | 2.375 | 2 | [] | no_license | package com.arnold.common.mvp.utils;
import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import com.arnold.common.architecture.utils.Preconditions;
import com.arnold.common.mvp.IView;
import autodispose2.AutoDispose;
import autodispose2.AutoDisposeConverter;
import autodispose2.androidx.lifecycle.AndroidLifecycleScopeProvider;
/**
* 使用此类操作 RxLifecycle 的特性
*/
public class RxLifecycleUtils {
private RxLifecycleUtils() {
throw new IllegalStateException("you can't instantiate me!");
}
/**
* 绑定 Activity/Fragment 的指定生命周期
*
* @param view
* @param event
* @param <T>
* @return
*/
public static <T> AutoDisposeConverter<T> bindUntilEvent(@NonNull final IView view,
final Lifecycle.Event event) {
Preconditions.checkNotNull(view, "view == null");
if (view instanceof LifecycleOwner) {
return AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from((LifecycleOwner) view, event));
} else {
throw new IllegalArgumentException("view isn't LifecycleOwner");
}
}
/**
* 绑定 Activity/Fragment 的生命周期
*
* @param view
* @param <T>
* @return
*/
public static <T> AutoDisposeConverter<T> bindToLifecycle(@NonNull IView view) {
Preconditions.checkNotNull(view, "view == null");
if (view instanceof LifecycleOwner) {
return AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from((LifecycleOwner) view));
} else {
throw new IllegalArgumentException("view isn't LifecycleOwner");
}
}
}
|
PHP | UTF-8 | 378 | 2.625 | 3 | [] | no_license | <?php
class AreaModel extends Model {
//获取地区的名字
public function getAreaInfo($areaId) {
return $this->where("area_id = $areaId")->field("pid, area_name")->find();
}
//获取一个id下的所有地区
public function getAreaList($pid) {
return $this->where("pid = $pid")->field("area_id, area_name")->select();
}
}
|
C | UTF-8 | 378 | 2.78125 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<sys/types.h>
int main() {
char buf1[17] = "abcdefghijklmnop", buf2[17] = "ABCDEFGHIJKLMNOP";
int fp = open("Hole.txt", O_RDWR|O_CREAT|O_EXCL, 0755);
write(fp, buf1, 16);
lseek(fp, 48L, SEEK_SET);
write(fp, buf2, 16);
close(fp);
system("less Hole.txt");
return 0;
}
|
PHP | UTF-8 | 2,738 | 2.59375 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace app\models;
use Yii;
/**
* This is the model class for table "permissions".
*
* @property string $permissionID
* @property string $moduleID
* @property string $entityActionID
* @property string $groupID
* @property int $access
* @property int $active
* @property string $insertedBy
* @property string $dateCreated
* @property string $updatedBy
* @property string $dateModified
*
* @property Groups $group
* @property EntityActions $entityAction
* @property Modules $module
*/
class Permissions extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'permissions';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['moduleID', 'entityActionID', 'groupID'], 'required'],
[['moduleID', 'entityActionID', 'groupID', 'insertedBy', 'updatedBy'], 'integer'],
[['dateCreated', 'dateModified'], 'safe'],
// [['access', 'active'], 'string', 'max' => 3],
[['moduleID', 'entityActionID', 'groupID'], 'unique', 'targetAttribute' => ['moduleID', 'entityActionID', 'groupID']],
[['groupID'], 'exist', 'skipOnError' => true, 'targetClass' => Groups::className(), 'targetAttribute' => ['groupID' => 'groupID']],
[['entityActionID'], 'exist', 'skipOnError' => true, 'targetClass' => EntityActions::className(), 'targetAttribute' => ['entityActionID' => 'entityActionID']],
[['moduleID'], 'exist', 'skipOnError' => true, 'targetClass' => Modules::className(), 'targetAttribute' => ['moduleID' => 'moduleID']],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'permissionID' => 'Permission ID',
'moduleID' => 'Module ID',
'entityActionID' => 'Entity Action ID',
'groupID' => 'Group ID',
'access' => 'Access',
'active' => 'Active',
'insertedBy' => 'Inserted By',
'dateCreated' => 'Date Created',
'updatedBy' => 'Updated By',
'dateModified' => 'Date Modified',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getGroup()
{
return $this->hasOne(Groups::className(), ['groupID' => 'groupID']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getEntityAction()
{
return $this->hasOne(EntityActions::className(), ['entityActionID' => 'entityActionID']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getModule()
{
return $this->hasOne(Modules::className(), ['moduleID' => 'moduleID']);
}
}
|
JavaScript | UTF-8 | 5,096 | 2.671875 | 3 | [
"MIT"
] | permissive | 'use strict';
var yahooFinance = require('yahoo-finance');
var logger = require('./logger');
function dateToYyyyMmDd(date) {
function pad(s) { return (s < 10) ? '0' + s : s; }
return [date.getFullYear(), pad(date.getMonth()+1), pad(date.getDate())].join('-');
}
module.exports = function (stocks, callback) {
var result = [];
var symbols = {}; // will be an array
var olderPurchaseDate = new Date();
stocks.forEach(function(stock) {
symbols[stock.symbol] = null;
if (stock.purchaseDate && (stock.purchaseDate < olderPurchaseDate)) {
olderPurchaseDate = stock.purchaseDate;
}
});
symbols = Object.keys(symbols);
var fromDate = new Date();
fromDate.setMonth(fromDate.getMonth() - 1);
var toDate = new Date();
//console.log(dateToYyyyMmDd(fromDate));
yahooFinance.historical({
symbols: symbols,
from: dateToYyyyMmDd(fromDate),
to: dateToYyyyMmDd(toDate),
// period: 'd' // 'd' (daily), 'w' (weekly), 'm' (monthly), 'v' (dividends only)
}, function (err, quotes) {
if (err) {
logger.error('An error occured while getting quotes history from Yahoo Finance: "%s"', err);
return;
}
//console.log('yahoo', err, quotes);
//http://www.canbike.org/information-technology/yahoo-finance-url-download-to-a-csv-file.html
yahooFinance.snapshot({
symbols: symbols,
fields: [
's', // symbol
'n', // pretty name
'x', // exchange name (PAR)
//'c4', // currency (not implemented by the node module)
'p', // previous close
'o', // open
'g', // day's low
'h', // day's high
'j', // 52-week low
'k', // 52-week high
't1', // last trade time
'l1', // last trade price
'v' // current volume
],
}, function (err, snapshot) {
if (err) {
logger.error('An error occured while getting quotes snapshot from Yahoo Finance: "%s"', err);
return;
}
//console.log(err, snapshot);
var currents = {};
snapshot.forEach(function(stock) {
currents[stock.symbol] = stock;
});
// get dividends for every symbols since the older purchase date
yahooFinance.historical({
symbols: symbols,
from: dateToYyyyMmDd(olderPurchaseDate),
to: dateToYyyyMmDd(toDate),
period: 'v'
}, function (err, stockDividends) {
if (err) {
logger.error('An error occured while getting dividends from Yahoo Finance: "%s"', err);
return;
}
stocks.forEach(function(stock) {
var symbol = stock.symbol;
if (!quotes[symbol].length) {
logger.error('Symbol not found: "%s"', symbol);
return;
} else {
var last = quotes[symbol][quotes[symbol].length - 1];
var current = currents[symbol];
var close = current.previousClose; // may be last.close or last.adjClose, but it seems not to be always right.
var earnedDividends = 0;
stockDividends[symbol].forEach(function(stockDividend) {
if (stockDividend.date > stock.purchaseDate) {
earnedDividends += stock.quantity * stockDividend.dividends;
}
});
result.push({
//_raw: quotes[symbol],
symbol: symbol,
name: current.name,
currency: (current.currency ? current.currency : ''),
place: current.stockExchange,
last: {
price: close, // == lastClose
date: new Date(last.date),
open: last.open,
close: close,
high: last.high,
low: last.low,
volume: last.volume
},
day: {
price: current.lastTradePriceOnly,
date: current.lastTradeTime, // to date?
open: current.open,
high: current.daysHigh,
low: current.daysLow,
volume: current.volume,
},
fiftyTwoWeeks: {
high: current['52WeekHigh'],
low: current['52WeekLow']
},
purchase: {
date: stock.purchaseDate,
price: stock.purchasePrice,
quantity: stock.quantity
},
gain: {
withFees: stock.quantity * (close - stock.purchasePrice),
withoutFees: stock.quantity * (close - stock.purchasePrice) - stock.purchaseFees - stock.saleFees
},
dividends: {
earned: earnedDividends,
last: (stockDividends[symbol].length ? stockDividends[symbol][stockDividends[symbol].length - 1].dividends : 0),
date: (stockDividends[symbol].length ? stockDividends[symbol][stockDividends[symbol].length - 1].date : null)
},
fees: {
purchase: stock.purchaseFees,
sale: stock.saleFees
},
variations: {
sincePurchase: (stock.purchaseDate ? ((current.lastTradePriceOnly / stock.purchasePrice) * 100) - 100 : 0),
sinceOpen: ((current.lastTradePriceOnly / current.open) * 100) - 100,
sincePreviousDay: ((close / quotes[symbol][quotes[symbol].length - 1 - 1].close) * 100) - 100,
sinceFiveDays: ((close / quotes[symbol][quotes[symbol].length - 1 - 5].close) * 100) - 100,
sinceThirtyDays: ((close / quotes[symbol][0].close) * 100) - 100
}
});
}
});
//console.log('Result:', result);
callback(result);
});
});
});
};
|
C | UTF-8 | 603 | 3.09375 | 3 | [] | no_license | #include "fthread.h"
#include "stdio.h"
/* use the base pthread */
void* pr (void *text)
{
int i;
for (i=0;i<10;i++) {
fprintf (stdout,"%s",(char*)text);
}
return NULL;
}
int main(void)
{
int v, *cell = &v;
ft_thread_t th1 = NULL, th2 = NULL;
pthread_t pth1, pth2;
pth1 = ft_pthread (th1);
pth2 = ft_pthread (th2);
pthread_create (&pth1,NULL,pr,"Hello ");
pthread_create (&pth2,NULL,pr,"World!\n");
pthread_join (pth1,(void**)&cell);
pthread_join (pth2,(void**)&cell);
fprintf (stdout,"exit\n");
return 0;
}
/* result
NONDETERMINISTIC
end result */
|
Python | UTF-8 | 543 | 3.671875 | 4 | [] | no_license | largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" : break
#cvalue = num
try:
ivalue = int(num)
except:
print("Invalid Output")
if largest is None:
largest = ivalue
elif ivalue>largest:
largest = ivalue
elif smallest is None:
smallest = ivalue
elif ivalue<smallest:
smallest = ivalue
#print(num)
print("Maximum is ", largest)
print("Minimum is ", smallest) |
C++ | UTF-8 | 2,037 | 3.046875 | 3 | [
"Zlib"
] | permissive | #include <Engine/Core/Camera.h>
#include <glm/gtc/matrix_transform.hpp>
#include <cstdio>
using namespace glm;
namespace engine
{
Camera::Camera(const vec3 &position, float aspectRatio, float FoV, float nearDistance, float farDistance)
: mPosition(position), mAspectRatio(aspectRatio), mFoV(FoV), mNearDistance(nearDistance), mFarDistance(farDistance), mYaw(0.0f), mPitch(0.0f)
{
}
Camera::Camera(void)
: mPosition(vec3(0.0f, 0.0f, 0.0f)), mAspectRatio(4.0f / 3.0f), mFoV(60.0f), mNearDistance(0.1f), mFarDistance(100.0f), mYaw(0.0f), mPitch(0.0f)
{
}
Camera::~Camera(void)
{
}
void Camera::Rotate(float yaw, float pitch)
{
mYaw += yaw;
mPitch += pitch;
}
mat4 Camera::GetProjectionMatrix() const
{
return perspective(radians(mFoV), mAspectRatio, mNearDistance, mFarDistance);
}
mat4 Camera::GetViewMatrix() const
{
const vec3 direction = GetDirection();
const vec3 right = GetRight();
const vec3 up = cross(right, direction);
return lookAt(mPosition, mPosition + direction, up);
}
vec3 Camera::GetDirection() const
{
return vec3(
cosf(mPitch) * sinf(mYaw),
sinf(mPitch),
cosf(mPitch) * cosf(mYaw)
);
}
vec3 Camera::GetRight() const
{
return vec3(-cosf(mYaw), 0.0f, sinf(mYaw));
}
vec3 Camera::GetUp() const
{
return cross(GetRight(), GetDirection());
}
Frustum Camera::GetFrustum() const
{
const vec3 center = mPosition + GetDirection() * mFarDistance * 0.5f;
return Frustum(mPosition, center, GetUp(), mFoV, mAspectRatio, mNearDistance, mFarDistance);
}
void Camera::SetDirection(const glm::vec3 &direction)
{
const vec3 dir(normalize(direction));
mPitch = asinf(dir.y);
mYaw = atan2f(dir.x, dir.z);
}
void Camera::SetLookAtPoint(const glm::vec3 &p)
{
SetDirection(p - mPosition);
}
}
|
Markdown | UTF-8 | 592 | 3.203125 | 3 | [
"MIT"
] | permissive | # MdTable.Insert Method
**Declaring Type:** [MdTable](../index.md)
Inserts the a row at the specified index.
```csharp
public void Insert(int index, MdTableRow row);
```
## Parameters
`index` int
The index (zero\-based) to insert the row at.
`row` [MdTableRow](../../MdTableRow/index.md)
The row to insert into the table.
## Exceptions
ArgumentNullException
Thrown when `row` is `null`.
ArgumentOutOfRangeException
Thrown when `index` is negative or greater than the number of rows in the table.
___
*Documentation generated by [MdDocs](https://github.com/ap0llo/mddocs)*
|
Java | UTF-8 | 509 | 1.640625 | 2 | [] | no_license | package com.cardinfolink.application;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//i'm fine ,and you ?
//i have do some thing in master
//ddddd
//test
//进行v2.0开发
//完成v2.0开发
}
}
|
TypeScript | UTF-8 | 41,733 | 3.140625 | 3 | [] | no_license | /// <reference path="_fakeBABYLON.ts"/>
module mathis {
export const PI=Math.PI
export const cos=Math.cos
export const sin=Math.sin
export const exp =Math.exp
export const sqrt=Math.sqrt
//
// export enum Direction{vertical,horizontal,slash,antislash}
// export var myFavoriteColors={
// green:new BABYLON.Color3(124 / 255, 252 / 255, 0)
// //greenMathis:new Color(new RGB_range255(124,252,0))
// }
export class UV{
u:number
v:number
constructor(u:number,v:number){
this.u=u
this.v=v
}
}
export class M22{
m11:number=0
m12:number=0
m21:number=0
m22:number=0
determinant():number{
return this.m11*this.m22-this.m21*this.m12
}
inverse():M22{
let res=new M22()
let det=this.determinant()
res.m11=this.m22/det
res.m22=this.m11/det
res.m12=-this.m12/det
res.m21=-this.m21/det
return res
}
multiplyUV(uv:UV):UV{
return new UV(this.m11*uv.u+this.m12*uv.v,this.m21*uv.u+this.m22*uv.v)
}
}
export class XYZ extends BABYLON.Vector3 implements HasHashString{
//private xyz:XYZ
//get x(){return this.xyz.x}
//get y(){return this.xyz.y}
//get z(){return this.xyz.z}
//set x(x:number){this.xyz.x=x}
//set y(y:number){this.xyz.y=y}
//set z(z:number){this.xyz.z=z}
static lexicalOrder=(a:XYZ,b:XYZ)=>{
if (a.x!=b.x) return a.x-b.x
else if (a.y!=b.y) return a.y-b.y
else if (a.z!=b.z) return a.z-b.z
else return 0
}
static lexicalOrderInverse=(a:XYZ,b:XYZ)=>{
return -XYZ.lexicalOrder(a,b)
}
/**it is important to rount the number for hash. Because we want that two almost equal vectors have the same hash*/
static nbDecimalForHash=5
static resetDefaultNbDecimalForHash(){XYZ.nbDecimalForHash=5}
get hashString():string{return roundWithGivenPrecision(this.x,XYZ.nbDecimalForHash)+','+roundWithGivenPrecision(this.y,XYZ.nbDecimalForHash)+','+roundWithGivenPrecision(this.z,XYZ.nbDecimalForHash)}
constructor( x:number, y:number, z:number) {
super(x,y,z)
}
static newZero():XYZ{
return new XYZ(0,0,0)
}
static newFrom(vect:XYZ):XYZ{
if (vect==null) return null
return new XYZ(vect.x,vect.y,vect.z)
}
static newOnes():XYZ{
return new XYZ(1,1,1)
}
static newRandom():XYZ{
return new XYZ(Math.random(),Math.random(),Math.random())
}
static temp0(x,y,z):XYZ{
tempXYZ0.copyFromFloats(x,y,z)
return tempXYZ0
}
static temp1(x,y,z):XYZ{
tempXYZ1.copyFromFloats(x,y,z)
return tempXYZ1
}
// static temp2(x,y,z):XYZ{
// tempXYZ2.copyFromFloats(x,y,z)
// return tempXYZ2
// }
// static temp3(x,y,z):XYZ{
// tempXYZ3.copyFromFloats(x,y,z)
// return tempXYZ3
// }
// static temp4(x,y,z):XYZ{
// tempXYZ4.copyFromFloats(x,y,z)
// return tempXYZ4
// }
// static temp5(x,y,z):XYZ{
// tempXYZ5.copyFromFloats(x,y,z)
// return tempXYZ5
// }
// newCopy():XYZ{
// return new XYZ(this.x,this.y,this.z)
//}
add(vec:XYZ):XYZ{
geo.add(this,vec,this)
return this
}
resizes(vec:XYZ):XYZ{
this.x*=vec.x
this.y*=vec.y
this.z*=vec.z
return this
}
multiply(vec:XYZ):XYZ{
this.x*=vec.x
this.y*=vec.y
this.z*=vec.z
return this
}
length():number{
return geo.norme(this)
}
lengthSquared():number{
return geo.squareNorme(this)
}
substract(vec:XYZ):XYZ{
geo.substract(this,vec,this)
return this
}
scale(factor:number):XYZ{
geo.scale(this,factor,this)
return this
}
copyFrom(vect:XYZ):XYZ{
this.x=vect.x
this.y=vect.y
this.z=vect.z
return this
}
copyFromFloats(x:number,y:number,z:number):XYZ{
this.x=x
this.y=y
this.z=z
return this
}
changeBy(x:number, y:number, z:number){
this.x=x
this.y=y
this.z=z
return this
}
normalize():XYZ{
var norm=geo.norme(this)
if (norm<geo.epsilon) throw 'be careful, you have normalized a very small vector'
return this.scale(1/norm)
}
almostEqual(vect:XYZ){
return geo.xyzAlmostEquality(this,vect)
}
toString(deci=2):string{
return '('+this.x.toFixed(deci)+','+this.y.toFixed(deci)+','+this.z.toFixed(deci)+')'
}
}
var tempXYZ0=new XYZ(0,0,0)
var tempXYZ1=new XYZ(0,0,0)
//TODO rewrite the not-in-place methods
export class XYZW extends BABYLON.Quaternion{
constructor( x:number, y:number, z:number,w:number) {
super(x,y,z,w)
}
multiply(quat:XYZW):XYZW{
geo.quaternionMultiplication(quat,this,this)
return this
}
}
export class Hash {
static orientedSegmentTuple(link:[Vertex,Vertex]):string{
return link[0].hashNumber+','+link[1].hashNumber
}
static orientedSegment(a:Vertex,b:Vertex):string{
return a.hashNumber+','+b.hashNumber
}
static segment(a : Vertex,b : Vertex) : string {
return Segment.segmentId(a.hashNumber,b.hashNumber);
}
static segmentOrd(a : Vertex,b : Vertex):[Vertex,Vertex] {
if(a.hashNumber > b.hashNumber) [a,b] = [b,a];
return [a,b];
}
static quad(a : Vertex,b : Vertex,c : Vertex,d : Vertex) : string {
[a,b,c,d] = Hash.quadOrd(a,b,c,d);
return a.hashNumber + "," + b.hashNumber + "," + c.hashNumber + "," + d.hashNumber;
}
static quadOrd(a : Vertex,b : Vertex,c : Vertex,d : Vertex) {
while(a.hashNumber > b.hashNumber || a.hashNumber > c.hashNumber || a.hashNumber > d.hashNumber)
[a,b,c,d] = [b,c,d,a];
if(b.hashNumber < d.hashNumber)
[b,d] = [d,b];
return [a,b,c,d];
}
}
export class Positioning{
position:XYZ = new XYZ(0,0,0)
frontDir:XYZ = new XYZ(1, 0, 0)
upVector:XYZ = new XYZ(0, 1, 0)
scaling=new XYZ(1,1,1)
private defaultUpDirIfTooSmall=new XYZ(1,1,0)
private defaultFrontDirIfTooSmall=new XYZ(0,0,1)
copyFrom(positionning:Positioning):void{
this.position=XYZ.newFrom(positionning.position)
this.upVector=XYZ.newFrom(positionning.upVector)
this.frontDir=XYZ.newFrom(positionning.frontDir)
this.scaling=XYZ.newFrom(positionning.scaling)
}
changeFrontDir(vector:XYZ):void {
geo.orthonormalizeKeepingFirstDirection(vector, this.upVector, this.frontDir, this.upVector)
}
changeUpVector(vector:XYZ):void {
geo.orthonormalizeKeepingFirstDirection( this.upVector,vector , this.upVector,this.frontDir)
}
setOrientation(frontDir,upVector){
this.upVector=new XYZ(0, 0, 0)
this.frontDir=new XYZ(0, 0, 0)
geo.orthonormalizeKeepingFirstDirection( frontDir,upVector , this.frontDir,this.upVector)
}
quaternion(preserveUpVectorInPriority=true):XYZW{
if (this.frontDir==null && this.upVector==null) throw 'you must precise a frontDir or a upVector or both of them'
else if (this.frontDir==null) {
this.frontDir=new XYZ(0,0,0)
geo.getOneOrthonormal(this.upVector,this.frontDir)
}
else if (this.upVector==null){
this.upVector=new XYZ(0,0,0)
geo.getOneOrthonormal(this.frontDir,this.upVector)
}
if (this.frontDir.length()<geo.epsilon) {
this.frontDir=this.defaultFrontDirIfTooSmall
logger.c('a tangent was too small, and so replaced by a default one')
}
if (this.upVector.length()<geo.epsilon) {
this.upVector=this.defaultUpDirIfTooSmall
logger.c('a normal was too small, and so replaced by a default one')
}
let quaternion=new XYZW(0,0,0,1)
geo.twoVectorsToQuaternion(this.frontDir,this.upVector,!preserveUpVectorInPriority,quaternion)
return quaternion
}
applyToMeshes(meshes:BABYLON.Mesh[]){
let quaternion=null
if (this.frontDir!=null||this.upVector!=null) quaternion=this.quaternion()
for (let mesh of meshes){
if(this.scaling!=null) {
if (mesh.scaling==null) mesh.scaling=new XYZ(1,1,1)
mesh.scaling.x=this.scaling.x
mesh.scaling.y=this.scaling.y
mesh.scaling.z=this.scaling.z
}
if(quaternion!=null) {
if (mesh.rotationQuaternion==null) mesh.rotationQuaternion=new XYZW(0,0,0,1)
mesh.rotationQuaternion.x=quaternion.x
mesh.rotationQuaternion.y=quaternion.y
mesh.rotationQuaternion.z=quaternion.z
mesh.rotationQuaternion.w=quaternion.w
}
if(this.position!=null) {
if (mesh.position==null) mesh.position=new XYZ(0,0,0)
mesh.position.x=this.position.x
mesh.position.y=this.position.y
mesh.position.z=this.position.z
}
}
}
applyToMesh(mesh:BABYLON.Mesh){
this.applyToMeshes([mesh])
}
applyToVertices(vertices:Vertex[]){
let quaternion=this.quaternion()
let matrix=new MM()
geo.quaternionToMatrix(quaternion,matrix)
for (let vertex of vertices){
vertex.position.multiply(this.scaling)
geo.multiplicationVectorMatrix(matrix,vertex.position,vertex.position)
vertex.position.add(this.position)
}
}
//smoothParam = 0.5
//
// almostEqual(camCarac:Positioning):boolean {
// return geo.xyzAlmostEquality(this.position, camCarac.position) && geo.xyzAlmostEquality(this.upVector, camCarac.upVector) && geo.xyzAlmostEquality(this.frontDir, camCarac.frontDir)
// }
//
// goCloser(positioning:Positioning):void {
// geo.between(positioning.position, this.position, this.smoothParam, this.position)
// geo.between(positioning.upVector, this.upVector, this.smoothParam, this.upVector)
// geo.between(positioning.frontDir, this.frontDir, this.smoothParam, this.frontDir)
// }
// copyFrom(positioning:Positioning) {
// geo.copyXYZ(positioning.position, this.position)
// geo.copyXYZ(positioning.upVector, this.upVector)
// geo.copyXYZ(positioning.frontDir, this.frontDir)
// }
//
// changeFrontDir(vector:XYZ):void {
// geo.orthonormalizeKeepingFirstDirection(vector, this.upVector, this.frontDir, this.upVector)
// }
// changeUpVector(vector:XYZ):void {
// geo.orthonormalizeKeepingFirstDirection( this.upVector,vector , this.upVector,this.frontDir)
// }
}
export class MM extends BABYLON.Matrix{
//private mm:MM
//get m(){return this.mm.m}
//public m=new Float32Array(16)
constructor(){
super()
}
static newIdentity():MM{
var res=new MM()
res.m[0]=1
res.m[5]=1
res.m[10]=1
res.m[15]=1
return res
}
static newFrom(matr:MM):MM{
var res=new MM()
for (var i=0;i<16;i++) res.m[i]=matr.m[i]
return res
}
static newRandomMat():MM{
var res=new MM()
for (var i=0;i<16;i++) res.m[i]=Math.random()
return res
}
static newZero():MM{
return new MM()
}
equal(matr:MM):boolean{
return geo.matEquality(this,matr)
}
almostEqual(matr:MM):boolean{
return geo.matAlmostEquality(this,matr)
}
leftMultiply(matr:MM):MM{
geo.multiplyMatMat(matr,this,this)
return this
}
rightMultiply(matr:MM):MM{
geo.multiplyMatMat(this,matr,this)
return this
}
inverse():MM{
geo.inverse(this,this)
return this
}
copyFrom(matr:MM):MM{
geo.copyMat(matr,this)
return this
}
transpose():MM{
geo.transpose(this,this)
return this
}
toString():string{
return "\n"+
this.m[0]+this.m[1]+this.m[2]+this.m[3]+"\n"+
this.m[4]+this.m[5]+this.m[6]+this.m[7]+"\n"+
this.m[8]+this.m[9]+this.m[10]+this.m[11]+"\n"+
this.m[12]+this.m[13]+this.m[14]+this.m[15]+"\n"
}
}
export class Link{
to:Vertex
opposites:Link[]
weight:number
customerOb:any=null
constructor(to:Vertex){
if (to==null) throw 'a links is construct with a null vertex'
this.to=to
}
}
/** An element of a graph */
export class Vertex {
static hashCount=0
private _hashCode:number
get hashNumber():number{return this._hashCode}
get hashString():string{return this._hashCode+''}
/**link lead to an other vertex*/
links:Link[]=[]
/**position in the 3d space*/
position:XYZ
//isInvisible=false
dichoLevel=0
param:XYZ
markers:Vertex.Markers[]=[]
importantMarker:Vertex.Markers
customerObject:any={}
setPosition(x:number,y:number,z:number,useAlsoTheseValuesForParam=true):Vertex{
this.position=new XYZ(x,y,z)
if(useAlsoTheseValuesForParam) this.param=new XYZ(x,y,z)
return this
}
hasMark(mark:Vertex.Markers):boolean{
return(this.markers.indexOf(mark)!=-1)
}
constructor(){
this._hashCode=Vertex.hashCount++
}
getOpposites(vert1:Vertex):Vertex[]{
let fle=this.findLink(vert1)
if (fle==null) throw "the vertex is not a neighbor. Probably your neighborhood relation is not symetric. " +
"Please, perform the graph analysis, with the help of the function linkModule.checkTheRegularityOfAGRaph"
if (fle.opposites==null) return null
let res:Vertex[]=[]
for (let li of fle.opposites) res.push(li.to)
return res
}
hasBifurcations():boolean{
for (let link of this.links){
if (link.opposites!=null && link.opposites.length>1) return true
}
return false
}
hasVoisin(vertex:Vertex):boolean{
for (let link of this.links){
if (link.to==vertex) return true
}
return false
}
isBorder(){return this.hasMark(Vertex.Markers.border)}
findLink(vertex:Vertex):Link{
for (let fle of this.links){
if (fle.to==vertex) return fle
}
return null
}
/** set two links in opposition.
* If one of them exists (eg as a link with no opposition) the opposition is created */
setTwoOppositeLinks(cell1:Vertex, cell2:Vertex):Vertex{
let link1=this.findLink(cell1)
let link2=this.findLink(cell2)
if(link1==null) {
link1=new Link(cell1)
this.links.push(link1)
}
if(link2==null) {
link2=new Link(cell2)
this.links.push(link2)
}
if (link1.opposites==null) link1.opposites=[]
if (link2.opposites==null) link2.opposites=[]
link1.opposites.push(link2)
link2.opposites.push(link1)
return this
}
/**set a simple link between this and vertex.
* if such a link already existe (even with somme oppositions, it is suppressed)*/
setOneLink(vertex:Vertex):Vertex{
if (vertex==this) throw "it is forbidden to link to itself"
this.suppressOneLink(vertex)
this.links.push(new Link(vertex))
return this
}
static separateTwoVoisins(v1:Vertex,v2:Vertex):void{
v1.suppressOneLink(v2)
v2.suppressOneLink(v1)
}
/**to completely separate to vertex, you have to apply this procedure on both the two vertices*/
private suppressOneLink(voisin:Vertex):void{
let link=this.findLink(voisin)
if (link==null) return
tab.removeFromArray(this.links,link)
if (link.opposites!=null) {
for (let li of link.opposites){
if (li.opposites.length>=2) tab.removeFromArray(li.opposites,link)
else li.opposites=null
}
}
}
changeToLinkWithoutOpposite(voisin:Vertex):void{
let link=this.findLink(voisin)
if (link==null) return
if (link.opposites!=null) {
for (let li of link.opposites){
if (li.opposites.length>=2) tab.removeFromArray(li.opposites,link)
else li.opposites=null
}
}
link.opposites=null
}
toString(toSubstract:number):string{
let res=(this.hashNumber-toSubstract)+""
return res
}
toStringComplete(toSubstract:number):string{
let res=this.hashNumber-toSubstract+"|links:"
for (let fle of this.links) {
let bif=""
if (fle.opposites!=null){
bif+=","
for (let li of fle.opposites) bif+=(li.to.hashNumber-toSubstract)+","
}
res+="("+(fle.to.hashNumber-toSubstract) + bif + ")"
}
if(this.position!=null) res+="|pos:"+this.position.toString(1)+','
res+="|mark:"
for (let mark of this.markers) res+=Vertex.Markers[mark]+','
return res
}
}
export module Vertex{
export enum Markers{honeyComb,corner,center,border,polygonCenter,selectedForLineDrawing}
}
/**A graph but not only : it contains vertices but also lines passing through vertices.
* Most of time a Mamesh is a graph on a surface, so it contains square/triangle between vertices.
* It can contain also many other informations e.g. {@link vertexToPositioning} or {@link lineToColor} which are useful
* to represent a Mamesh */
export class Mamesh{
/**'points' of a graph*/
vertices :Vertex[]=[]
/**lines passing through vertices*/
lines:Line[]
/**surface element between vertices*/
smallestTriangles :Vertex[]=[]
smallestSquares:Vertex[]=[]
/** Hexahedron configuration
* 4 7
* /| |
* 3-+-2 |
* | | |
* 5-+-6
* |
* 0---1
*
* Coplanar faces ; order (for vectorial product) important.
* */
hexahedrons : Vertex[] = [];
/**to each vertex can be associate a positioning
* is initialised to null: some classes, if null, create a positioning and save it in this field*/
vertexToPositioning:HashMap<Vertex,Positioning>
/**to perform dichotomy*/
cutSegmentsDico :{[id:string]:Segment}={}
name:string
/**ex : Polyheron class fill this field*/
faces:Vertex[][]
//symmetries:((a:XYZ)=>XYZ)[]
get polygons():Vertex[][]{
let res=[]
for (let i=0;i< this.smallestSquares.length;i+=4) res.push([this.smallestSquares[i],this.smallestSquares[i+1],this.smallestSquares[i+2],this.smallestSquares[i+3]])
for (let i=0;i< this.smallestTriangles.length;i+=3) res.push([this.smallestTriangles[i],this.smallestTriangles[i+1],this.smallestTriangles[i+2]])
return res
}
//linksOK=false
get linesWasMade(){
return this.lines!=null
}
get segments():Vertex[][]{
let res:Vertex[][]=[]
for (let vertex of this.vertices){
for (let link of vertex.links){
if (vertex.hashNumber<link.to.hashNumber) res.push([vertex,link.to])
}
}
return res
}
addATriangle(a:Vertex, b:Vertex, c:Vertex,exceptionIfAVertexIsNull=false):Mamesh {
if(a!=null&&b!=null&&c!=null) this.smallestTriangles.push(a,b,c);
else if (exceptionIfAVertexIsNull) throw "you try to add a null vertex in a triangle"
return this
}
addASquare(a:Vertex, b:Vertex, c:Vertex,d:Vertex):Mamesh {
this.smallestSquares.push(a,b,c,d);
return this
}
addHexahedron(pos : Vertex[]) : Mamesh {
this.hexahedrons.concat(pos);
return this;
}
getVertex(pos : XYZ) {
let v = this.findVertexFromParam(pos);
if(v == null)
v = this.newVertex(pos);
return v;
}
newVertex(position:XYZ,dichoLevel=0,param?:XYZ):Vertex{
let vertex=new Vertex()
vertex.position=position
vertex.param=(param)?param:position
vertex.dichoLevel=dichoLevel
this.addVertex(vertex)
return vertex
}
findVertexFromParam(param:XYZ):Vertex{
for (let v of this.vertices){
if (v.param.hashString==param.hashString) return v
}
return null
}
addVertex(vertex:Vertex):void{
this.vertices.push(vertex)
}
hasVertex(vertex:Vertex):boolean{
for (let ver of this.vertices){
if (ver.hashNumber==vertex.hashNumber) return true
}
return false
}
getStraightLines():Line[]{
let res=[]
for (let line of this.lines){
if (!line.isLoop) res.push(line)
}
return res
}
getLoopLines():Line[]{
let res=[]
for (let line of this.lines){
if (line.isLoop) res.push(line)
}
return res
}
getStraightLinesAsVertices():Vertex[][]{
let res=[]
for (let line of this.lines){
if (!line.isLoop) res.push(line.vertices)
}
return res
}
getLoopLinesAsVertices():Vertex[][]{
let res=[]
for (let line of this.lines){
if (line.isLoop) res.push(line.vertices)
}
return res
}
toString(substractHashCode=true):string{
let toSubstract=0
if (substractHashCode){
toSubstract=Number.MAX_VALUE
for (let vert of this.vertices){
if (vert.hashNumber<toSubstract) toSubstract=vert.hashNumber
}
}
let res="\n"
if (this.name!=null) res+=this.name+"\n"
for (let vert of this.vertices){
res+=vert.toStringComplete(toSubstract)+"\n"
}
res+="tri:"
for (let j=0;j<this.smallestTriangles.length;j+=3){
res+="["+(this.smallestTriangles[j].hashNumber-toSubstract)+","+(this.smallestTriangles[j+1].hashNumber-toSubstract)+","+(this.smallestTriangles[j+2].hashNumber-toSubstract)+"]"
}
res+="\nsqua:"
for (let j=0;j<this.smallestSquares.length;j+=4){
res+="["+(this.smallestSquares[j].hashNumber-toSubstract)+","+(this.smallestSquares[j+1].hashNumber-toSubstract)+","+(this.smallestSquares[j+2].hashNumber-toSubstract)+","+(this.smallestSquares[j+3].hashNumber-toSubstract)+"]"
}
if (this.linesWasMade) {
res += "\nstrai:"
for (let line of this.getStraightLines()) {
res += "["
for (let ver of line.vertices) {
res += (ver.hashNumber-toSubstract) + ","
}
res += "]"
}
res += "\nloop:"
for (let line of this.getLoopLines()) {
res += "["
for (let ver of line.vertices) {
res += (ver.hashNumber-toSubstract) + ","
}
res += "]"
}
}
res+="\ncutSegments"
for (let key in this.cutSegmentsDico){
let segment=this.cutSegmentsDico[key]
res+= '{'+(segment.a.hashNumber-toSubstract)+','+(segment.middle.hashNumber-toSubstract)+','+(segment.b.hashNumber-toSubstract)+'}'
}
// res+="\nparamToVertex"
// //let key:XYZ
// for (let key of this.paramToVertex.allKeys()){
// res+=key.hashString+':'+(this.paramToVertex.getValue(key).hashNumber-toSubstract)+'|'
// }
return res
}
fillLineCatalogue(startingVertices:Vertex[]=this.vertices):void{
this.lines=lineModule.makeLineCatalogue2(startingVertices,true)
}
addSimpleLinksAroundPolygons():void{
new linkModule.SimpleLinkFromPolygonCreator(this).goChanging()
}
addOppositeLinksAroundPolygons():void{
new linkModule.SimpleLinkFromPolygonCreator(this).goChanging()
new linkModule.OppositeLinkAssocierByAngles(this.vertices).goChanging()
//new linkModule.LinkCreaterSorterAndBorderDetecterByPolygons(this).goChanging()
}
/** A IN_mamesh can be include in a larger graph. This method cut all the link going outside.
* This method is often use after a submamesh extraction */
isolateMameshVerticesFromExteriorVertices():void{
let verticesAndLinkToSepare:{vertex:Vertex;link:Link}[]=[]
for (let vertex of this.vertices){
for (let link of vertex.links){
if (!this.hasVertex(link.to)) verticesAndLinkToSepare.push({vertex:vertex,link:link})
}
}
for (let vl of verticesAndLinkToSepare){
Vertex.separateTwoVoisins(vl.link.to,vl.vertex)
//vl.vertex.suppressOneLink(vl.link.to,true)
//vl.link.to.suppressOneLink(vl.vertex,false)
}
}
getOrCreateSegment(v1:Vertex,v2:Vertex,segments:{[id:string]:Segment}):void{
let res=this.cutSegmentsDico[Segment.segmentId(v1.hashNumber,v2.hashNumber)]
if(res==null) {
res=new Segment(v1,v2)
this.cutSegmentsDico[Segment.segmentId(v1.hashNumber,v2.hashNumber)]=res
}
segments[Segment.segmentId(v1.hashNumber,v2.hashNumber)]=res
}
maxLinkLength():number{
let res=-1
this.vertices.forEach(vert=>{
vert.links.forEach(li=>{
let dist=geo.distance(vert.position,li.to.position)
if (dist>res) res=dist
})
})
if (res==-1) throw 'your IN_mamesh seems empty'
return res
}
// standartDeviationOfLinks():number{
// let res=0
// let nb=0
//
// this.vertices.forEach(v=>{
// v.links.forEach(l=>{
// nb++
// res+=geo.squaredDistance(v.position,l.to.position)
// })
//
// })
//
// return Math.sqrt(res)/nb
//
// }
clearLinksAndLines():void{
this.vertices.forEach(v=>{
tab.clearArray(v.links)
})
this.lines=null
}
clearOppositeInLinks():void{
this.vertices.forEach(v=>{
v.links.forEach((li:Link)=>{
li.opposites=null
})
})
}
allLinesAsASortedString(substractHashCode=true):string{
let res=""
let stringTab:string[]
let toSubstract
if (substractHashCode){
toSubstract=Number.MAX_VALUE
for (let vert of this.vertices){
if (vert.hashNumber<toSubstract) toSubstract=vert.hashNumber
}
}
if (this.linesWasMade) {
let straigth=this.getStraightLines()
let loop=this.getLoopLines()
if (this.linesWasMade && straigth.length > 0) {
stringTab = []
straigth.forEach(li=> {
let line=li.vertices
let hashTab:number[] = []
line.forEach(v=> {
hashTab.push(v.hashNumber - toSubstract)
})
stringTab.push(JSON.stringify(hashTab))
})
stringTab.sort()
res = "straightLines:" + JSON.stringify(stringTab)
}
if (loop.length > 0) {
stringTab = []
loop.forEach(li=> {
let line=li.vertices
let hashTab:number[] = []
line.forEach(v=> {
hashTab.push(v.hashNumber - toSubstract)
})
let minIndex = tab.minIndexOfNumericList(hashTab)
let permutedHashTab:number[] = []
for (let i = 0; i < hashTab.length; i++) {
permutedHashTab[i] = hashTab[(i + minIndex) % hashTab.length]
}
stringTab.push(JSON.stringify(permutedHashTab))
})
stringTab.sort()
res += "|loopLines:" + JSON.stringify(stringTab)
}
}
return res
}
allSquareAndTrianglesAsSortedString(subtractHashCode=true):string{
let toSubtract:number=0
if (subtractHashCode){
toSubtract=Number.MAX_VALUE
for (let vert of this.vertices){
if (vert.hashNumber<toSubtract) toSubtract=vert.hashNumber
}
}
let resSquare="square:"+this.allSquaresOrTrianglesAsASortedString(this.smallestSquares,4,toSubtract)
let resTri="triangle:"+this.allSquaresOrTrianglesAsASortedString(this.smallestTriangles,3,toSubtract)
return resSquare+resTri
}
private allSquaresOrTrianglesAsASortedString(squareOrTriangles:Vertex[],blockSize:number,toSubtract):string{
let res=""
let stringTab:string[]
let listOfPoly:Vertex[][]=[]
for (let i=0;i<squareOrTriangles.length;i+=blockSize){
let block:Vertex[]=[]
for (let j=0;j<blockSize;j++) block.push(squareOrTriangles[i+j])
listOfPoly.push(block)
}
stringTab = []
listOfPoly.forEach(line=> {
let hashTab:number[] = []
line.forEach(v=> {
hashTab.push(v.hashNumber - toSubtract)
})
let minIndex = tab.minIndexOfNumericList(hashTab)
let permutedHashTab:number[] = []
for (let i = 0; i < hashTab.length; i++) {
permutedHashTab[i] = hashTab[(i + minIndex) % hashTab.length]
}
stringTab.push(JSON.stringify(permutedHashTab))
})
stringTab.sort()
res += JSON.stringify(stringTab)
return res
}
checkPolygonAsLinkedSides(poly:Vertex[]){
for (let i=0;i<poly.length;i++){
if (! poly[i].hasVoisin(poly[(i+1)%poly.length])) return false
}
return true
}
}
export class Line{
vertices:Vertex[]
isLoop:boolean
getVertex(index,loopIfLoop=true):Vertex{
if (this.isLoop&& loopIfLoop) return this.vertices[index%this.vertices.length]
else return this.vertices[index]
}
hashForDirected():string{
let decayList:number[]=[]
if (!this.isLoop){
for (let v of this.vertices) decayList.push(v.hashNumber)
}
else {
let minIndex=tab.minIndexOb<Vertex>(this.vertices,(v1,v2)=>v1.hashNumber-v2.hashNumber)
for (let i=0;i<this.vertices.length;i++) decayList.push(this.vertices[(i+minIndex)%this.vertices.length].hashNumber)
}
return JSON.stringify(decayList)
}
inverted():Line{
let invertedVert:Vertex[]=[]
for (let i=0;i<this.vertices.length;i++) invertedVert.push(this.vertices[this.vertices.length-1-i])
return new Line(invertedVert,this.isLoop)
}
positionList():XYZ[]{
let res:XYZ[]=[]
for (let v of this.vertices) res.push(v.position)
return res
}
get hashString():string{
let hash1=this.hashForDirected()
let hash2=this.inverted().hashForDirected()
return (hash1<hash2)? hash1 : hash2
}
positionnalHashForDirected(precision=1):string{
let listOfHash:string[]=[]
XYZ.nbDecimalForHash=precision
if (!this.isLoop){
for (let v of this.vertices) listOfHash.push(v.position.hashString)
}
else {
let positionList=this.positionList()
let minIndex=tab.minIndexOb<XYZ>(positionList,XYZ.lexicalOrder)
for (let i=0;i<positionList.length;i++) listOfHash.push(positionList[(i+minIndex)%positionList.length].hashString)
}
XYZ.resetDefaultNbDecimalForHash()
return JSON.stringify(listOfHash)
}
positionnalHash(precision=1):string{
let hash1=this.positionnalHashForDirected(precision)
let hash2=this.inverted().positionnalHashForDirected(precision)
return (hash1<hash2)? hash1 : hash2
}
//
// hashStringUpToSymmetries(symmetries:((xyz:XYZ)=>XYZ)[],precision=1):string{
//
// let symmetriesAndIdentity=symmetries.concat((xyz:XYZ)=>xyz)
//
// let firstPosSymmetrised:XYZ[]=[]
// for (let sym of symmetriesAndIdentity) firstPosSymmetrised.push(sym(this.vertices[0].position))
// let lesserFirst=tab.minValueOb<XYZ>(firstPosSymmetrised,XYZ.lexicalOrder)
//
// let lastPosSymmetrized:XYZ[]=[]
// for (let sym of symmetriesAndIdentity) lastPosSymmetrized.push(sym(this.vertices[this.vertices.length-1].position))
// let lesserLast=tab.minValueOb<XYZ>(lastPosSymmetrized,XYZ.lexicalOrder)
//
// let chosenSym:(xyz:XYZ)=>XYZ
// let chosenOrder:Vertex[]
//
// if (XYZ.lexicalOrder(lesserFirst,lesserLast) <0){
// let chosenSymInd=firstPosSymmetrised.indexOf(lesserFirst)
// chosenSym=symmetriesAndIdentity[chosenSymInd]
// chosenOrder=this.vertices
// }
// else{
// let chosenSymInd=lastPosSymmetrized.indexOf(lesserLast)
// chosenSym=symmetriesAndIdentity[chosenSymInd]
// chosenOrder=[]
// for (let i=0;i<this.vertices.length;i++) chosenOrder.push(this.vertices[this.vertices.length-1-i])
// }
//
// let res:string[]=[]
// XYZ.nbDecimalForHash=precision
// for (let a of chosenOrder) res.push(chosenSym(a.position).hashString)
// XYZ.resetDefaultNbDecimalForHash()
//
//
// return JSON.stringify(res)
//
// }
//
hashStringUpToSymmetries(symmetries:((xyz:XYZ)=>XYZ)[],positionVersusParam):string{
let linesHash=[this.positionnalHash()]
for (let sym of symmetries){
let symV:Vertex[]=[]
for (let v of this.vertices) {
let vert=new Vertex()
if(positionVersusParam) vert.position=sym(v.position)
else vert.position=sym(v.param)
symV.push(vert)
}
let line=new Line(symV,this.isLoop)
linesHash.push(line.positionnalHash())
}
return tab.minValueString(linesHash)
}
constructor(vertices:Vertex[],isLoop:boolean){
this.vertices=vertices
this.isLoop=isLoop
}
allSegments():Segment[]{
let res=[]
let oneMore=(this.isLoop) ?1:0
for (let i=0;i<this.vertices.length-1+oneMore;i++){
res.push(new Segment(this.vertices[i],this.vertices[(i+1)%this.vertices.length]))
}
return res
}
}
export class Segment {
static segmentId(a:number, b:number):string{
if (a<b) return a+','+b
else return b+','+a
}
public a:Vertex
public b:Vertex
public middle:Vertex
public orth1:Vertex
public orth2:Vertex
get hashString():string{return Segment.segmentId(this.a.hashNumber,this.b.hashNumber)}
constructor(c:Vertex, d:Vertex) {
this.a = (c.hashNumber < d.hashNumber) ? c : d;
this.b = (c.hashNumber < d.hashNumber) ? d : c;
}
equals(ab:Segment):boolean {
return this.a == ab.a && this.b == ab.b;
}
getOther(c:Vertex) {
if (c == this.a) return this.b;
else return this.a;
}
getFirst():Vertex {
return this.a
}
getSecond():Vertex {
return this.b
}
has(c:Vertex):boolean {
return c == this.a || c == this.b
}
}
/**
* Eventuellement on pourrait rajouter des infos dans notre ClickEvent.
* Voici toutes les infos disponibles dans BabylonJS
* Remarque : nous n'avons pas besoin de pickedMesh puisque nous attachons le clickHandler au mesh (cf. MathisFrame)
*
* class PickingInfo {
hit: boolean;
distance: number;
pickedPoint: Vector3;
pickedMesh: AbstractMesh;
bu: number;
bv: number;
faceId: number;
subMeshId: number;
pickedSprite: Sprite;
getNormal(useWorldCoordinates?: boolean, useVerticesNormals?: boolean): Vector3;
getTextureCoordinates(): Vector2;
}
*
* */
export class ClickEvent{
position:XYZ
}
}
|
Markdown | UTF-8 | 1,179 | 2.59375 | 3 | [] | no_license | #include<stdio.h>
#include<conio.h>
int main()
{
printf("Oprating System For Prority \n");
int n;
printf("\n\nEnter No. Of Student :- ");
scanf("%d",&n);
int i,Sname[n],gift[n],BT[n],CT[n],WT[n],TAT[n];
// Input Student buy Gift
for(i=0;i<n;i++)
{
printf("\nStudent [%d]",i+1);
Sname[i]=i+1;
printf("\nNo. Of Gifts :- ");
scanf("%d",&gift[i]);
BT[i]=gift[i];
}
// for CT
int k,max=0,ind,sum=0;
for(k=0;k<n;k++)
{
for(i=0;i<n;i++)
{
if(max<=gift[i])
{
max=gift[i];
ind = i;
}
}
sum=sum+gift[ind];
CT[ind]=sum;
TAT[ind] = sum;
gift[ind] = -1;
max=0;
}
//for WT And TAT,TAT = CT - AT
// AT[] = 0 ,CT=TAT
//WT = TAT - BT;
float A_WT,A_TAT,SWT=0,STAT=0;
for(i=0;i<n;i++)
{
WT[i]=TAT[i]-BT[i];
}
for(i=0;i<n;i++)
{
SWT = SWT + WT[i];
STAT = STAT + TAT[i];
}
A_WT = SWT/n;
A_TAT = STAT/n;
int j;
printf("\nStudent \tBT \tCT \tTAT \tWT ");
for(j=0;j<n;j++)
{
printf("\n\nStudent[%d]\t%d \t%d \t%d \t%d",Sname[j],BT[j],CT[j],TAT[j],WT[j]);
}
printf("\n\nAverage Waiting Time(WT):- %f",A_WT);
printf("\nAverage Turn Around Time(TAT):- %f",A_TAT);
getch();
}
|
Swift | UTF-8 | 3,115 | 2.984375 | 3 | [] | no_license | //
// TableBrcOperand.swift
//
//
// Created by Hugh Bellamy on 12/11/2020.
//
import DataStream
/// [MS-DOC] 2.9.305 TableBrcOperand
/// The TableBrcOperand structure is an operand that specifies borders for a range of cells in a table row.
public struct TableBrcOperand {
public let cb: UInt8
public let itc: ItcFirstLim
public let bordersToApply: BordersToApply
public let brc: BrcMayBeNil
public init(dataStream: inout DataStream) throws {
/// cb (1 byte): An unsigned integer that specifies the size, in bytes, of the remainder of this structure. This value MUST be 11.
self.cb = try dataStream.read()
if self.cb != 11 {
throw OfficeFileError.corrupted
}
let startPosition = dataStream.position
/// itc (2 bytes): An ItcFirstLim structure that specifies the range of cell columns to which the border type format is applied.
self.itc = try ItcFirstLim(dataStream: &dataStream)
/// bordersToApply (1 byte): An unsigned integer that specifies which borders are affected. The value MUST be the result of the bitwise OR of any
/// subset of the following values that specifies an edge to be formatted:
self.bordersToApply = BordersToApply(rawValue: try dataStream.read())
/// brc (8 bytes): A BrcMayBeNil structure that specifies the border type that is applied to the edges which are indicated by bordersToApply.
self.brc = try BrcMayBeNil(dataStream: &dataStream)
if dataStream.position - startPosition < self.cb {
throw OfficeFileError.corrupted
}
}
/// bordersToApply (1 byte): An unsigned integer that specifies which borders are affected. The value MUST be the result of the bitwise OR of any
/// subset of the following values that specifies an edge to be formatted:
public struct BordersToApply: OptionSet {
public let rawValue: UInt8
public init(rawValue: UInt8) {
self.rawValue = rawValue
}
/// 0x01: Top border.
public static let top = BordersToApply(rawValue: 0x01)
/// 0x02: Logical left border.
public static let logicalLeft = BordersToApply(rawValue: 0x02)
/// 0x04: Bottom border.
public static let bottom = BordersToApply(rawValue: 0x04)
/// 0x08: Logical right border.
public static let logicalRight = BordersToApply(rawValue: 0x08)
/// 0x10: Border line from top left to bottom right.
public static let borderLineFromTopLeftToBottomRight = BordersToApply(rawValue: 0x08)
/// 0x20: Border line from top right to bottom left.
public static let borderLineFromTopRightToBottomLeft = BordersToApply(rawValue: 0x20)
public static let all: BordersToApply = [
.top,
.logicalLeft,
.bottom,
.logicalRight,
.borderLineFromTopLeftToBottomRight,
.borderLineFromTopRightToBottomLeft
]
}
}
|
Markdown | UTF-8 | 2,736 | 2.625 | 3 | [
"CC-BY-4.0",
"MIT"
] | permissive | ---
title: Auto Item
description: Auto Item
ms.date: 03/27/2023
---
# Auto Item
To implement [auto-configured scanning](auto-configured-scanning.md) in Windows 7 and later, a WIA minidriver must include an *auto item* in the [WIA item tree](wia-item-trees.md) for the scanner device. An auto item belongs to the WIA_CATEGORY_AUTO category. For more information about this category, see [WIA Item Categories](wia-item-categories.md).
The following diagram shows an example WIA item tree that includes an auto item. The auto item is a child of the root item in the tree.

In addition to the auto item, the WIA tree in the preceding diagram includes a flatbed item and a feeder item, both of which are children of the root item. The WIA architecture requires that an auto item is never the sole child of the root item--an auto item always has one or more siblings. At least one of these siblings must be a flatbed item, feeder item, or film item. For more information about these items, see [WIA Item Categories](wia-item-categories.md).
If a WIA scanner device supports auto-configured scanning, a WIA application can acquire an image from the currently selected input source on the device by requesting a data transfer from the auto item. In response to this request, the device can automatically configure most of its scan settings before acquiring the image. The application is responsible only for determining the file format to use for the transfer. For this reason, an auto item implements a relatively small subset of the WIA properties that are implemented by the WIA item for a fully programmable input source (that is, a flatbed item, feeder item, or film item). For more information, see [WIA Properties Supported by an Auto Item](wia-properties-supported-by-an-auto-item.md).
The WIA architecture does not permit a scanner device operating in auto-configured scanning mode to automatically select the file format that it uses to transfer image data acquired from an input source. Instead, the application determines the file format--either by explicitly selecting a format or by simply accepting the default format. This restriction prevents the device from transferring scanned image data in a format that the application cannot use.
A WIA minidriver for a scanner device that supports auto-configured scanning should set the AUTO_SOURCE flag bit in the [**WIA_DPS_DOCUMENT_HANDLING_CAPABILITIES**](./wia-dps-document-handling-capabilities.md) property value implemented by the root item in the WIA tree. A WIA application can query this property to determine whether the WIA item tree for the device contains an auto item.
|
Java | UTF-8 | 452 | 2.234375 | 2 | [] | no_license | package com.DAO.Test;
import com.Factory.DAOFactory;
import com.vo.Person;
import org.junit.Test;
public class PersonDAOTest {
@Test
public void loginCheckTest() throws Exception{
Person person = new Person();
person.setId("2018110116");
person.setPassword("123");
System.out.println(DAOFactory.getPersonDAOInstance().loginCheck(person));
System.out.println(person.toString());
}
}
|
Rust | UTF-8 | 628 | 2.765625 | 3 | [] | no_license | use ndarray::Array1;
use super::{FullState, Game};
use policies::{Policy, Random};
pub trait StateEvaluator<G: Game> {
type TargetPolicy: Policy;
fn evaluate(&self, &FullState<G>) -> Array1<f64>;
}
pub struct RandomEvaluator<G: Game> {
game: G,
}
impl<G: Game> RandomEvaluator<G> {
pub fn new(game: G) -> Self {
RandomEvaluator { game }
}
}
impl<G: Game> StateEvaluator<G> for RandomEvaluator<G> {
type TargetPolicy = Random;
fn evaluate(&self, state: &FullState<G>) -> Array1<f64> {
let num_actions = self.game.num_actions(state);
Array1::ones((num_actions,))
}
}
|
PHP | UTF-8 | 6,975 | 2.953125 | 3 | [] | no_license | <?php
abstract class BaseOAuth extends BaseObject
{
/**
* Variables for the OAuth urls
*
* @var string
*/
protected $_requestTokenUrl;
protected $_accessTokenUrl;
protected $_authoriseUrl;
/**
* Variables for the consumer
*
* @var string
*/
protected $_consumerKey;
protected $_consumerSecret;
/**
* OAuth information
*
* @var string
*/
protected $_signatureMethod = "HMAC-SHA1";
protected $_version = "1.0";
/**
* Prefix for the parameters
*/
protected $_paramPrefix = "oauth_";
/**
* Default parameters
*
* @var array
*/
protected $_params = array();
/**
* Setup the base data
*
* @return void
*/
protected function _construct()
{
$this->resetParams();
return parent::_construct();
}
/**
* Get the request Token
*
* @return BaseOAuthResponse
*/
public function getRequestToken()
{
if(!$this->hasRequestToken()){
//reset all the parameters
$this->resetParams();
// make signature and append to params
//$this->setSecret($this->_consumerSecret);
$this->setRequestUrl($this->_requestTokenUrl);
$this->_buildSignature();
//get the response
$response = $this->_send($this->_requestTokenUrl)->getBody();
//format the response
$responseVars = array();
parse_str($response, $responseVars);
$response = new BaseOAuthResponse($responseVars);
$this->setRequestToken($response);
}
//send the query
return $this->getData('request_token');
}
/**
* Get the authorise URL
*
* @return string
*/
public function getAuthUrl()
{
$tokenData = $this->getRequestToken();
return rtrim($this->_authoriseUrl,'/').'?'.$tokenData;
}
/**
* Get the access token
*
* @param string $token
* @return string
*/
public function getAccessToken()
{
if(!$this->hasAccessToken()){
//reset all the parameters
$this->resetParams();
//set the returned token
$this->setParam('token', $this->getRequestToken()->getToken());
//build the signiture
$this->setSecret($this->getRequestToken()->getTokenSecret());
$this->setRequestUrl($this->_accessTokenUrl);
$this->_buildSignature();
//get the response
$response = $this->_send($this->_accessTokenUrl)->getBody();
//format the response
$responseVars = array();
parse_str($response, $responseVars);
$response = new BaseOAuthResponse($responseVars);
$this->setAccessToken($response);
}
return $this->getData('access_token');
}
/**
* Call the api resource
*
* @param string $url
* @param array $params
* @param BaseObject $accessToken
* @return string
*/
public function callResource($url, $params, $accessToken)
{
//reset all the parameters
$this->resetParams();
foreach($params as $key => $value){
$this->setParam($key, $value, false);
}
//set the returned token
$this->setParam('token', $accessToken->getToken());
//build the signature
$this->setRequestUrl($url);
$this->setTransport(HttpClient::POST);
$this->setSecret($accessToken->getTokenSecret());
$this->_buildSignature();
//get the response
$response = $this->_send($url)->getBody();
return $response;
}
/**
* Send the query to the oauth server
*
* @return HttpClient
*/
protected function _send($url)
{
//sort the parameters again
uksort($this->_params, 'strcmp');
//build the query
$query = $this->_buildQuery($this->_params);
$header = $this->_buildHeader($this->_params);
//send it to the server
$http = new HttpClient($url);
$http->addHeader("Authorization: {$header}");
$http->setTransport($this->getTransport());
//set the verbose options
if($this->getFlag('verbose')){
$http->setFlag('verbose',true);
}
$http->setQuery($query);
//a bit of error checking
try{
$http->get();
return $http;
} catch(HttpClientException $e) {
if($e->getCode() == 401){
throw new BaseOAuthException("Access Denied to oAuth Server", 401);
}
throw $e;
}
}
/**
* Build the signature
*
* @return BaseOAuth
*/
protected function _buildSignature()
{
//encode the parameters
$keys = $this->_urlencodeRfc3986(array_keys($this->_params));
$values = $this->_urlencodeRfc3986(array_values($this->_params));
$this->_params = array_combine($keys, $values);
uksort($this->_params, 'strcmp');
//put it into a query
$params = $this->_buildQuery($this->_params, true);
//Form all the strings to work with
$base = $this->getTransport()."&".$this->_urlencodeRfc3986($this->getRequestUrl())."&".$this->_urlencodeRfc3986($params);
$secret = $this->_urlencodeRfc3986($this->_consumerSecret) ."&".$this->_urlencodeRfc3986($this->getSecret());
//Encode it all and assign to the params
$hash = hash_hmac('sha1', $base, $secret, true);
$base64 = base64_encode($hash);
$this->setParam('signature', $this->_urlencodeRfc3986($base64));
return $this;
}
/**
* Reset the parameters
*
* @return BaseOAuth
*/
public function resetParams()
{
$this->_params = array();
$this->setParam('version', $this->_version);
$this->setParam('nonce', time());
$this->setParam('timestamp', time());
$this->setParam('consumer_key', $this->_consumerKey);
$this->setParam('signature_method', $this->_signatureMethod);
$this->setTransport(HttpClient::GET);
return $this;
}
/**
* Set a parameter for the header request
*
* @param string $key
* @param mixed $value
* @param bool $prefix
* @return BaseOAuth
*/
public function setParam($key, $value, $prefix = true)
{
$key = $prefix ? $this->_paramPrefix.$key : $key;
$this->_params[$key] = $value;
return $this;
}
/**
* Get a param value
*
* @param string $key
* @param bool $prefix
* @return mixed
*/
public function getParam($key, $prefix = true)
{
$key = $prefix ? $this->_paramPrefix.$key : $key;
return $this->_params[$key];
}
/**
* URL Encode to RFC3986 specification
*
* @param mixed $input
* @return mixed
*/
protected function _urlencodeRfc3986($input)
{
if(is_array($input)) {
return array_map(array($this, '_urlencodeRfc3986'), $input);
} elseif (is_scalar($input)) {
return str_replace('+',' ',str_replace('%7E', '~', rawurlencode($input)));
} else{
return '';
}
}
/**
* Build the query
*
* @param array $params
* @return string
*/
protected function _buildQuery($params, $includeoAuth = false)
{
$parts = array();
foreach($params as $k=>$v){
if($includeoAuth || strpos($k, $this->_paramPrefix) === false){
$parts[] = "{$k}={$v}";
}
}
return implode('&', $parts);
}
/**
* Build the OAuth header
*
* @param array params
* @return string
*/
protected function _buildHeader($params)
{
$parts = array();
foreach($params as $k=>$v)
{
if(strpos($k, $this->_paramPrefix) !== false){
$parts[] = sprintf('%s="%s"', $k, $v);
}
}
return "OAuth ".implode(', ', $parts);
}
} |
Markdown | UTF-8 | 1,452 | 3.4375 | 3 | [
"MIT"
] | permissive | # realGen
Fast implementation of Genetic Algorithm only for real genotype, useful for nonlinear constrained and unconstrained optimization problems.
## INSTALL
```
$ git clone https://github.com/alenic/realGen.git
$ cd realGen
$ make
```
# Quick start
First of all you have to define a fitness function to minimize, and just pass it as function pointer to the RealGen class with the method setFitnessFunction:
```c++
#include <iostream>
#include "realgen.h"
using namespace std;
/* Fitness function: x1^2 + x2^2 */
double myFitnessFunction(RealGenotype &g, void *par) {
return g.gene[0]*g.gene[0] + g.gene[1]*g.gene[1];
}
int main(int argc, char** argv) {
float LB[] = {-5.0, -5.0}; // Lower bound of genes
float UB[] = { 5.0, 5.0}; // Upper bound of genes
// Define RealGen(Population size, number of genes in a chromosome, LB, UB)
RealGen ga(50, 2, LB, UB);
ga.setFitnessFunction(myFitnessFunction, NULL);
// Init population with uniform random
ga.initRandom();
// Evolve the population for 100 times
for (int i=0; i<100; i++) {
ga.evolve();
}
// get the best score function (the minimum)
RealGenotype best = ga.getBestChromosome();
// Print results
cout << ga.populationToString(); // print all the population
cout << "Best solution: "<< best.toString() << endl;
cout << "Best Fitness value = " << best.fitness << endl;
return 0;
}
```
|
Markdown | UTF-8 | 791 | 2.5625 | 3 | [
"MIT"
] | permissive | # Knock
Knock Sensor
This sketch reads a piezo element to detect a knocking sound.
It reads an analog pin and compares the result to a set threshold.
If the result is greater than the threshold, it writes
"knock" to the serial port, and toggles the LED on pin 13.
The circuit:
+ connection of the piezo attached to analog in 0
- connection of the piezo attached to ground
-1-megohm resistor attached from analog in 0 to ground

### The Knock sketch
- `File -> Examples -> Denbit -> Sensors -> Knock`
- Compile the software: click the tick in the top left of the Arduino application... wait while it compiles...
- Upload the software: click the arrow in the top left of the Arduino application... wait while it uploads
|
Java | UTF-8 | 484 | 1.796875 | 2 | [] | no_license | package top.duanhong.emims.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @author duanhong
* @description webSocket配置
* @date 2019/5/11
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
|
Markdown | UTF-8 | 626 | 2.890625 | 3 | [] | no_license | # Mobile-first Responsive Landing Page
## About the project
On this solo project for my Treehouse tech degree, I built a responsive, mobile-first layout using HTML and CSS from a mock-up design. The layout is responsive, adjusting to accommodate mobile, tablet, and desktop screen sizes.
### Built With
- HTML
- CSS
## Contact
Jennifer Carey - [@JennifaCarey](https://twitter.com/JennifaCarey)
Project Link: [https://jennifer-carey.github.io/techdegree-project-2/](https://jennifer-carey.github.io/techdegree-project-2/)
## Acknowledgements
This landing page was created as a project for the Treehouse Front End Tech Degree.
|
Java | UTF-8 | 6,420 | 2.046875 | 2 | [] | no_license | package com.example.sociedad;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import MODEL.Society;
public class RegisterSocietyActivity extends AppCompatActivity {
private Button back, next;
private String id;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mDatabaseReference;
private Society society;
private TextView society_name, society_reg_no, society_mobileno, society_emailid, society_address, society_uid, society_buildings, society_bunglows, society_rowhouses;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_society);
Intent intent = getIntent();
id = intent.getStringExtra("id");
society_name = (TextView) findViewById(R.id.society_name);
society_reg_no = (TextView) findViewById(R.id.society_reg_no);
society_mobileno = (TextView) findViewById(R.id.society_contact_no);
society_emailid = (TextView) findViewById(R.id.society_email_id);
society_address = (TextView) findViewById(R.id.society_address);
society_uid = (TextView) findViewById(R.id.society_uid);
society_buildings = (TextView) findViewById(R.id.no_of_buildings);
society_bunglows = (TextView) findViewById(R.id.no_of_bunglows);
society_rowhouses = (TextView) findViewById(R.id.no_of_rowhouse);
mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mFirebaseDatabase.getReference("Society");
back = (Button) findViewById(R.id.society_back_button);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO populate old contains in Admin Activity
finish();
}
});
next = (Button) findViewById(R.id.society_next_button);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Toast.makeText(RegisterSocietyActivity.this,id,Toast.LENGTH_LONG).show();
society = new Society(society_name.getText().toString(), society_reg_no.getText().toString(), society_mobileno.getText().toString(), society_emailid.getText().toString(), society_address.getText().toString(), society_uid.getText().toString(), society_buildings.getText().toString(), society_bunglows.getText().toString(), society_rowhouses.getText().toString(), id);
if (TextUtils.isEmpty(society.getSociety_name())) {
Toast.makeText(RegisterSocietyActivity.this, "Enter Society Name", Toast.LENGTH_LONG).show();
} else if (TextUtils.isEmpty(society.getSociety_reg_no())) {
Toast.makeText(RegisterSocietyActivity.this, "Enter Society Registration Number", Toast.LENGTH_LONG).show();
} else if (TextUtils.isEmpty(society.getSociety_mobileno())) {
Toast.makeText(RegisterSocietyActivity.this, "Enter Society Mobile Number", Toast.LENGTH_LONG).show();
} else if (TextUtils.isEmpty(society.getSociety_emailid())) {
Toast.makeText(RegisterSocietyActivity.this, "Enter Society Email Id", Toast.LENGTH_LONG).show();
} else if (TextUtils.isEmpty(society.getSociety_address())) {
Toast.makeText(RegisterSocietyActivity.this, "Enter Society Address", Toast.LENGTH_LONG).show();
} else if (TextUtils.isEmpty(society.getSociety_uid())) {
Toast.makeText(RegisterSocietyActivity.this, "Enter Society Unique Id", Toast.LENGTH_LONG).show();
} else if (TextUtils.isEmpty(society.getSociety_buildings())) {
Toast.makeText(RegisterSocietyActivity.this, "Enter Number of Buildings", Toast.LENGTH_LONG).show();
} else if (TextUtils.isEmpty(society.getSociety_bunglows())) {
Toast.makeText(RegisterSocietyActivity.this, "Enter Number of Bunglows", Toast.LENGTH_LONG).show();
} else if (TextUtils.isEmpty(society.getSociety_rowhouses())) {
Toast.makeText(RegisterSocietyActivity.this, "Enter Number of Rowhouses", Toast.LENGTH_LONG).show();
} else {
final String uid = society.getSociety_uid();
mDatabaseReference.child(uid).child("society_name").setValue(society.getSociety_name());
mDatabaseReference.child(uid).child("society_reg_no").setValue(society.getSociety_reg_no());
mDatabaseReference.child(uid).child("society_mobileno").setValue(society.getSociety_mobileno());
mDatabaseReference.child(uid).child("society_emailid").setValue(society.getSociety_emailid());
mDatabaseReference.child(uid).child("society_address").setValue(society.getSociety_address());
mDatabaseReference.child(uid).child("society_uid").setValue(society.getSociety_uid());
mDatabaseReference.child(uid).child("society_buildings").setValue(society.getSociety_buildings());
mDatabaseReference.child(uid).child("society_bunglows").setValue(society.getSociety_bunglows());
mDatabaseReference.child(uid).child("society_admin_uid").setValue(society.getSociety_admin_uid());
mDatabaseReference.child(uid).child("society_rowhouses").setValue(society.getSociety_rowhouses(), new DatabaseReference.CompletionListener() {
@Override
public void onComplete(@Nullable DatabaseError databaseError, @NonNull DatabaseReference databaseReference) {
Toast.makeText(RegisterSocietyActivity.this, "Successful", Toast.LENGTH_LONG).show();
}
});
}
}
});
}
}
|
C++ | UTF-8 | 1,158 | 3 | 3 | [
"MIT"
] | permissive | #ifndef __SEQUENCER__
#define __SEQUENCER__
#include <stdint.h>
#include "ButtonManager.h"
#define MIN_SEQUENCE_LENGTH 8
#define MAX_SEQUENCE_LENGTH 32
class Sequencer {
public:
enum SequencerState {
SEQUENCER_STATE_STOPPED = 0,
SEQUENCER_STATE_PLAYING,
SEQUENCER_STATE_RECORDING
};
void togglePlayPause();
void startRecording();
uint8_t processStep(ButtonManager *manager);
void increaseSequence();
void decreaseSequence();
bool addStep(uint8_t step);
Sequencer() :
sequenceLength(MIN_SEQUENCE_LENGTH),
state(SEQUENCER_STATE_STOPPED),
currentStep(0) {
for (int i = 0; i < MAX_SEQUENCE_LENGTH; i++) {
sequence[i] = 0;
}
}
//// INLINE FUNCTIONS ////
inline bool isPlaying() const { return state == SEQUENCER_STATE_PLAYING; }
inline int getSequenceLength() const { return sequenceLength; }
inline int getCurrentStep() { return currentStep; }
inline SequencerState getState() { return state; }
private:
uint8_t sequence[MAX_SEQUENCE_LENGTH];
int sequenceLength;
SequencerState state;
int currentStep;
};
#endif
|
JavaScript | UTF-8 | 1,079 | 2.671875 | 3 | [] | no_license | // File - /pages/index.js
import { useEffect, useState } from "react";
import { useAppContext } from "../context/context";
export default function posts() {
const [posts, setPosts] = useState([]);
const { authenticatedName } = useAppContext();
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then(res => res.json())
.then(res => {
console.log(res)
setPosts(res)
})
}, []);
return (
<>
<div style={{ textAlign: "left", margin: "5%" }} >
<h2 style={{ textAlign: "center", margin: "5%" }}>Hello {authenticatedName}</h2>
<table>
<tbody>
<tr>
<th>User Id</th>
<th>Title </th>
<th>Body</th>
</tr>
{posts?.map((post) => (
<tr key={post.id}>
<td>{post.userId}</td>
<td>{post.title}</td>
<td>{post.body}</td>
</tr>
))}
</tbody>
</table> </div>
{/* </Layout> */}
</>
)
}
|
C++ | UTF-8 | 1,404 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <time.h> /* time */
#include <algorithm>
#include <list>
#include <utility>
using namespace std;
int main()
{
ofstream outfile;
outfile.open ("phonenumber.out");
std::ifstream infile;
infile.open ("data.in", std::ifstream::in);
std::string line;
getline(infile, line);
std::stringstream lineStream(line);
int T;
lineStream>>T;
for(int k=0;k<T;k++){
int z=0,o=0,w=0,t=0,r=0,v=0,x=0,s=0,g=0,i=0;
string letter;
getline(infile, line);
std::stringstream Stream1(line);
Stream1>>letter;
for(int j=0;j<letter.length();j++){
char c=letter[j];
if(c=='Z') z++;
if(c=='O') o++;
if(c=='W') w++;
if(c=='T') t++;
if(c=='R') r++;
if(c=='V') v++;
if(c=='X') x++;
if(c=='S') s++;
if(c=='G') g++;
if(c=='I') i++;
}
vector<int> digits;
digits.assign(10,0);
digits[0]=z;
r=r-z;
o=o-z;
digits[2]=w;
o=o-w;
t=t-w;
digits[6]=x;
s=s-x;
i=i-x;
digits[8]=g;
i=i-g;
t=t-g;
digits[3]=t;
r=r-t;
digits[7]=s;
v=v-s;
digits[5]=v;
i=i-v;
digits[4]=r;
o=o-r;
digits[9]=i;
digits[1]=o;
outfile<<"Case #"<<k+1<<": ";
for(int counter=0;counter<10;counter++){
for(int counter2=0;counter2<digits[counter];counter2++){
outfile<<counter;
}
}
outfile<<endl;
}
infile.close();
outfile.close();
return 0;
}
|
C# | UTF-8 | 577 | 2.84375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FunctionalExamples
{
public class Maybe:Identity
{
public Maybe(object val):base(val)
{
}
public override Identity Map(Func<object, object> f)
{
return this.val != null? new Maybe(f(this.val)) : new Maybe(null);
}
}
public static partial class Functions
{
public static Maybe Maybe(object val)
{
return new Maybe(val);
}
}
}
|
PHP | UTF-8 | 413 | 3.296875 | 3 | [
"MIT"
] | permissive | <?php
namespace Spatie\UnitConversions;
class Temprature
{
/** @var float */
private $celsius;
public static function fromCelsius(float $celsius): self
{
return new static($celsius);
}
public function __construct(float $celsius)
{
$this->celsius = $celsius;
}
public function toFahrenheit(): float
{
return ($this->celsius * 1.8) + 32;
}
}
|
Java | UTF-8 | 726 | 2.1875 | 2 | [] | no_license | package io.openmessaging.demo;
/**
* Created by YangMing on 2017/5/25.
*/
public class YmMessageRegister3 {
private int offset = 0;
private YmBucketCache6[] bucketArray;
private static YmMessageRegister3 register = new YmMessageRegister3();
private YmMessageRegister3() {
bucketArray = new YmBucketCache6[Config.CACHE_NUM];
for (int i = 0; i < bucketArray.length; i++) {
bucketArray[i] = new YmBucketCache6();
}
}
public static synchronized YmMessageRegister3 getInstance() {
return register;
}
public synchronized YmBucketCache6 getCache() {
int r = offset % bucketArray.length;
offset++;
return bucketArray[r];
}
}
|
C++ | UTF-8 | 1,770 | 2.921875 | 3 | [] | no_license | #pragma once
#include <vector>
#include <cstdint>
#include <thread>
#include "socketabstraction.h"
#include "messages.h"
namespace Krakenplay
{
/// \brief Krakenplay server singleton class.
///
/// The server manages all connections to clients and gathers all incoming inputs.
class NetworkServer
{
public:
/// Returns singleton instance.
static NetworkServer& Instance();
/// \brief Inits server on a given port.
///
/// If server was already initialized, existing server will be closed.
/// Opens a thread that will continuously try to receive message headers and
/// another one that sends identify messages in the rate given by SetIdentifyMessageRate.
/// \return true if everything is alright, false otherwise - will write error messages to cerr!
bool InitServer(uint16_t messagePort = g_defaultMessagePort, uint16_t identifyPort = g_defaultIdentifyPort);
/// \brief Closes the server.
void DeInitServer();
/// \brief Sets the rate of identify message broadcasts in milliseconds.
///
/// These packages are used to enable automatic client connection.
/// \param identifyMessageRateMS Rate in milliseconds. Zero will result in NO packages at all.
void SetIdentifyMessageRate(unsigned int identifyMessageRateMS = 400);
private:
NetworkServer();
~NetworkServer();
void Receive();
void Identify();
volatile unsigned int identifyMessageRateMS;
volatile bool serverRunning;
std::thread receiveThread;
SOCKET serverSocket;
uint16_t messagePort;
std::thread identifyThread;
SOCKET broadcastSocket;
uint16_t identifyPort;
/// List of all known clients. Position within list gives each an unique id.
/// \attention Used by the receive thread.
std::vector<std::string> knownClients;
};
}
|
Markdown | UTF-8 | 488 | 2.734375 | 3 | [] | no_license | # Chess notation reader
Chess notation reader is a failed experiment in creating an app to convert chess games recorded by hand in notation books to digitally analysable games.
OCR readers struggle to read human handwriting, but I had hoped that using a combination of photoprocessing and pattern matching, the simple lettering of chess notation could be read. I was unable to get recognition up above 50%, but hopefully OCR tech will improve in future and I can revisit this project.
|
C | UTF-8 | 5,721 | 3.640625 | 4 | [] | no_license | //CONTA BANCO
#include <stdio.h>
#include <string.h>
#define N 7
void cadastraCliente (int pos);
void listaTodosCliente ();
void listaCliente (int pos);
void inicializaVetor ();
int buscaPosicaoVazia ();
int menu ();
int buscaCPF (long cpf);
void buscaNome (char str[]);
void removeCliente (int pos);
int submenu ();
void deposito (float money, int conta, int ag, int cont);
int saque ();
struct REGISTRO
{
long ag, conta, cpf;
char nome[51];
int id, flag;
float saldo;
};
struct REGISTRO cliente[N];
void inicializaVetor ()
{
for (int i=0; i<N; i++)
cliente[i].flag=0;
}
int menu ()
{
printf("\nMENU PRINCIPAL:\n");
int op;
printf(" 1 - Cadastrar cliente\n 2 - Lista todos clientes\n 3 - Lista um cliente\n 4 - remover um cliente\n 5 - fazer um deposito\n 0 - Sair\n ");
scanf("%d", &op);
return op;
}
int submenu ()
{
int opsub;
printf("1 - busca por nome\n");
printf("2 - busca por cpf\n");
printf("opção: ");
scanf("%d", &opsub);
return opsub;
}
void cadastraCliente (int pos)
{
printf("Digite a Agência: ");
scanf("%ld", &cliente[pos].ag);
printf("Digite a conta: ");
scanf("%ld", &cliente[pos].conta);
printf("Nome: ");
scanf(" %[^\n]", cliente[pos].nome);
printf("CPF: ");
scanf("%ld", &cliente[pos].cpf);
cliente[pos].id=pos;
cliente[pos].flag=1;
cliente[pos].saldo=0;
printf("Cliente cadastrado\n");
}
void listaCliente (int pos)
{
printf("Cliente ID: %d\n", cliente[pos].id);
printf("Agencia: %ld\n", cliente[pos].ag);
printf("Conta: %ld\n", cliente[pos].conta);
printf("Nome: %s\n", cliente[pos].nome);
printf("CPF: %ld\n", cliente[pos].cpf);
printf("Saldo: R$ %.2f\n", cliente[pos].saldo);
printf("\n -------------------- \n");
}
void listaTodosCliente ()
{
int cont=0;
for (int i=0; i<N; i++)
{
if (cliente[i].flag == 1)
{
printf("Cliente ID: %d\n", cliente[i].id);
printf("Agencia: %ld\n", cliente[i].ag);
printf("Conta: %ld\n", cliente[i].conta);
printf("Nome: %s\n", cliente[i].nome);
printf("CPF: %ld\n", cliente[i].cpf);
printf("Saldo: R$ %.2f\n", cliente[i].saldo);
printf("\n -------------------- \n");
cont++;
}
}
if (cont==0)
{
printf("Não há clientes registrados\n");
}
}
int buscaPosicaoVazia ()
{
for (int i=0; i<N; i++)
{
if (cliente[i].flag == 0)
{
return i;
}
}
return -1;
}
int buscaCPF (long cpf)
{
for (int i=0; i<N; i++)
{
if (cpf == cliente[i].cpf && cliente[i].flag == 1)
return i;
return -1;
}
}
void buscaNome (char str[])
{
int retorno, cont=0;
for (int i=0; i<N; i++)
{
retorno = strcmp(cliente[i].nome, str);
if(retorno == 0 && cliente[i].flag == 1)
{
cont++;
listaCliente(i);
}
}
if (cont == 0)
printf("Cliente não cadastrado\n");
}
void removeCliente (int pos)
{
long cpfr;
if (cliente[pos].flag != 0)
{
printf("Digite o cpf do cliente para confirmar a remoção: ");
scanf("%ld", &cpfr);
if (cpfr == cliente[pos].cpf)
{
cliente[pos].flag = 0;
printf("O cliente de id %d foi removido\n", pos);
}
else
printf(" CPF incorreto\n Operação cancelada.\n");
}
else
printf("Cliente não registrado");
}
void deposito (float money, int conta, int ag, int cont)
{
int x = 0;
cont = 0;
printf("Digite a quantidade a ser depositada: ");
scanf("%f", &money);
printf("Digite a conta: ");
scanf("%d", &conta);
printf("Digite a agencia: ");
scanf("%d", &ag);
for (int i=1; i<=N; i++)
{
if (cliente[i].conta == conta)
cont++;
if (cliente[i].ag == ag)
{
cont++;
i = x;
}
}
if (cont == 2)
cliente[x].saldo = money;
else
printf("Cliente não localizado");
}
int main()
{
int a, op, p, pos, conta, ag, contdep;
long cpfBusca;
char nomeBusca[51];
float money;
inicializaVetor();
do{
op = menu();
switch (op)
{
case 1: a = buscaPosicaoVazia();
if (a != -1)
cadastraCliente(a);
else
printf("Erro!\nVetor cheio!\n");
break;
case 2: listaTodosCliente();
break;
case 3: a = submenu();
if (a == 1)
{
printf("Busca nome: ");
scanf("%s", &nomeBusca);
buscaNome(nomeBusca);
}
else if(a == 2)
{
printf("busca cpf: ");
scanf("%ld", &cpfBusca);
p = buscaCPF(cpfBusca);
if (p != -1)
listaCliente(p);
else
printf("Cliente não localizado\n");
}
else
printf("Opção inválida.\n");
break;
case 4: printf("Digite o id do cliente a ser removido: ");
scanf("%d", &pos);
removeCliente(pos);
break;
case 5: deposito(money, conta, ag, contdep);
break;
case 0: printf("Programa finalizado.\n");
break;
default: printf("Opção inválida.\n");
}
}while(op != 0);
return 0;
}
|
PHP | UTF-8 | 2,390 | 2.6875 | 3 | [] | no_license | <?php
/**
* Default
*
*
* @package
* @subpackage Controller
* @author YOUR NAME <YOUREMAIL@jouve.com>
*/
include '../../../config/autoload.php';
//BDD
$postgres = new connexion();
$conn = $postgres->connect();
//var_dump($_POST);
//SQL
$sql = "select * from menu m order by m.niveau";
$dataOut = $postgres->getSQL($conn, $sql);
$dataOut = reorganisation($dataOut);
echo json_encode($dataOut);
function reorganisation($dataOut) {
$ordre = [];
$test = true;
$finish_count = 0;
while ($test) {
$test = false;
$force_break = false;
foreach ($dataOut as $key => $value) {
if ($force_break == true)
break;
$tab_niv = explode('-', $dataOut[$key]['niveau']);
if (array_key_exists($key + 1, $dataOut)) {
$tab_niv_another = explode('-', $dataOut[$key + 1]['niveau']);
$count = count($tab_niv_another);
if (count($tab_niv) > count($tab_niv_another)) {
$count = count($tab_niv);
}
for ($index = 0; $index < $count; $index++) {
if (array_key_exists($index, $tab_niv) && array_key_exists($index, $tab_niv_another)) {
$note_niv = intval($tab_niv[$index]);
$note_niv_another = intval($tab_niv_another[$index]);
if ($note_niv > $note_niv_another) {
$avant = $dataOut[$key];
$apres = $dataOut[$key + 1];
$dataOut[$key] = $apres;
$dataOut[$key + 1] = $avant;
$test = true;
$force_break = true;
break;
}
} else if (!array_key_exists($index, $tab_niv) && array_key_exists($index, $tab_niv_another)) {
break;
} else if (array_key_exists($index, $tab_niv) && !array_key_exists($index, $tab_niv_another)) {
break;
}
}
}
}
$finish_count++;
if ($finish_count > 500) { //Si boucle infinie
$test = false;
}
}
return $dataOut;
}
?> |
JavaScript | UTF-8 | 3,037 | 2.515625 | 3 | [] | no_license | const express = require("express");
const app = express();
const mongoose = require("mongoose")
app.use(express.json());
require("./models/Artigo");
const Artigo = mongoose.model('artigo')
var cors = require('cors')
//========== MIDDLEWARE CORS =================//
app.use((req, res, next) => {
console.log("Middleware working...")
res.header("Access-Control-Allow-Origin", "*")// * any app can do req
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE")
app.use(cors());
next()
});
//========== DB CONNECT =============//
mongoose.connect('mongodb://localhost/api02db', {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
}).then(() => {
console.log(`Connect success with db`)
}).catch((err) => {
console.log(`Error ----> ${err}`)
})
//========= POST CREATE ===========//
app.post("/artigo", (req, res) => {
const artigo = Artigo.create(req.body, (err) => {
if (err) return res.status(400).json({
error: true,
message: "Error: Sem sucesso no cadastro, tente novamente"
})
return res.status(200).json({
error: false,
message: "Pronto, feitinho!"
})
//console.log(`O que foi criado: ${req.body});
// return res.json(req.body)
})
});
//========= GET READ ALL ==============//
app.get("/", (req, res) => {
Artigo.find({}).then((artigo) => {
return res.json(artigo);
}).catch((err) => {
return res.status(400).json({
error: true,
message: "Nada consta! Parece estar vazio."
})
})
});
//============ GET READ ( =============//
app.get("/artigo/:id", (req, res) => {
Artigo.findOne({ _id: req.params.id }).then((artigo) => {
return res.json(artigo);
}).catch((err) => {
return res.status(400).json({
error: true,
message: "Nada consta!"
})
})
});
//=============== PUT UPDATE ===============//
app.put("/artigo/:id", (req, res) => {
const artigo = Artigo.updateOne({ _id: req.params.id }, req.body, (err) => {
if (err) return res.status(400).json({
error: true,
message: "Bahhh,oh meooo, deu ruim! Tente novamente tchee"
});
return res.json({
error: false,
message: "Sucesso total na missao, ediçao concluida"
});
})
});
//============ DELETE =================//
app.delete("/artigo/:id", (req, res) => {
const artigo = Artigo.deleteOne({ _id: req.params.id }, (err) => {
if (err) return res.status(400).json({
error: true,
message: "Uai so.... ainda ta ai esse trem... tenta denovo uai"
});
return res.json({
error: false,
message: "Oua, sumiu o trem!"
});
})
});
//========= PORT ============//
app.listen(8080, () => {
console.log(`Server is running at http://localhost:8080/`)
}) |
Java | UTF-8 | 9,435 | 2.265625 | 2 | [] | no_license | package FreeRun;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.World;
public class FR_Situation
{
private FR_Situation(double x, double y, double z, int lookdirection, World world, MovingObjectPosition objectmouseover)
{
nextPosX = posX = MathHelper.floor_double(x);
nextPosY = posY = (int) Math.ceil(y);
nextPosZ = posZ = MathHelper.floor_double(z);
lookDirection = lookdirection;
worldObj = world;
objectMouseOver = objectmouseover;
}
public boolean canClimbLeft()
{
return hasEdgeLeft();
}
public boolean canClimbRight()
{
return hasEdgeRight();
}
public boolean canClimbUp()
{
return hasEdgeUp();
}
public boolean canClimbDown()
{
return hasEdgeDown();
}
public boolean canHangStill()
{
return hasEdgeOnLocation(posX, posY, posZ);
}
public float canPushUp()
{
if (canClimbUp() || !canHangStill())
{
return 0F;
}
int x = posX;
int y = posY - 1;
int z = posZ;
boolean flag = hasAirAbove(x, y, z, 2);
if (lookDirection == FR_FreerunPlayer.LOOK_WEST)
{
z++;
} else if (lookDirection == FR_FreerunPlayer.LOOK_NORTH)
{
x--;
} else if (lookDirection == FR_FreerunPlayer.LOOK_EAST)
{
z--;
} else if (lookDirection == FR_FreerunPlayer.LOOK_SOUTH)
{
x++;
}
Material material = worldObj.getBlockMaterial(x, y, z);
//if (material.isSolid())
{
if (hasAirAbove(x, y, z, 2) && flag)
{
float f = y;
Block block = Block.blocksList[worldObj.getBlockId(x, y, z)];
if (block != null)
{
AxisAlignedBB bb = block.getCollisionBoundingBoxFromPool(worldObj, x, y, z);
if (bb != null)
{
f += bb.maxY - y - 1F;
}
}
return f;
}
}
return 0F;
}
public boolean canJumpUpBehind()
{
return hasEdgeUpBehind();
}
public boolean canClimbAroundEdgeLeft()
{
boolean flag = false;
int i = lookDirection;
lookDirection = (lookDirection + 1) % 4;
if (i == FR_FreerunPlayer.LOOK_WEST)
{
nextPosX = posX + 1;
nextPosZ = posZ + 1;
flag = hasEdgeOnLocation(nextPosX, posY, nextPosZ);
} else if (i == FR_FreerunPlayer.LOOK_NORTH)
{
nextPosZ = posZ + 1;
nextPosX = posX - 1;
flag = hasEdgeOnLocation(nextPosX, posY, nextPosZ);
} else if (i == FR_FreerunPlayer.LOOK_EAST)
{
nextPosX = posX - 1;
nextPosZ = posZ - 1;
flag = hasEdgeOnLocation(nextPosX, posY, nextPosZ);
} else if (i == FR_FreerunPlayer.LOOK_SOUTH)
{
nextPosZ = posZ - 1;
nextPosX = posX + 1;
flag = hasEdgeOnLocation(nextPosX, posY, nextPosZ);
}
lookDirection = i;
return flag;
}
public boolean canClimbAroundEdgeRight()
{
boolean flag = false;
int i = lookDirection;
lookDirection = (lookDirection - 1) % 4;
if (i == FR_FreerunPlayer.LOOK_WEST)
{
nextPosX = posX + 1;
nextPosZ = posZ + 1;
flag = hasEdgeOnLocation(nextPosX, posY, nextPosZ);
} else if (i == FR_FreerunPlayer.LOOK_NORTH)
{
nextPosZ = posZ + 1;
nextPosX = posX - 1;
flag = hasEdgeOnLocation(nextPosX, posY, nextPosZ);
} else if (i == FR_FreerunPlayer.LOOK_EAST)
{
nextPosX = posX - 1;
nextPosZ = posZ - 1;
flag = hasEdgeOnLocation(nextPosX, posY, nextPosZ);
} else if (i == FR_FreerunPlayer.LOOK_SOUTH)
{
nextPosZ = posZ - 1;
nextPosX = posX + 1;
flag = hasEdgeOnLocation(nextPosX, posY, nextPosZ);
}
lookDirection = i;
return flag;
}
private boolean hasAirAbove(int x, int y, int z, int i)
{
if (i >= 1)
{
Material material = worldObj.getBlockMaterial(x, y + 1, z);
if (i >= 2)
{
Material material1 = worldObj.getBlockMaterial(x, y + 2, z);
return !material.isSolid() && !material1.isSolid();
}
return !material.isSolid();
}
return false;
}
private boolean hasEdgeLeft()
{
boolean b = false;
if (lookDirection == FR_FreerunPlayer.LOOK_WEST)
{
nextPosX = posX + 1;
b = hasEdgeOnLocation(nextPosX, posY, posZ);
} else if (lookDirection == FR_FreerunPlayer.LOOK_NORTH)
{
nextPosZ = posZ + 1;
b = hasEdgeOnLocation(posX, posY, nextPosZ);
} else if (lookDirection == FR_FreerunPlayer.LOOK_EAST)
{
nextPosX = posX - 1;
b = hasEdgeOnLocation(nextPosX, posY, posZ);
} else if (lookDirection == FR_FreerunPlayer.LOOK_SOUTH)
{
nextPosZ = posZ - 1;
b = hasEdgeOnLocation(posX, posY, nextPosZ);
}
return b;
}
private boolean hasEdgeRight()
{
boolean b = false;
if (lookDirection == FR_FreerunPlayer.LOOK_WEST)
{
nextPosX = posX - 1;
b = hasEdgeOnLocation(nextPosX, posY, posZ);
} else if (lookDirection == FR_FreerunPlayer.LOOK_NORTH)
{
nextPosZ = posZ - 1;
b = hasEdgeOnLocation(posX, posY, nextPosZ);
} else if (lookDirection == FR_FreerunPlayer.LOOK_EAST)
{
nextPosX = posX + 1;
b = hasEdgeOnLocation(nextPosX, posY, posZ);
} else if (lookDirection == FR_FreerunPlayer.LOOK_SOUTH)
{
nextPosZ = posZ + 1;
b = hasEdgeOnLocation(posX, posY, nextPosZ);
}
return b;
}
private boolean hasEdgeUp()
{
nextPosY = posY + 1;
return hasEdgeOnLocation(posX, nextPosY, posZ);
}
private boolean hasEdgeDown()
{
nextPosY = posY - 1;
return hasEdgeOnLocation(posX, nextPosY, posZ);
}
private boolean hasEdgeUpBehind()
{
boolean b = false;
nextPosY = posY + 2;
if (lookDirection == FR_FreerunPlayer.LOOK_WEST)
{
nextPosZ = posZ - 1;
b = hasEdgeOnLocation(posX, nextPosY, nextPosZ);
} else if (lookDirection == FR_FreerunPlayer.LOOK_NORTH)
{
nextPosX = posX + 1;
b = hasEdgeOnLocation(nextPosX, nextPosY, posZ);
} else if (lookDirection == FR_FreerunPlayer.LOOK_EAST)
{
nextPosZ = posZ + 1;
b = hasEdgeOnLocation(posX, nextPosY, nextPosZ);
} else if (lookDirection == FR_FreerunPlayer.LOOK_SOUTH)
{
nextPosX = posX - 1;
b = hasEdgeOnLocation(nextPosX, nextPosY, posZ);
}
return b;
}
public static int getMetaData(int lookdirection)
{
if (lookdirection == FR_FreerunPlayer.LOOK_WEST)
{
return 2;
} else if (lookdirection == FR_FreerunPlayer.LOOK_NORTH)
{
return 5;
} else if (lookdirection == FR_FreerunPlayer.LOOK_EAST)
{
return 3;
} else if (lookdirection == FR_FreerunPlayer.LOOK_SOUTH)
{
return 4;
}
return 0;
}
private boolean hasEdgeOnLocation(int x, int y, int z)
{
int b = worldObj.getBlockId(x, y - 1, z);
int b1 = worldObj.getBlockId(x, y, z);
int md = worldObj.getBlockMetadata(x, y - 1, z);
int md1 = FR_Situation.getMetaData(lookDirection);
if (b1 == Block.vine.blockID || md == 0 || md == md1)
{
if (FR_FreerunPlayer.climbableInside.contains(b))
{
return true;
} else if (worldObj.getBlockMaterial(x, y, z).isSolid() || worldObj.getBlockMaterial(x, y - 1, z).isSolid())
{
return false;
}
}
if (lookDirection == FR_FreerunPlayer.LOOK_WEST)
{
z++;
} else if (lookDirection == FR_FreerunPlayer.LOOK_NORTH)
{
x--;
} else if (lookDirection == FR_FreerunPlayer.LOOK_EAST)
{
z--;
} else if (lookDirection == FR_FreerunPlayer.LOOK_SOUTH)
{
x++;
}
b = worldObj.getBlockId(x, y - 1, z);
b1 = worldObj.getBlockId(x, y, z);
if (FR_FreerunPlayer.climbableInside.contains(b))
{
return false;
}
if (FR_FreerunPlayer.climbableBlocks.contains(b))
{
blockHeight = (float) (Block.blocksList[b].maxY);
return true;
}
if (worldObj.getBlockMaterial(x, y - 1, z).isSolid())
{
if (b != b1)
{
blockHeight = (float) (Block.blocksList[b].maxY);
return !(((b == Block.stone.blockID || b == 14 || b == 15 || b == 16 || b == 21 || b == 56 || b == 73 || b == 74) && (b1 == Block.stone.blockID || b1 == 14 || b1 == 15 || b1 == 16 || b1 == 21 || b1 == 56 || b1 == 73 || b1 == 74)) || ((b == Block.dirt.blockID || b == Block.grass.blockID) && (b1 == Block.dirt.blockID || b1 == Block.grass.blockID)) || ((b == Block.cobblestone.blockID || b == Block.cobblestoneMossy.blockID || b == Block.stairCompactCobblestone.blockID) && (b1 == Block.cobblestone.blockID || b1 == Block.cobblestoneMossy.blockID || b1 == Block.stairCompactCobblestone.blockID)) || ((b == Block.planks.blockID || b == Block.stairCompactPlanks.blockID) && (b1 == Block.planks.blockID || b1 == Block.stairCompactPlanks.blockID)));
}
}
blockHeight = 1.0F;
return false;
}
public Vec3D getHangPositions()
{
double x = posX + 0.5D;
double y = posY - 0.1D - (1.0F - blockHeight);
double z = posZ + 0.5D;
Vec3D vec3d = Vec3D.createVector(x, y, z);
return vec3d;
}
private World worldObj;
public float blockHeight = 1.0F;
public int lookDirection;
private int posX;
private int posY;
private int posZ;
private int nextPosX;
private int nextPosY;
private int nextPosZ;
private MovingObjectPosition objectMouseOver;
public static FR_Situation getSituation(EntityPlayer player, int lookdirection, World world, MovingObjectPosition objectmouseover)
{
return new FR_Situation(player.posX, player.posY, player.posZ, lookdirection, world, objectmouseover);
}
public static FR_Situation getSituation(double x, double y, double z, int lookdirection, World world, MovingObjectPosition objectmouseover)
{
return new FR_Situation(x, y, z, lookdirection, world, objectmouseover);
}
}
|
Markdown | UTF-8 | 2,037 | 2.9375 | 3 | [] | no_license | # Neural and Behavioral Modeling 2018 Fall
Neural and Behavioral Modeling @ NTU, given by Prof. Tsung-Ren Huang.
## Syllabus
|Week|Subject|
|---|---|
|01|National Holiday|
|02|Course Introduction: Models & modeling|
|03|Behavioral Modeling (1/2): System dynamics|
|04|Behavioral Modeling (2/2): Agent-based modeling|
|05|Computational Cognitive Science (1/2): Basics|
|06|National Holiday|
|07|Computational Cognitive Science (2/2): Advanced |
|08|Computational Cognitive Neuroscience (1/8): Modeling principles & canonical neural computation |
|09|Computational Cognitive Neuroscience (2/8): Overview of learning & memory|
|10|Computational Cognitive Neuroscience (3/8): Local/shallow learning & memory|
|11|Computational Cognitive Neuroscience (4/8): Global/deep learning & memory|
|12|Computational Cognitive Neuroscience (5/8): Deep convolutional neural networks|
|13|Computational Cognitive Neuroscience (6/8): Deep reinforcement learning|
|14|Computational Cognitive Neuroscience (7/8): Deep recurrent neural networks|
|15|Computational Cognitive Neuroscience (8/8): Advanced issues & models|
|16|Computational Neuroscience (1/2): 1 spiking neuron|
|17|Computational Neuroscience (2/2): N spiking neurons|
## Weekly Assignments
### Assignments are in the hw folder. (R06227101_#.ipynb)
|# | Description |
|---|---|
|01|no assignment|
|02|1. Party Simulation <br>2. Shunting Equation|
|03|1. Nonlinear love triangle <br>2. Tragedy of the Commons|
|04|Replicate one Agent-Based Model (group genesis in homogeneous population)|
|05|1. Drifit Diffusion Model <br>2. Port EZdata.m from Matlab to Python |
|08|Replicate Sequence Memory Model|
|09|no assignment|
|10|2-layered Linear Network(numpy & pytorch version)|
|11|Tuning the performance of a neural net|
|12|1. Neural Network performance assessment <br>2. Universal Approximation Theorem|
|14|Activation/Signal Function in RNN|
|15|1. Visualizing the latent space of an autoencoder <br>2. Integer Factorization|
|16|Integrate-and-Fire Neuron with a Refractory Period|
|17|(optional)||
|
PHP | UTF-8 | 7,419 | 2.90625 | 3 | [
"MIT"
] | permissive | <?php
use Slim\Http\Request;
use Slim\Http\Response;
use WebDrinkAPI\Models\ApiKeys;
use WebDrinkAPI\Models\DrinkItemPriceHistory;
use WebDrinkAPI\Models\DrinkItems;
use WebDrinkAPI\Utils\API;
use WebDrinkAPI\Utils\Database;
function addItem($item_name, $item_price, API $api): DrinkItems {
// Creates a entityManager
$entityManager = Database::getEntityManager();
// Create new Item
$item = new DrinkItems();
$item->setItemName($item_name)->setItemPrice($item_price);
// Add to database
$entityManager->persist($item);
$entityManager->flush($item);
$item_history = new DrinkItemPriceHistory();
$item_history->setItemId($item->getItemId())->setItemPrice($item_price);
// Add to database
$entityManager->persist($item_history);
$entityManager->flush($item_history);
$api->logAPICall('/items/add', json_encode($item));
return $item;
}
function updateItem($item_id, $item_name, $item_price, $item_status, API $api): DrinkItems {
// Creates a entityManager
$entityManager = Database::getEntityManager();
$drinkItems = $entityManager->getRepository(DrinkItems::class);
$item = $drinkItems->findOneBy(["itemId" => $item_id]);
$item->setItemName($item_name)->setItemPrice($item_price);
// Add to database
$entityManager->persist($item);
$entityManager->flush($item);
$item_history = new DrinkItemPriceHistory();
$item_history->setItemId($item->getItemId())->setItemPrice($item_price);
// Add to database
$entityManager->persist($item_history);
$entityManager->flush($item_history);
$api->logAPICall('/items/update', json_encode($item));
return $item;
}
function deleteItem($item_id, API $api): DrinkItems {
// Creates a entityManager
$entityManager = Database::getEntityManager();
$drinkItems = $entityManager->getRepository(DrinkItems::class);
$item = $drinkItems->findOneBy(["itemId" => $item_id]);
// Add to database
$entityManager->remove($item);
$entityManager->flush($item);
$api->logAPICall('/items/delete', json_encode($item));
return $item;
}
/**
* GET /items/list - Get a list of all drink items
*/
$app->get('/list', function (Request $request, Response $response) {
// Creates a entityManager
$entityManager = Database::getEntityManager();
$drinkItems = $entityManager->getRepository(DrinkItems::class);
$activeItems = $drinkItems->findBy(["state" => "active"]);
// Creates an API object for creating returns
$api = new API(2);
if (!empty($activeItems)) {
return $api->result($response, true, "Success (/items/list)", $activeItems, 200);
} else {
return $api->result($response, true, "Failed to query database (/items/list)", false, 400);
}
});
/**
* POST /items/add/:name/:price - Add a new drink item (drink admin only)
*/
$app->post('/add/{name}/{price}', function (Request $request, Response $response) {
// Grabs the attributes from the url path
$item_name = $request->getAttribute('name');
$item_price = $request->getAttribute('price');
/** @var OpenIDConnectClient $auth */
$auth = $request->getAttribute('auth');
/** @var ApiKeys $apiKey */
$apiKey = $request->getAttribute('api_key');
if (!is_null($auth)) {
// Creates an API object for creating returns
$api = new API(2, $auth->requestUserInfo('preferred_username'));
if (in_array('drink', $auth->requestUserInfo('groups'))) {
$item = addItem($item_name, $item_price, $api);
return $api->result($response, true, "Success (/items/add)", $item->getItemId(), 200);
} else {
return $api->result($response, false, "Must be an admin to add items (/items/add)", false, 403);
}
} else if (!is_null($apiKey)) {
// Creates an API object for creating returns
$api = new API(2, $apiKey->getUid());
if ($api->isAdmin($apiKey->getUid())) {
$item = addItem($item_name, $item_price, $api);
return $api->result($response, true, "Success (/items/add)", $item->getItemId(), 200);
} else {
return $api->result($response, false, "Must be an admin to add items (/items/add)", false, 403);
}
}
});
/**
* POST /items/update/:item_id/:name/:price/:status - Update an existing drink item (drink admin only)
*/
$app->post('/update/{item_id}/{name}/{price}/{status}', function (Request $request, Response $response) {
// Grabs the attributes from the url path
$item_name = $request->getAttribute('name');
$item_price = $request->getAttribute('price');
$item_id = $request->getAttribute('item_id');
$item_status = $request->getAttribute('status');
/** @var OpenIDConnectClient $auth */
$auth = $request->getAttribute('auth');
/** @var ApiKeys $apiKey */
$apiKey = $request->getAttribute('api_key');
if (!is_null($auth)) {
// Creates an API object for creating returns
$api = new API(2, $auth->requestUserInfo('preferred_username'));
if (in_array('drink', $auth->requestUserInfo('groups'))) {
$item = updateItem($item_id, $item_name, $item_price, $item_status, $api);
return $api->result($response, true, "Success (/items/update)", $item->getItemId(), 200);
} else {
return $api->result($response, false, "Must be an admin to update items (/items/update)", false, 403);
}
} else if (!is_null($apiKey)) {
// Creates an API object for creating returns
$api = new API(2, $apiKey->getUid());
if ($api->isAdmin($apiKey->getUid())) {
$item = updateItem($item_id, $item_name, $item_price, $item_status, $api);
return $api->result($response, true, "Success (/items/update)", $item->getItemId(), 200);
} else {
return $api->result($response, false, "Must be an admin to update items (/items/update)", false, 403);
}
}
});
/**
* POST /items/delete/:item_id - Delete a drink item (drink admin only)
*/
$app->post('/delete/{item_id}', function (Request $request, Response $response) {
// Grabs the attributes from the url path
$item_id = $request->getAttribute('item_id');
/** @var OpenIDConnectClient $auth */
$auth = $request->getAttribute('auth');
/** @var ApiKeys $apiKey */
$apiKey = $request->getAttribute('api_key');
if (!is_null($auth)) {
// Creates an API object for creating returns
$api = new API(2, $auth->requestUserInfo('preferred_username'));
if (in_array('drink', $auth->requestUserInfo('groups'))) {
$item = deleteItem($item_id, $api);
return $api->result($response, true, "Success (/items/delete)", $item->getItemId(), 200);
} else {
return $api->result($response, false, "Must be an admin to delete items (/items/delete)", false, 403);
}
} else if (!is_null($apiKey)) {
// Creates an API object for creating returns
$api = new API(2, $apiKey->getUid());
if ($api->isAdmin($apiKey->getUid())) {
$item = deleteItem($item_id, $api);
return $api->result($response, true, "Success (/items/delete)", $item->getItemId(), 200);
} else {
return $api->result($response, false, "Must be an admin to delete items (/items/delete)", false, 403);
}
}
});
|
Swift | UTF-8 | 1,277 | 2.71875 | 3 | [] | no_license | //
// ViewController.swift
// FIT5140-Maybe the last Version
//
// Created by Burns on 2/9/19.
// Copyright © 2019 Burns. All rights reserved.
//
import UIKit
import MapKit
class ViewController: UIViewController {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
centerMapLocation(location: initialLocation)
}
let initialLocation = CLLocation(latitude: -37.8124, longitude: 144.9623)
//set the distance for the view
let regionRadius:CLLocationDistance = 1000
//This function is used to set the initial map view when use open the app.
func centerMapLocation(location:CLLocation){
let coordinateRegion = MKCoordinateRegion(center: location.coordinate,latitudinalMeters: regionRadius, longitudinalMeters: regionRadius)
mapView.setRegion(coordinateRegion, animated: true)
}
func focusOn(annotation: MKAnnotation){
mapView.selectAnnotation(annotation, animated: true)
let newCenter = MKCoordinateRegion(center: annotation.coordinate,latitudinalMeters: regionRadius, longitudinalMeters: regionRadius)
mapView.setRegion(newCenter, animated: true)
}
}
|
JavaScript | UTF-8 | 4,328 | 3.8125 | 4 | [] | no_license | /**
* Trabalhando com comentarios e arquivo js + overwie básico sobre JS.
*/
console.log('Oláaaa');
/*console.log('Oláaaa');
console.log('Oláaaa');*/
/**
* Utilizando varivel
*/
var olaMundo = "Olá, Mundo!";
console.log(olaMundo);
console.log(olaMundo);
console.log(olaMundo);
console.log(olaMundo);
/**
* var = comando para declarar variaveis.
* Novidades: (ES6 ES7) Declarações por escopo: let
*
*/
/**
* Atualização por escopo. Declarar variaveis com: let
* Declara variáveis definindo o escopo de atuação.
* Leva em consiferação o local que é declaro. Ela vai existir apenas num bloco de código.
*
* Comando const = Declarando uma constante.
* O valor nunca vai mudar. Gravou, ficou! :D
*
* "Constante é constante, variavel é variavel!"
*
*/
/**
* Tipos de dados gravados em variaveis.
*
* string (texto), number (numeros), objetos (array).
*
* Mostrar o tipo de dado da variavel: typeOf.
* Saber de onde veio uma instancia, objeto.
*
* *Função anonima numa varivel.
*
* Não precisa declarar o tipo da variavel, isso quer dizer que no JS as variaveis
* são FRACAMENTE TIPADAS (tipo de dado variavel).
*
* Funções de conversão:
* parseInt, parseFloat,
* (to string)
*
*/
/**
* Operadores aritmeticos
*
*
* Operadores de atribuição
* Exemplo:
*/
let a = 10;
const b = "10";
/**
* Operador de comparação
*
*/
console.log(a == b);
/**
*
* Operador de comparação, comparando o valor e o tipo de dado!
*
*/
console.log(a === b);
/**
* Operador de comparação, diferente
*
* Compara se os valores e tipos são diferentes
*
* !==
*
*/
console.log(a !== b);
/**
* Comparando apenas os dados (se são diferentes)
*
* !=
*
*/
console.log(a != b);
/**
*
* Operadores lógicos
*
* Exemplo: A é maior que B?
*
* AND = as duas condições precisam ser verdadeiras = &&
* OR = uma condição precisa ser verdadeira.
*/
console.log(a == b && typeof b == 'string');
// Verdadeiro E Verdadeiro = Verdadeiro
console.log(a == b && typeof a == 'string')
// Verdadeiro E falso = falso
/**
* Operador lógico OR.
* or é igual a: ou
*
*/
console.log(a == b || typeof a == 'string');
/**
*
* Operador incremental ou decremental
*
* a++;
* ou
* a--;
*
* Cada vez que se passa num laço, é adicionado mais 1 na variavel.
*
*/
/**
*
* Controlando fluxo.
*
* Estrutura de condição
*
*/
let cor = "amarelo";
if (cor === "verde") {
console.log("siga");
} else if (cor === "amarelo") {
console.log("atenção");
} else if (cor === "amarelo") {
console.log("pare");
}
/**
*
* Outro controle de fluxo.
*
* Estrutura de condição
*
*/
let cor2 = "azul";
switch(cor2) {
case "verde":
console.log("siga");
break;
case "amarelo":
console.log("atenção");
break;
case "vermleho":
console.log("pare");
break;
default:
console.log("não sei");
break;
}
/**
*
* Laços de repetição.
*
* Quando preciso repetir uma instrução no cógido, caso eu saiba quantas vezes repetirá ou não.
*
*/
// for, foreach, foring
// while, do while
// continue = ignora as instruções que defino. Passa direto e vai para o próximo.
let n = 5;
for (let i = 0; i <=10; i++) {
console.log(`${i} X ${n} = ${i*n}`);
// Recurso "novo": `Template String = ${js}
/**
*
* Dessa forma pode-se até quebrar linha.
*
* console.log(`
* ${i} X ${n} = ${i*n}
* `);
*
*
*/
console.log(i + " X " + n + " = " + (i * n));
}
|
C++ | UTF-8 | 948 | 3.578125 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int fact(int num); // proto
int largest(const int list[], int lowerIndex, int upperIndex);
int rFibNum(int a, int b, int n);
int main()
{
int mylist[] = { 5,10,12,8 };
//cout << fact(3) << endl;
//cout << largest(mylist, 0, 3) << endl;
cout << rFibNum(2, 3, 7) << endl;
system("pause");
return 0;
}
int rFibNum(int a, int b, int n)
{
if (n == 1)
{
return a;
}
else if( n ==2)
{
return b;
}
else
{
return rFibNum(a, b, n - 1) + rFibNum(a, b, n - 2);
}
}
int largest(const int list[], int lowerIndex, int upperIndex)
{
int max;
if (lowerIndex == upperIndex)
{
return list[lowerIndex];
}
else
{
max = largest(list, lowerIndex + 1, upperIndex);
if (list[lowerIndex] >= max)
{
return list[lowerIndex];
}
else
{
return max;
}
}
}
int fact(int num)
{
if (num == 0)
{
return 1;
}
else
{
return num * fact(num - 1);
}
}
|
Java | UTF-8 | 79,528 | 2.75 | 3 | [] | no_license | package org.jsweet;
import static def.dom.Globals.*;
import java.io.*;
import java.util.*;
public class Logic{
/** Logic modes - how to choose alternatives! */
static final int MODE_RANDOM_TYPED=0,
MODE_RANDOM_RELATED=1, MODE_COMPLETELY_RANDOM=2,
MODE_SOUNDS_SIMILAR=3,
MODE_BROTHER_OF_CORRECT=4,
MODE_BROTHER_OF_ROOT=5;
static final String[] MODE_NAMES = {"Random typed", "Random related", "Random.", "Looks similar", "Brother of correct", "Brother of root"};
EntityData ed;
Entity seed;
/** number of incorrect answers to generate */
int N=4;
/** Choose a random item as the root */
boolean randomroot = false;
/** Restrict possible roots to items with proper ultimate parents */
boolean restrRoot = false;
/** Restrict possible stems to items with proper ultimate parents */
boolean restrChoice = false;
/** Include descriptions in the reasoning */
boolean INCLUDE_DESCRIPTION=true;
/** permitted direction for question */
int[] DIRECTIONS = { Entity.CAUSE, Entity.EFFECT, Entity.TREATMENTS, Entity.TREATS };
/**
* an array of pairs of strings that wrap the root entity;
* currently one pair for each direction of questioning.
*/
String[][] questionHead ={
{"Which of the following is most likely to be the cause of " , "?"},
{"Which of the following are commonly associated with ", "?"},
{"Which of the following might be used to treat ", "?"},
{"Which of the following is most likely to be treated with ", "?"}
};
/** current question data: */
Entity[] incorrect; // incorrect options
String infoText; // info bout the question
String[] infoIncor; // info about the incorrect options
String infoCorrect; // info about the correct option
/** create a question, with new root, new correct, and store it in q. */
void newQuestion(int mode) {
q=new Question();
// the root entity is the one that appears in the question.
if(randomroot) { // select root randomly if user wants
boolean ok=false;
while(!ok) {
q.root=ed.getRandomEntity();
// ensure that is descends from a standard root node.
// This could be removed for more general questions.
ok=!restrRoot | Entities.hasAStandardUltimateParent(q.root);
}
}
else q.root=seed;
seed=q.root; // hold the last root?
q.mode=mode; // set the questioning mode of this question
int d1,d2; // direction forward and backwards
// construct the question text from the root entity
int attempt=0, numposs=0;
do {
q.direction = (int)Math.floor(Math.random()*DIRECTIONS.length); // choose a random direction
d1=DIRECTIONS[q.direction]; d2=Entity.inverseOf(d1); // and calculate its inverse
q.head = questionHead[q.direction][0] + q.root + questionHead[q.direction][1];
numposs=q.root.listOf(d1).size();
}while (numposs==0 && attempt++<10); if(attempt>=10) throw new IllegalStateException("Unable to find any questions for "+q.root);
// selet a random entity in the direction d1, as the correct answer.
Stem corrStem = new Stem();
q.correctStem.add(corrStem);
corrStem.correct=true;
Entity correct = (Entity)q.root.listOf(d1).get( (int)Math.floor(Math.random() * numposs) );
corrStem.entity=correct;
Entity correctTypeT = Entities.getUltimateParents(correct); // the type of the correct answer
Vector corrD2=correct.listOf(d2); corrD2.remove(q.root);
// generate some stock text for relations.
String rel1= d1==Entity.CAUSE?"Causes": d1==Entity.EFFECT ? "Effects" : d1==Entity.TREATMENTS?"Treatments":d1==Entity.TREATS?"Uses":"ERROR",
rel2=d1==Entity.CAUSE?"can cause":d1==Entity.EFFECT?"can be caused by":d1==Entity.TREATMENTS?"can treat":"can be treated by",
rel3= d1==Entity.CAUSE?"Effects":d1==Entity.EFFECT?"Causes":d1==Entity.TREATMENTS?"Uses":"Treatments";
corrStem.reasoning = rel1 +" of "+q.root+" include "+Entities.listToText(q.root.listOf(d1))+". \n";
if(corrD2.size()>0) corrStem.reasoning+= correct +" also "+ rel2 + " " + Entities.listToText(corrD2)+".";
if(INCLUDE_DESCRIPTION) corrStem.reasoning+='\n'+q.root.description;
incorrect=new Entity[N]; // create array of incorrect responses
infoIncor = new String[N];
for(int i=0;i<N;i++) { // generate the incorrects
Stem s=newIncorrect(incorrect, q.root, correct, q.direction, q.mode);
q.errorStems.add(s);
incorrect[i]=s.entity;
}
infoText="Incorrect answers are all "+infoText;
}
/**
* choose a single new incorrect item that isn't in Exclude.
* dirn is the direction to move from the root entity in order to find alternatives.
* mode is an index of the MODE_NAMES above
*/
Stem newIncorrect(Entity[] exclude, Entity root, Entity correct, int dirn, int mode ) {
int attempt=0; boolean isOK=false;
Stem s=null;
while(attempt++<100 && !isOK) { //stop if >100 iterations or found an ok item
s=newIncorrect(root, correct, dirn, mode); isOK=true;
for(int i=0;i<exclude.length;i++) {
if(s.entity==exclude[i]) isOK=false;
}
}
if(!isOK) throw new TryAgain();
return s;
}
/** choose a single new incorrect stem */
Stem newIncorrect(Entity root, Entity correct, int dirn, int mode) {
Stem stem=new Stem();
stem.correct=false;
int d1=DIRECTIONS[dirn], d2=Entity.inverseOf(d1);
String rel1= d1==Entity.CAUSE?"Causes":"Effects", rel2=d1==Entity.CAUSE?"can cause":"can be caused by",
rel3= d1==Entity.CAUSE?"Effects":"Causes", rel4=d1==Entity.CAUSE?"can be caused by":"can cause";
if(mode==MODE_RANDOM_TYPED || mode==MODE_RANDOM_RELATED || mode==MODE_COMPLETELY_RANDOM) {
/**
* Choose random items, filter by criteria:
* * parent equals correct items' parent (or grandparents equivalent)
* * not related by the same relation as the correct answer, to the root item.
*/
if(correct.parents.size()==0) throw new TryAgain();
Entity correctType1=(Entity)correct.parents.get(0), correctType2=null;
if(correctType1.parents.size()>0 && Math.random()>0.5 ) correctType2=(Entity)correctType1.parents.get(0);
Entity correctType0=(Entity)Entities.getUltimateParents(correct);
Entity tmp; int attempt=0; boolean sametype=false;
do {
tmp = ed.getRandomEntity();
//sametype = Entities.getUltimateParents(tmp) == correctTypeT;
if(mode==MODE_RANDOM_RELATED) {
if(tmp.parents.size()==0) sametype=false;
else {
Entity tmpp=(Entity)tmp.parents.get(0);
sametype = tmpp==correctType1 ;// || tmpp==correctType2;
// if(!sametype && tmpp.parents.size()>0) sametype=tmpp.parents.get(0)==correctType1 || tmpp.parents.get(0)==correctType2;
}
stem.reasoning = tmp+" is related to "+correct+" by being a type of "+correctType1;
}else if(mode==MODE_RANDOM_TYPED) {
sametype = Entities.getUltimateParents(tmp)==correctType0;
stem.reasoning = tmp+" is a "+correctType0; // random subtype
}else if(mode==MODE_COMPLETELY_RANDOM) {
sametype=true;
stem.reasoning = ""; // completely random!
}
} while ( ( !sametype // ensure of same generic type
|| Entities.isRelatedTo(root, tmp, d2 | Entity.PARENT | Entity.CHILD, 3, null) // ensure unrelated in the 'correct' direction
|| correct==tmp // ensure not the correct item (!) (should be subsumed by the prev check)
) && attempt++<5000 );
if(attempt>=5000) throw new IllegalStateException("Unable to find an unrelated ("+d1+") item to "+root+", of type "+correctType1);
infoText="randomly related";
stem.entity = tmp;
if(stem.entity.listOf(d1).size()>0) stem.reasoning+=" It "+rel4+" "+Entities.listToText(stem.entity.listOf(d1))+".";
if(stem.entity.listOf(d2).size()>0) stem.reasoning+=" It "+rel2+" "+Entities.listToText(stem.entity.listOf(d2))+".";
}else if(mode == MODE_SOUNDS_SIMILAR) { // choose unrelated items that sound similar
int NS=7;
Collection es = ed.getAllEntities();
double score[]=new double[es.size()],
hiscore[]=new double[NS];
Entity[] hient =new Entity[NS];
int idx=0;
for(int i=0;i<NS;i++) hiscore[i]=Double.MIN_VALUE; // clear hi-scores
for(Iterator i=es.iterator(); i.hasNext(); idx++) {
Entity ei=(Entity)i.next(); // for each entity,
// exclude if semantically close to the correct answer,
if(ei==correct || Entities.isRelatedTo(ei, correct, Entity.PARENT | Entity.CHILD | d1, 2, null)) continue;
score[idx] = compareStrings( ei.name, correct.name );
if(score[idx]>hiscore[0]) { // if it scores higher than any of the hi-choices,
int inspos=0;
while(inspos<NS-1 && score[idx]>hiscore[inspos+1]) inspos++; // find the appropriate position,
for(int j=0; j<inspos;j++) { // shift the lower elements down one place,
hiscore[j] = hiscore[j+1]; hient[j]=hient[j+1];
}
hiscore[inspos]=score[idx]; hient[inspos]=ei; // and insert it in the ascending list
}
infoText="Lexically similar to "+correct;
}
for(int i=0;i<NS;i++) {
//incorrect[i] = hient[i];
//infoIncor[i] = hient[i]+" looks similar to "+correct;
}
for(int i=0;i<5;i++)if(hiscore[i]<0.5) throw new TryAgain(); // disallow low similarity entities.
currentBank = new Vector(Arrays.asList( hient ));
int i=(int)(NS*Math.random());
stem.entity=hient[i];
stem.reasoning= hient[i]+" could be confused with "+correct+"."; // +hiscore[i];
if(stem.entity.listOf(d1).size()>0) stem.reasoning+=" It "+rel4+" "+Entities.listToText(stem.entity.listOf(d1))+".";
if(stem.entity.listOf(d2).size()>0) stem.reasoning+=" It "+rel2+" "+Entities.listToText(stem.entity.listOf(d2))+".";
}else if(mode==MODE_BROTHER_OF_CORRECT) {
/**
* Incorrect answers are brothers of the correct answer, that do not
* have the specified relation with the root element.
*/
if(correct.parents.size()==0) throw new TryAgain();
Entity p =(Entity)correct.parents.get(0);
Vector s=new Vector(Entities.getExtensiveListOf(Entity.CHILD, p, 10));
filterOutRelations(s, root, d2 | Entity.CHILD, 3);
s.remove(correct);
infoText="Brothers of "+correct;
if(s.size()<N) {
if(p.parents.size()>0) p=(Entity)p.parents.get(0);
s.addAll(Entities.getExtensiveListOf(Entity.CHILD, p, 10));
filterOutRelations(s, root, d2 | Entity.CHILD , 3);
s.remove(correct);
if(s.size()<N) throw new TryAgain(); // not enough brothers...
infoText="Cousins of "+correct;
}
//Vector r=choose(s,N);
//for(int i=0;i<N;i++) { incorrect[i] = (Entity)r.get(i); infoIncor[i]=r.get(i)+" is a type of "+p; }
currentBank=s;
int i=(int)(s.size()*Math.random());
stem.entity=(Entity)s.get(i);
stem.reasoning=stem.entity+" is a type of "+p+".";
if(stem.entity.listOf(d1).size()>0) stem.reasoning+=" It "+rel4+" "+Entities.listToText(stem.entity.listOf(d1))+".";
if(stem.entity.listOf(d2).size()>0) stem.reasoning+=" It "+rel2+" "+Entities.listToText(stem.entity.listOf(d2))+".";
}else if(mode==MODE_BROTHER_OF_ROOT) {
/**
* Incorrects are related to a brother of the root in the same way as the
* answer is related to the root.
*/
if(root.parents.size()==0) throw new TryAgain();
Entity p=(Entity)root.parents.get(0);
Set exclude = new HashSet(); exclude.add(root); // exclude the root from the children set
Set brothrs = Entities.getExtensiveListOf(Entity.CHILD, p, 2, exclude); // these are the eligible brothers
Set rels = new HashSet(); // use this to collate the items related in the same way as the correct answer
for(Iterator i=brothrs.iterator(); i.hasNext();) {
Entity b=(Entity)i.next();
exclude = new HashSet(); exclude.add(root); // exclude the root from the children set
rels.addAll(Entities.getExtensiveListOf(d1, b, 1, exclude));
}
rels.removeAll(brothrs);// eliminate degree zero!
Vector v=new Vector(rels); // eliminate items that actually do relate.
filterOutRelations(v, root, d2 /* | Entity.CHILD */, 3);
/*
v=choose(v,N);
infoText=Entities.getRelationNamesFromBits(d1)+"s of the brothers (& nephews) of "+root;
for(int i=0;i<N;i++) {
incorrect[i]=(Entity)v.get(i);
Vector ch=Entities.findRelationChains(p, incorrect[i], Entity.CHILD | d1, 4, null, null, null, 0);
if(ch.size()==0) throw new IllegalStateException("Could not find chain for brother of root: "+p+"'s children's "+Entities.getRelationNamesFromBits(d1)+ " don't include "+incorrect[i]);
int shortest=0, shortlen=100, tmp;for(int j=0;j<ch.size();j++) if((tmp=((Vector)ch.get(j)).size())<shortlen) {shortest=j; shortlen=tmp;} // find shortest chain
Vector inf=(Vector)ch.get(shortest); Collections.reverse(inf);
infoIncor[i]=Entities.chainText(inf);
}
*/
if(v.size()==0)throw new TryAgain();
currentBank=v;
int i=(int)(v.size()*Math.random());
stem.entity=(Entity)v.get(i);
// create the causal chain
Vector ch=Entities.findRelationChains(p, stem.entity, Entity.CHILD | d1, 4, null, null, null, 0);
if(ch.size()==0) throw new IllegalStateException("Could not find chain for brother of root: "+p+"'s children's "+Entities.getRelationNamesFromBits(d1)+ " don't include "+stem.entity);
int shortest=0, shortlen=100, tmp;for(int j=0;j<ch.size();j++) if((tmp=((Vector)ch.get(j)).size())<shortlen) {shortest=j; shortlen=tmp;} // find shortest chain
Vector inf=(Vector)ch.get(shortest); Collections.reverse(inf);
try {
stem.reasoning = Entities.chainText(inf);
}catch(IllegalArgumentException x) {x.printStackTrace();}
if(stem.entity.listOf(d1).size()>0) stem.reasoning+=" It "+rel4+" "+Entities.listToText(stem.entity.listOf(d1))+".";
if(stem.entity.listOf(d2).size()>0) stem.reasoning+=" It "+rel2+" "+Entities.listToText(stem.entity.listOf(d2))+".";
}
if(INCLUDE_DESCRIPTION) stem.reasoning+='\n'+stem.entity.description;
return stem;
}
/** set of entities that could be used as incorrect answers */
Vector currentBank=new Vector();
/** is any of the items in a[0 to N-1] equal to e? */
boolean anyarrayequal(Entity[] a, int N, Entity e) { boolean f=false;
for(int i=0;i<N;i++) if (a[i]==e) f=true;
return f;
}
/** randomly choose n items from c into a vector */
Vector choose(Collection s, int n) {
int ns = s.size(); Vector result= new Vector();
if(ns<n) throw new IllegalStateException("Cannot choose "+n+" items from a set "+s+" of "+ns);
Vector<Integer> r=new Vector<Integer>();
for(int i=0;i<ns;i++){r.add(new Integer(i));} // fill r with integers up to the set size
Collections.shuffle(r); // shuffle, then select the first N from the shuffled list
Iterator it=s.iterator(); int un=0; // number stored so far?
for(int i=0;i<ns;i++) { // go through each possible item
Object o=it.next();
for(int j=0;j<n;j++) if(((Integer)r.get(j)).intValue() == i )
{result.add(o); un++;} // and if it was chosen (in r), add it.
if(un>=n) break; // complete?
}
return result;
}
/** remove any items from v which are related to 'relative' by relations 'relations'
* to a depth 'depth'
*/
void filterOutRelations(Vector v, Entity relative, int relations, int depth) {
Vector rm=new Vector();
for(int i=0;i<v.size();i++) {
if(Entities.isRelatedTo((Entity)v.get(i), relative, relations, depth, null))
rm.add(v.get(i));
}
v.removeAll(rm);
}
/** @return lexical similarity value in the range [0,1] */
public static double compareStrings(String str1, String str2) {
ArrayList pairs1 = wordLetterPairs(str1.toUpperCase());
ArrayList pairs2 = wordLetterPairs(str2.toUpperCase());
int intersection = 0;
int union = pairs1.size() + pairs2.size();
for (int i=0; i<pairs1.size(); i++) {
Object pair1=pairs1.get(i);
for(int j=0; j<pairs2.size(); j++) {
Object pair2=pairs2.get(j);
if (pair1.equals(pair2)) {
intersection++;
pairs2.remove(j);
break;
}
}
}
return (2.0*intersection)/union;
}
/** @return an ArrayList of 2-character Strings. */
private static ArrayList wordLetterPairs(String str) {
ArrayList allPairs = new ArrayList();
// Tokenize the string and put the tokens/words into an array
String[] words = str.split("\\s");
// For each word
for (int w=0; w < words.length; w++) {
// Find the pairs of characters
String[] pairsInWord = letterPairs(words[w]);
for (int p=0; p < pairsInWord.length; p++) {
allPairs.add(pairsInWord[p]);
}
}
return allPairs;
}
/** @return an array of adjacent letter pairs contained in the input string */
private static String[] letterPairs(String str) {
int numPairs = str.length()-1;
if(numPairs<1) return new String[0];
String[] pairs = new String[numPairs];
for (int i=0; i<numPairs; i++) {
pairs[i] = str.substring(i,i+2);
}
return pairs;
}
static class TryAgain extends RuntimeException{};
Question q;
/**
* Call newQuestion() then
* Create a question structure from the current logic
*/
Question getNewQuestion(int mode) {
/** create 4 wrong and 1 right options */
newQuestion(mode);
return q;
}
/**
* generate a single new Stem according to the current logic and current
* question's root, correct, direction and mode.
*/
Stem generateNewStem() {
return newIncorrect(incorrect, q.root, q.correctStem.get(0).entity, q.direction, q.mode);
}
void setQuestion(Question qu) {
qu=qu;
}
public void setStem(Stem stem, Entity newItem){
// Auto-generate stem contents from an entity
stem.entity=newItem;
stem.reasoning = Essay.getText(newItem);
}
}
public class Entity implements Serializable{
static int serial=0;
public static final int PARENT=1, CHILD=2, CAUSE=4, EFFECT=8, TREATS=16,
TREATMENTS=32;
public static int relationList[]= new int[]{CAUSE, EFFECT, PARENT, CHILD, TREATS, TREATMENTS};
public static String[] relationNameList =
{"Causes", "Effects", "Supertypes", "Subtypes", "Treats", "Treatments"};
double[] probs[];
public Entity(Entity from, int connection) {
children=new Vector();
parents=new Vector();
causes=new Vector();
effects=new Vector();
treats=new Vector();
treatments=new Vector();
if(from!=null){
connect(from, connection);
}
synonyms=new Vector();
name="Entity"+serial++;
description="";
}
/**
eg. listOf(PARENT) returns parent.
*/
public Vector listOf(int relation){
switch(relation){
case PARENT: return parents;
case CHILD: return children;
case CAUSE: return causes;
case EFFECT: return effects;
case TREATS: return treats;
case TREATMENTS: return treatments;
}
return null;
}
/**
* List the probabilities of the entities related to this entity.
* return null if not set.
*/
public double[] probsOf(int relation){
if(probs==null) return null;
for(int i=0;i<relationList.length;i++){
if((relationList[i]&relation)>0){
double[] v=probs[i];
if(v==null)continue;
if(v.length!=listOf(relation).size()){
ensureConnectionProbs(relation);
}
return v;
}
} return null;
}
private static int probidxOfRel(int rel){
for(int i=0;i<relationList.length;i++){
if((relationList[i]&rel)>0){
return i;
}
}throw new IllegalArgumentException(rel+" is not a relation.");
}
/** return the name of the first relation in the bitwise flags 'rel' */
public static String nameOfRelation(int rel){
return relationNameList[probidxOfRel(rel)];
}
/** return the bitwise flags for a given relation string. return 0 if not a valid string. */
public static int getRelationForName(String s){
for(int i=0;i<relationNameList.length;i++){
if(relationNameList[i].toLowerCase().equals(s.toLowerCase())) return relationList[i];
}
return 0;
}
private void removeProb(int rel, int idx){
if(probs!=null){
double[] op=probs[probidxOfRel(rel)];
if(op!=null){
double[] np=new double[op.length-1];
System.arraycopy(op, 0, np, 0, idx);
System.arraycopy(op, idx+1, np, idx, op.length-idx-1);
probs[probidxOfRel(rel)] = np;
}
}
}
public void moveListItem(int rel, int idx1, int idx2){
Object o=listOf(rel).get(idx1);
if(idx1==idx2)return;
int dest=idx2;
if (idx1 < idx2) {
dest--;
}
listOf(rel).remove(idx1);
Vector<Object> v= listOf(rel);
v.insertElementAt(o, dest);
double p[]=probsOf(rel);
if(p!=null){
double tmp=p[idx1];
if(idx2>idx1) for(int i=idx1; i<dest; i++) p[i]=p[i+1];
else for(int i=idx1; i>dest; i--) p[i]=p[i-1];
p[dest]=tmp;
}
}
/** remove a probability list if all NaN */
public void checkIfProbsClear(){
if(probs!=null){
for(int i=0;i<probs.length;i++){
if(probs[i]==null) continue;
boolean empty=true;
for(int j=0;j<probs[i].length;j++){
if(!Double.isNaN(probs[i][j])) empty=false;
}
if(empty) probs[i]=null;
}
}
}
/**
* Set the probabilities of the entities related to this entity.
* the probabilities x must have name size as number of related items.
*/
public void setProbOf(int relation, int idx, double x){
if(probs==null) probs=new double[relationList.length] [];
for(int i=0;i<relationList.length;i++){
if((relationList[i]&relation)>0){
if(probs[i]==null){
int nrel=listOf(relation).size();
probs[i]=new double[nrel];
for(int j=0;j<nrel;j++) probs[i][j]=Double.NaN;
}else if(probs[i].length<=idx){
int nrel=listOf(relation).size();
double[] npr=new double[nrel];
for(int j=0;j<probs[i].length;j++) npr[j]=probs[i][j];
for(int j=probs[i].length; j<nrel; j++) npr[j]=Double.NaN;
probs[i]=npr;
}
probs[i][idx]=x;
}
}
}
public static int inverseOf(int reciprocalRelation){
switch(reciprocalRelation){
case PARENT: return CHILD;
case CHILD: return PARENT;
case CAUSE: return EFFECT;
case EFFECT: return CAUSE;
case TREATS: return TREATMENTS;
case TREATMENTS: return TREATS;
}
return 0;
}
/**
e.g. A.connect(B, PARENT) means
A.parents.add(B); B.children.add(A)
*/
public void connect(Entity to, int connectAs){
Vector mylist=listOf(connectAs);
if(mylist.indexOf(to)>=0)return; //already connected!
listOf(connectAs).add(to);
ensureConnectionProbs(connectAs);
to.listOf(inverseOf(connectAs)).add(this);
to.ensureConnectionProbs(inverseOf(connectAs));
}
/** expand the probabilities list to the correct size after adding a connection*/
public void ensureConnectionProbs(int rel){
boolean error=false;
if(probs!=null){
int r=probidxOfRel(rel);
if(probs[r]!=null){
int n=listOf(rel).size(); // length of entities
int nn = probs[r].length; // length of probs list
if(nn==n) return; // OK
double[] np=new double[n];
if( n < nn) { // there are too many probs!
nn=n; // remove some probs
error=true;
}
System.arraycopy(probs[r], 0, np, 0, nn);
for(int j=probs[r].length; j<np.length;j++)
np[j]=Double.NaN;
probs[r]=np;
}
}
if (error) {
throw new IllegalStateException("The list "+this+"."+relationNameList[rel]+" has too many probabilities. I am truncating the list, possible losing data.");
}
}
public void disconnect(Entity from, int relation){
//check that this is not the only connection!
if(numConnections()<2){System.out.println("Cannot delete last connection");return;}
if(listOf(relation).contains(from)){
int idx=listOf(relation).indexOf(from);
listOf(relation).remove(from);
removeProb(relation, idx);
int idx2=from.listOf(inverseOf(relation)).indexOf(this);
from.listOf(inverseOf(relation)).remove(this);
from.removeProb(inverseOf(relation),idx2 );
}
}
public String toString(){return name;}
//SERIALISED MEMBERS
public Vector children, parents, causes, effects,
synonyms;
public String name;
public String description;
public Vector treats, treatments;
public Vector pChildren, pCauses, pEffects; // the probabilities
/**
* Check if equal to name or any of the synonyms
*/
public boolean equals(String s){
if(name.equals(s))return true;
for(int i=0;i<synonyms.size();i++){
if(s.equals((String)synonyms.get(i)))return true;
}
return false;
}
public boolean equalsIgnoreCase(String s){
if(name.equalsIgnoreCase(s))return true;
for(int i=0;i<synonyms.size();i++){
if(s.equalsIgnoreCase((String)synonyms.get(i)))return true;
}
return false;
}
public boolean contains(String s){
if(name.indexOf(s)>=0) return true;
for(int i=0;i<synonyms.size();i++){
if(((String)synonyms.get(i)).indexOf(s)>=0)return true;
}
return false;
}
public boolean containsIgnoreCase(String s){
if(indexOfIgnoreCase(name,s)>=0)return true;
for(int i=0;i<synonyms.size();i++){
if(indexOfIgnoreCase( (String)synonyms.get(i), s )>=0) return true;
}
return false;
}
int indexOfIgnoreCase(String main, String sub){
for(int k=0;k<=main.length()-sub.length();k++){
if(main.substring(k, k + sub.length()).equalsIgnoreCase(sub))
return k;
}
return -1;
}
/**
* Is the object blank -- i.e. does it have connections other than its
* original one?
*/
public boolean isBlank(){
return synonyms.isEmpty() && numConnections()<2 && description.equals("") ;
}
/**
* Replaces any uses of the current entry with the replacement entry,
* leaving this entry disconnected & henceforth discardable
*/
public void replaceAllWith(Entity replacement){
for(int i=0;i<relationList.length;i++){
int rel=relationList[i];
Vector v=listOf(rel);
for(int j=0;j<v.size();j++){
Entity dest=(Entity)v.get(j);
replacement.connect(dest, rel);
dest.disconnect(this, inverseOf(rel));
}
}
}
/**
* Count total number of links this object has with other objects
*/
int numConnections(){
int n=causes.size()+effects.size()+parents.size()+children.size();
n+=treatments.size() + treats.size();
return n;
}
}
public class EntityData {
private Hashtable namesToEntities=new Hashtable();
public EntityData() {
}
/** Collection of entities backed by the hashtable of names */
public Collection getAllEntities(){
return namesToEntities.values();
}
public long saveTime;
public long lastRead;
/** Create new entity with given name and no connections */
public Entity addNewEntity(String name){
Entity e=new Entity(null,0);
e.name=name;
Object o=namesToEntities.put(name,e);
if(o!=null) throw new IllegalStateException("Two entites with key "+name);
return e;
}
public Entity addNewEntity(Entity from, int relation){
Entity e=new Entity(from, relation);
Object o=namesToEntities.put(e.name,e);
if(o!=null) throw new IllegalStateException("Two entites with key "+e.name);
return e;
}
public void removeEntity(Entity r){
namesToEntities.remove(r.name);
}
public void removeAllOf(Collection e){
for(Iterator i=e.iterator();i.hasNext();){
removeEntity((Entity)i.next());
}
}
/** update the name hash table */
void refreshNames(){
Collection es=namesToEntities.values();
Hashtable nht=new Hashtable();
for(Iterator i=es.iterator();i.hasNext();){
Entity e=(Entity)i.next();
nht.put(e.name, e) ;
}
namesToEntities=nht;
}
/** Check that all entities are found in the data */
public void checkIntegrity() throws DataIntegrityException{
Collection c=namesToEntities.values();
for(Iterator it=c.iterator();it.hasNext();){
Entity e=(Entity)it.next();
for(int i=1;i<Entity.relationList.length;i++){
Vector v=e.listOf(Entity.relationList[i]);
for(Iterator it2=v.iterator();it2.hasNext();){
Entity e2=(Entity)it2.next();
if(!c.contains(e2)){
throw new DataIntegrityException(e2.name + " not found in data.");
}
}
}
}
}
public int size(){return namesToEntities.size();}
public Entity findEntityExact(String name){
return (Entity)namesToEntities.get(name);
}
public Vector findEntities(String text,boolean contains, boolean csensitive){
Vector res = new Vector();
for(Enumeration k=namesToEntities.elements();k.hasMoreElements();){
Entity c=(Entity)k.nextElement();
String s=c.name;
String textlc=text.toLowerCase();
if(contains){
if(csensitive){
if (s.indexOf(text)>=0) {res.addElement(namesToEntities.get(s));continue;}
}else{
if (s.toLowerCase().indexOf(textlc) >= 0) {
res.addElement(namesToEntities.get(s));
continue;
}
}
for(int i=0;i<c.synonyms.size();i++){
String syn=(String)c.synonyms.elementAt(i);
if(csensitive){
if (syn.indexOf(text)>=0) {res.addElement(namesToEntities.get(s));break;}
}else{
if (syn.toLowerCase().indexOf(textlc) >= 0) {
res.addElement(namesToEntities.get(s));
break;
}
}
}
}else{
if(csensitive){
if (s.equals(text)) res.addElement(namesToEntities.get(s));
}else{
if (s.equalsIgnoreCase(text)) res.addElement(namesToEntities.get(s));
}
}
}
return res;
}
/** @deprecated never crawl entities: the stack trace gets too deep. */
@Deprecated public Entity getFirstEntity() {
return (Entity)namesToEntities.values().iterator().next();
}
/**
* this is a silly method that returns an entity by its serial index.
* This serial index changes all the time, so don't use it except to generate
* a random entity.
* It is also slow, as it iterates through N entities!
*/
private Entity getItemAtIndex(int n){
int index=0;
for(Iterator i=namesToEntities.values().iterator(); i.hasNext();index++) {
Object o=i.next();
if(index==n) return (Entity)o;
}
throw new ArrayIndexOutOfBoundsException("can't get entity at index "+n);
}
public Entity getRandomEntity(){
return getItemAtIndex((int)Math.floor(Math.random() * getAllEntities().size()));
}
/**
* Parse an edit string
* return: true if an edit was made
* dispatches to the relevant implementEdit... functions
*/
public boolean implementEdit(String editString) throws MedicineEditException{
String[] s=editString.split("\t"); // split on tabs
int i=0;
while(s[i].length()==0) i++;
String cmd=s[i].toLowerCase().trim();
int rel=Entity.getRelationForName(s[2].trim());
Entity e1=findEntityExact(s[1].trim()), e2=findEntityExact(s[3].trim());
// dispatch to implementEdit functions
if(cmd.equals("remove")){
if(s[2].equalsIgnoreCase("Synonyms")){ // remove synonym
if(e1==null) throw new MedicineEditException("no entity for synonym in "+editString);
return implementEditRemoveSynonym(e1, s[3]);
}else{ // remove an entity link
if(e1==null || rel==0 || e2==null) throw new MedicineEditException("no such link in "+editString);
return implementEditDelete(e1, rel,e2);
}
}else if(cmd.equals("add")){
if(s[2].equalsIgnoreCase("Synonym")){ // add a synonym
if(e1==null) throw new MedicineEditException("no entity for synonym in "+editString);
return implementEditAddSynonym(e1, s[3]);
}else{ // add an entity (new or old)
if(e1==null || rel==0) throw new MedicineEditException("invalid new link in "+editString);
if(e2==null) e2=addNewEntity(s[3]); // none existing - create.
return implementEditAdd(e1, rel, e2);
}
}else if(cmd.equals("edit")){ // only used for description
if(s[2].equalsIgnoreCase("Name") ){
String newname = s[3].trim();
if(e1==null || newname.length()==0) throw new MedicineEditException("invalid name edit: "+editString);
return implementEditName(e1, s[3]);
}else if(s[2].equalsIgnoreCase("Description")){
String desc=s[3]; // perform any transformations here, e.g. remove HTML / quotes
if(e1==null) throw new MedicineEditException("no entity for description in "+editString);
return implementEditDescription(e1, desc);
}else throw new MedicineEditException("unknown edit: "+s[2]+" in "+editString);
}else if(cmd.equals("updatepercent")){
if(e1==null || rel==0 || e2==null) throw new MedicineEditException("invalid link for percentage in "+editString);
double percent;
try{
percent = Double.parseDouble(s[4]);
}catch(NumberFormatException e){ throw new MedicineEditException("Not a valid percentage: "+s[4]+" in "+editString); }
return implementEditUpdatePercent(e1, Entity.getRelationForName(s[2]), e2, percent);
}else if(cmd.equals("comment")){
return true; // do nothing.
}else throw new MedicineEditException("unknown command: "+cmd+" in "+editString);
}
/**
* create a string representing an edit.
* Starts with a command, then tab-separated arguments.
* e.g. remove Disease Child Infection
* add Disease Child Infection
* edit Disease Name Diseases (relation can be Name or Description)
* updatepercent Disease Child Infection 0.5
* comment Disease not sure about this one
*/
public static String createEditString(String command, Entity entity, String relation, String item,
String value ) throws MedicineEditException {
String cmd = command.toLowerCase(), string;
if(cmd.equals("remove")){ // e.g. remove Disease Child Infection
string=cmd+"\t"+entity.name+"\t"+relation+"\t"+item;
}else if(cmd.equals("add")){ // e.g. add Disease Child Infection
string=cmd+"\t"+entity.name+"\t"+relation+"\t"+item;
}else if(cmd.equals("edit")){ // e.g. edit Disease Name Diseases
// "relation" can be "Name" or "Description"
string=cmd+"\t"+entity.name+"\t"+relation+"\t"+item;
}else if(cmd.equals("updatepercent")){ // e.g. updatepercent Disease Child Infection 0.5
string=cmd+"\t"+entity.name+"\t"+relation+"\t"+item+"\t"+value;
}else if(cmd.equals("comment")){ // e.g. comment Disease not sure about this one
string=cmd+"\t"+value;
}else{
throw new MedicineEditException("unknown command: "+cmd);
}
return string;
}
//// actuall DO EDITS here: (protected)
boolean implementEditRemoveSynonym(Entity e, String syn){
if(e.synonyms.contains(syn)){
e.synonyms.removeElement(syn);
return true;
}else return false;
}
boolean implementEditAddSynonym(Entity e, String syn){
return true;
}
boolean implementEditDelete(Entity e, int rel, Entity item){
if(e.listOf(rel).contains(item)){
e.disconnect(item,rel);
return true;
} else return false;
}
boolean implementEditAdd(Entity e, int rel, Entity item){
e.connect(item, rel); return true;
}
boolean implementEditName(Entity e, String n) throws MedicineEditException{
String legalchars="ABCDEFGHIJKLMNOPQRTSUVWXYZabcdefghijklmnopqrtsuvwxyz' -";
for(int i=0;i<n.length();i++)
if(legalchars.indexOf(n.charAt(i))<0) throw new MedicineEditException("Illegal character "+n.charAt(i)+" in new name for "+e+", "+n);
namesToEntities.remove(e.name); // remove from hash table
e.name = n;
namesToEntities.put(e.name, e); // put new name in hash table
return true;
}
boolean implementEditDescription(Entity e, String d){
e.description=d; return true;
}
boolean implementEditUpdatePercent(Entity e, int rel, Entity item, double p){
int ix = e.listOf(rel).indexOf(item); // index of item
if(ix>=0) {
e.setProbOf(rel, ix, p);
return true;
} else return false;
}
public static class MedicineEditException extends Exception{
public MedicineEditException(String c){super(c);}
}
}
public class DataIntegrityException extends IllegalStateException{
public DataIntegrityException(String s){super(s);}
}
/**
* General utilities for use with tht class Entity
*/
public class Entities {
public Entities() {
}
EntityData entityData;
public static final String[] standardStrings = {
"Disease","Pathology","Investigation","Sign",
"Symptom","Substance","Treatment","Lifestyle"
};
/** bits representing which ultimate parent */
public static int E_DISEASE=1, E_PATHOLOGY=2, E_INVESTIGATION=4, E_SIGN=8,
E_SYMPTOM=16, E_SUBSTANCE=32, E_TREATMENT=64, E_LIFESTYLE=128;
public static boolean isStandardUltimateParent(Entity e) {
if(e==null) return false;
for(int i=0;i<standardStrings.length;i++)
if(e.name.equals(standardStrings[i])) return true;
return false;
}
public static boolean hasAStandardUltimateParent(Entity e) {
Set l=getExtensiveListOf(Entity.PARENT, e, 15);
for(Iterator i=l.iterator();i.hasNext();)if( isStandardUltimateParent((Entity)i.next()) ) return true;
return false;
}
/** modify the vector to contain only entities which have a standard ultimate parent */
public void filterVectorForStandardParents(Vector v) {
Vector rm=new Vector();
for(int i=0;i<v.size();i++) if( isStandardUltimateParent( getUltimateParents((Entity)v.get(i))) ) rm.add(v.get(i));
v.removeAll(rm);
}
/**
* modify the vector to contain only entities which have the specified ultimate parent
* (specify a combination of the bits E_DISEASE E_PATHOLOGY etc)
*/
public static void filterVectorForStandardParents(Vector v, int ultimateParent ) {
Vector rm=new Vector();
for(int i=0;i<v.size();i++) {
Entity e=(Entity)v.get(i), ultP = getUltimateParents(e);
boolean ok=false;
if(ultP!=null) {
for(int b=0;b<8;b++) { // for each bit in ultimateParent,
if( (ultimateParent & (1<<b))>0 && ultP.name.equals(standardStrings[b]) ) ok=true;
}
}
if(!ok) rm.add(v.get(i));
}
v.removeAll(rm);
}
public void setData(EntityData e){
Vector toremove=new Vector();
for(Iterator i=e.getAllEntities().iterator();i.hasNext();){
Entity en=(Entity)i.next();
int nconn=0;
for(int j=0;j<Entity.relationList.length;j++){
Vector v=en.listOf(Entity.relationList[j]);
nconn+=v.size();
}
if(nconn==0){ //remove items which are disconnected
toremove.add(en);
}
int nsyn=en.synonyms.size();
for(int j=0;j<nsyn;j++) {
for(int k=j+1;k<nsyn;k++) {
if(en.synonyms.get(j).equals(en.synonyms.get(k))) {
en.synonyms.set(k, ""); // remove duplicated synonyms
}
}
}
for(int j=0;j<en.synonyms.size();j++)if(en.synonyms.get(j).equals("")) {
en.synonyms.remove(j--);
}
}
e.removeAllOf(toremove);
entityData=e;
}
public EntityData getData(){return entityData;}
public void writeTextForm(OutputStream os){
PrintStream out=new PrintStream(os);
synchronized (this){
for(Iterator i=entityData.getAllEntities().iterator();i.hasNext();){
Entity ent=(Entity)i.next();
writeTextForm(out,ent);
}
writeTimeToStream(out, new Date().getTime());
}
}
private void writeTimeToStream(PrintStream pw, long time){
pw.println("_SAVED_TIME "+time);
}
/**
format of output:
Pulmonary fibrosis{
Synonyms { Lung fibrosis, Fibrosis of lung }
Children { Apical lung fibrosis, Basal lung fibrosis }
Description {"Scarring and fibrous change of the
pulmonary interstitium"}
Parents { Lung pathology }
}
Aortic stenosis{
...
}
*/
void writeTextForm(PrintStream out, Entity e){
out.println(e.name+" {");
if(e.synonyms.size()>0)
out.println("\tSynonyms {" + getDelimitedNames(e.synonyms,", ") + "}");
if(e.causes.size()>0)
out.println("\tCauses {" + getDelimitedEntities(e, Entity.CAUSE,", ") + "}");
if(e.effects.size()>0)
out.println("\tEffects {" + getDelimitedEntities(e, Entity.EFFECT,", ") + "}");
if(e.parents.size()>0)
out.println("\tParents {" + getDelimitedEntities(e, Entity.PARENT,", ") + "}");
if(e.children.size()>0)
out.println("\tChildren {" + getDelimitedEntities(e, Entity.CHILD,", ") + "}");
if(e.treats.size()>0)
out.println("\tTreats {" + getDelimitedEntities(e, Entity.TREATS, ", ") + "}");
if(e.treatments.size()>0)
out.println("\tTreatments {" + getDelimitedEntities(e, Entity.TREATMENTS,", ") + "}");
if(!e.description.equals(""))
out.println("\tDescription {\"" + e.description.replace('{','(')
.replace('}',')') + "\"}");
out.println("}");
}
public static EntityData readTextForm(InputStream is) throws IOException{
// BufferedReader br=new BufferedReader(fr);
InputStreamReader fr = null;
EntityData data=null;
try {
fr = new InputStreamReader(is);
data = new EntityData();
while (true) {
readEntity(data, fr);
}
} catch (EOF e) { /** End of file encountered */ }
if (fr != null) { fr.close(); }
if(data==null)return null;
if(data.size()==0)return null;
validateConnections(data);
return data;
}
/** Merge two input streams in text format
* @deprecated - use the single-stream version to merge with a dataset*/
@Deprecated public static Entity mergeTextFromStreams(InputStream is, InputStream is2) throws IOException{
InputStreamReader fr = null;
EntityData data = null;
try {
fr = new InputStreamReader(is);
data = new EntityData();
while (true) {
readEntity(data, fr);
}
} catch (EOF e) { /** End of file encountered */}
if (fr != null) {fr.close(); fr=null; }
if (data == null) data=new EntityData();
try {
fr = new InputStreamReader(is2);
while (true) {
readEntity(data, fr);
}
} catch (EOF e) { /** End of file encountered */}
if (fr != null) { fr.close(); }
if (data == null)return null;
if (data.size()==0)return null;
return data.getFirstEntity();
}
public static EntityData mergeTextFromStream(EntityData d, InputStream is)
throws IOException{
Reader fr=null;
try {
fr = new InputStreamReader(is);
while (true) {
readEntity(d, fr);
}
} catch (EOF e) { /** End of file encountered */}
if (fr != null) { fr.close(); }
validateConnections(d);
return d;
}
/**
* readEntity - reads an entity form the stream into the EntityData.
*
* @param data EntityData
* @param fr FileReader
*/
private static void readEntity(EntityData data, Reader r) throws IOException, EOF{
StringBuffer nameb=new StringBuffer();
int ch;
while((ch=r.read())!='{' && ch!=-1) nameb.append((char)ch);
if(ch==-1)throw new EOF();
String name=nameb.toString().trim();
if(nameb.equals("_SAVED_TIME")) { data.saveTime=readTimeFromStream(r); return; }
Entity e=data.findEntityExact(name);
if(e==null){
e= data.addNewEntity(name);
}
try{
while (true) readSection(e,data,r);
}catch(EOE ex){}
}
private static long readTimeFromStream(Reader r) throws IOException, EOF{
int ch; StringBuffer d=new StringBuffer();
while (!Character.isWhitespace((char)(ch=r.read()))) d.append(ch);
if(ch==-1) throw new EOF();
return Long.parseLong(d.toString());
}
/**
* readSection -reads a list of causes, effects, synonyms etc. from an entity
*
* @param e Entity
* @param data EntityData
*/
private static void readSection(Entity e, EntityData data, Reader r) throws EOE, IOException{
StringBuffer nameb=new StringBuffer();
int ch;
while((ch=r.read())!='{' && ch!='}' && ch!=-1) nameb.append((char)ch);
if(ch=='}')throw new EOE();
if(ch==-1)throw new EOF();
String name=nameb.toString().trim();
if(name.equals("Causes"))readListTillCloseBracket(e,Entity.CAUSE,data,r,true);
if(name.equals("Effects"))readListTillCloseBracket(e,Entity.EFFECT,data,r,true);
if(name.equals("Parents"))readListTillCloseBracket(e,Entity.PARENT,data,r,true);
if(name.equals("Children"))readListTillCloseBracket(e,Entity.CHILD,data,r,true);
if(name.equals("Synonyms"))readStringListTillCloseBracket(e.synonyms,data,r);
if(name.equals("Treats"))readListTillCloseBracket(e,Entity.TREATS, data,r,true);
if(name.equals("Treatments"))readListTillCloseBracket(e,Entity.TREATMENTS, data,r,true);
if(name.equals("Description")){
StringBuffer desc=new StringBuffer();
while((ch=r.read())!='}' && ch!=-1) desc.append((char)ch);
if(ch==-1)throw new EOF();
String d=desc.toString().trim();
if(d.startsWith("\""))d=d.substring(1,d.length()-1);
mergeDescriptions(e,d);
}
}
/**
* If false, then the stream readers will only add the connections in
* one direction, for each entity. This means it is possible to have
* connections that only go one way (which is of course illegal),
* so caution must be used that the file is valid. On the other hand
* The order of the items is well specified by the file- the order will
* be lost if two-directional adding is enabled by setting the value to
* 'true'.
*/
static final boolean ENSURE_VALIIDTY_AT_EXPENSE_OF_ORDER=false;
/**
* Scans a stream 'r' until the next }
* Takes a list of comma-delimited values, and stores them as elements
* in v, converting them into entities if instructed.
*/
private static void readListTillCloseBracket(Entity from,int relation, EntityData data,Reader r, boolean convertToEntity) throws IOException, EOF{
StringBuffer s=new StringBuffer();
int ch;
while((ch=r.read())!='}'){
if(ch==-1)throw new EOF();
if(ch==','){
storeEntity(from, s, relation, data,convertToEntity);
}else {
if (ch == '`') ch = ',';
s.append( (char) ch);
}
}storeEntity(from, s,relation,data,convertToEntity);
}
/** scan the stream for comma delimited strings, into vector v. */
private static void readStringListTillCloseBracket(Vector v, EntityData d, Reader r)
throws IOException, EOF{
StringBuffer s=new StringBuffer();
int ch;
while((ch=r.read())!='}'){
if(ch==-1)throw new EOF();
if(ch==','){
if(!v.contains(s.toString())) {v.addElement(s.toString().trim());}
s.setLength(0);
}else {
if (ch == '`') ch = ',';
s.append( (char) ch);
}
}
if(!v.contains(s.toString())) { v.addElement(s.toString().trim()); }
s.setLength(0);
}
/**
* Called when an item 's' in a list has been read. This adds the item to
* vector v, converting to entities if instructed.
*/
private static void storeEntity(Entity from, StringBuffer s,int relation,EntityData d,boolean convertToEntity)
throws IOException{
String n = s.toString().trim();
Vector v=from.listOf(relation);
if(convertToEntity){
// Parse probabililty
double p=Double.NaN;
if(n.endsWith("%")){
int i=n.length()-2;
while(!Character.isWhitespace(n.charAt(i))) i=i-1;
try{
p=Double.parseDouble(n.substring(i+1,n.length()-1));
}catch(NumberFormatException e){ throw new IOException(
"Illegal percentage in "+from.name+": "+n);
}
n=n.substring(0,i);
}
// Already exists?
Entity e = d.findEntityExact(n);
if(e==null){
e=d.addNewEntity(n);
v.addElement(e);
if(ENSURE_VALIIDTY_AT_EXPENSE_OF_ORDER)e.listOf(Entity.inverseOf(relation)).addElement(from);
}else{
if(!v.contains(e)) {
v.addElement(e);
if(ENSURE_VALIIDTY_AT_EXPENSE_OF_ORDER)e.listOf(Entity.inverseOf(relation)).addElement(from);
}
}
// Set probability if specified
if(!Double.isNaN(p)){
from.setProbOf(relation, v.indexOf(e), p);
}
s.setLength(0);
}else{
if(!v.contains(s.toString())) { v.addElement(s.toString().trim()); }
s.setLength(0);
}
}
static class EOF extends IllegalStateException{}
static class EOE extends IllegalStateException{}
private static void mergeDescriptions(Entity e, String d){
if(e.description.equals(d))return;
if(e.description.startsWith(d)) return;
if(d.startsWith(e.description)) {e.description=d;return;}
else e.description += '\n'+d;
}
/** Convert a Vector to a string as a delimited list - for serialisation! */
public static String getDelimitedNames(Vector v,String delimiter){
StringBuffer list = new StringBuffer();
for(int i = 0; i < v.size(); i++){
Object o = v.get(i);
String s=o.toString();
//Replace {} with (), replace " with '
s=s.replace('{','(').replace('}',')').replace(',','`');
list.append( s.toString() );
if(i < v.size()-1) list.append( delimiter );
}
return list.toString();
}
/** Get the list for a particular direction - for serialisation */
public static String getDelimitedEntities(Entity e, int relation, String delimiter){
StringBuffer list = new StringBuffer();
Vector v=e.listOf(relation);
double[]p = e.probsOf(relation);
for(int i = 0; i < v.size(); i++){
Object o = v.get(i);
String s=o.toString();
//Replace {} with (), replace " with '
s=s.replace('{','(').replace('}',')').replace(',','`');
list.append( s.toString() );
if(p!=null && p.length>i && !Double.isNaN(p[i])){
list.append(' '); list.append(p[i]); list.append('%');
}
if(i < v.size()-1) list.append( delimiter );
}
return list.toString();
}
/*
Entity readTextForm(InputStream p,Entity startFrom) throws IOException{
StreamTokenizer st=new StreamTokenizer(new InputStreamReader(p));
st.quoteChar('"');
st.eolIsSignificant(false);
String name=readUntil(st,"{");
getSpecificNamedEntity(name,startFrom);
return null;//incomplete
}
*/
/**
* read from st until the string c is returnec as a token. this is not
* included in the resuld.
*/
/*
String readUntil(StreamTokenizer st,String c) throws IOException{
StringBuffer s=new StringBuffer();
int tt;
do{
tt=st.nextToken();
if(tt==st.TT_WORD)
s.append(st.sval);
}while(!st.sval.equals(c));
return s.toString().trim();
}
*/
/**
* Blocking call that checks each entity in the set
* and ensures that every connection has a reciprocal.
* If not, one is created.
* Returns the number of extra connections created.
*/
public static int validateConnections(EntityData d) {
int errors=0;
for(Iterator i=d.getAllEntities().iterator();i.hasNext();) {
Entity e=(Entity)i.next();
for(int j=1;j<Entity.relationList.length;j++) {
int r=Entity.relationList[j];
int ri=Entity.inverseOf(r);
for(Iterator k=e.listOf(r).iterator();k.hasNext();) {
Entity f=(Entity)k.next();
if(!f.listOf(ri).contains(e)) {
f.listOf(ri).add(e);
errors++;
}
}
}
}
return errors;
}
/**
* Lists all causes of an entity
* Use: Vector v=getAllCauses(currentEntity, null);
*/
public static Vector getAllCauses(Entity entity, Vector except){
if(except!=null && except.contains(entity))return null;
if(except==null)except=new Vector();
Vector v=new Vector();
except.add(entity);
for(int i=0;i<entity.causes.size();i++){
Entity e=(Entity)entity.causes.get(i);
if(except==null || !except.contains(e)){
Vector ve=Entities.getAllCauses(e,v);
if(ve!=null){
if(ve.size()>0)v.addAll(ve);
else ve.add(e);
}
}
}
return v;
}
public static String getRelationNamesFromBits(int b) {
String s="";
for(int i=0;i<Entity.relationList.length;i++) {
if( (b & Entity.relationList[i]) > 0) s+=Entity.relationNameList[i];
}
if(s.endsWith("s")) s=s.substring(0,s.length()-1);
return s.toLowerCase();
}
public static Set getExtensiveListOf(int relations, Entity entity, int depth){ return getExtensiveListOf(relations, entity, depth, null);}
public static Set getExtensiveListOf(int relations, Entity entity, int depth, Set except){
Set v=except;
if(depth<0) return v;
if(v==null)v=new HashSet();
if(v.contains(entity)) return v;
v.add(entity);
for(int i=0;i<Entity.relationList.length;i++){
if((relations & Entity.relationList[i])>0){
Vector ve=entity.listOf(Entity.relationList[i]);
if(ve!=null) for(int j=0;j<ve.size();j++){
Entity e=(Entity)ve.get(j);
Set vf=Entities.getExtensiveListOf(relations, e, depth-1, v);
v.addAll(vf);
}
}
}
return v;
}
/**
* As above but don't go backwards - e.g. after going up to a parent,
* you can go sideways but not back down again.
* Don't include direct parents and children.
*/
public static Set getDirectionalListOf(int relations, Entity entity, int depth){
Set s=getDirectionalListOf(relations, entity, depth, null); // recursively get all directionally linked items
HashSet<Entity> rm=new HashSet<Entity>(); // now filter out any direct parents or children
for(Entity e:(Set<Entity>)s){
if(Entities.isChildOf(e, entity) || Entities.isChildOf(entity, e) || entity==e){
rm.add(e);
}
}
s.removeAll(rm);
return s;
}
/** This implements recursive getDirectionalListOf */
public static Set getDirectionalListOf(int relations, Entity entity, int depth, Set except){
Set v=except;
if(depth<0) return v;
boolean first=v==null;
if(first) v=new HashSet();
if(v.contains(entity)) return v;
v.add(entity);
for(int i=0;i<Entity.relationList.length;i++){
if((relations & Entity.relationList[i])>0){
Vector ve=entity.listOf(Entity.relationList[i]);
if(ve!=null) for(int j=0;j<ve.size();j++){
Entity e=(Entity)ve.get(j);
// now unset the bit corresponding to the opposeite to the direction we've just traversed
int newrelations = relations & ~ Entity.inverseOf( Entity.relationList[i] );
Set vf=Entities.getDirectionalListOf(newrelations, e, depth-1, v);
v.addAll(vf);
}
}
}
return v;
}
public static Vector getCauseHierarchy(Entity entity, Vector complete){
if(complete!=null && complete.contains(entity))return null;
if(complete==null)complete=new Vector();
Vector v=new Vector();
complete.add(entity);
for(int i=0;i<entity.causes.size();i++){
Entity e= (Entity)entity.causes.get(i);
if(complete==null || !complete.contains(e)){
Vector add=Entities.getCauseHierarchy(e, complete);
if(add!=null)v.add(add);
}
}
return v;
}
public static int numConnections(Entity e){
return e.causes.size()+e.effects.size()+e.parents.size()+e.children.size();
}
/**
* Recursively find whether the given queryItem is a child of 'parent'.
*/
public static boolean isChildOf(Entity queryItem, Entity parent){
/*
Vector p = queryItem.parents;
if(p.indexOf(parent) >= 0) return true;
for(int i=0;i<p.size();i++){
Entity nquery = (Entity)p.get(i);
if( isChildOfRecursive(nquery, parent, new Vector()) ) return true;
}
return false;
*/
// now delegate to recursive method which prevents cycling
return isChildOfRecursive(queryItem, parent, new Vector()) ;
}
public static boolean isChildOfRecursive(Entity queryItem, Entity parent, Vector avoid){
if(avoid.contains(queryItem)) return false;
avoid.add(queryItem);
Vector p = queryItem.parents;
if(p.indexOf(parent) >= 0) return true;
for(int i=0;i<p.size();i++){
Entity nquery = (Entity)p.get(i);
if( isChildOfRecursive(nquery, parent, avoid) ) return true;
}
return false;
}
public EntityData data;
/**
* Get an entity by name. This call is slow and blocking.
* @param any a node to start searching from.
*/
public static Entity getSpecificNamedEntity(String name, EntityData data)
throws EntityNotFoundException{
Vector v = data.findEntities(name, false, true);
if(v.size()==1) return (Entity)v.get(1);
else throw new EntityNotFoundException("Can't find entity "+name);
}
/**
* Traverse the parents, using only the first element in the list of
* parents on each level; and return the topmost entity
*/
public static Entity getUltimateParents(Entity e){
if(e.parents.size()==0)return null;
Entity p=(Entity)e.parents.elementAt(0);
while(p.parents.size()>0){
p=(Entity)p.parents.elementAt(0);
}
return p;
}
/**
* traverse along a particular direction, getting the top item on each list
* in that direction.
*/
public static Vector<Entity> getChainOfFirstItem(Entity e, int direction){
Vector<Entity> v=new Vector<Entity>();
v.add(e);
while(!e.listOf(direction).isEmpty()){
v.add(e=(Entity) e.listOf(direction).get(0)); // add to list and travel onwards!
}
return v;
}
/**
/**
* Find whether the 'putativeRelative' is a 'relation' of 'queryEntity'.
* If 'traverseParents' is true, and 'relation' is CAUSE or EFFECT, then
* this will return true if 'putativeRelative' is a 'relation' of any
* parent of any 'relation' of 'queryEntity'.
*/
/*
public static boolean isRelativeOf(Entity queryEntity, Entity putativeRelative,
int relation, boolean traverseParents, boolean traverseChildren,
int maxRecursionDepth){
if(maxRecursionDepth<=0)return false;
if(queryEntity==putativeRelative) return true;
Vector v=queryEntity.listOf(relation);
for(int i=0;i<v.size();i++){
if(v.get(i)==putativeRelative) return true; //is it directly related?
}
for(int i=0;i<v.size();i++){
Entity e=(Entity)v.get(i); //is it related to any of the relations?
if(isRelativeOf(e, putativeRelative, relation,traverseParents,
traverseChildren,maxRecursionDepth-1)) return true;
}
if(relation==Entity.CAUSE || relation==Entity.EFFECT) {
if(traverseParents){ //is it related to any of the parents?
for (int i = 0; i < queryEntity.parents.size(); i++) {
Entity t = (Entity) queryEntity.parents.get(i);
if (isRelativeOf(t, putativeRelative, relation, traverseParents,
traverseChildren,maxRecursionDepth-1))return true;
}
}
if(traverseChildren){ //is it related to any of the children?
for (int i = 0; i < queryEntity.children.size(); i++) {
Entity t = (Entity) queryEntity.children.get(i);
if (isRelativeOf(t, putativeRelative, relation, traverseParents,
traverseChildren,maxRecursionDepth-1))return true;
}
}
}
return false;
}
*/
/**
* Blocking call that determines whether an entity is related to a query
* entity.
* @param from Entity to start from - the entity to be queried
* @param to Entity to end at - the putative relative
* @param relations An integer representing which relations to follow, as a
* binary 'OR' of Entity.CAUSE, Entity.EFFECT etc.
* @param maxRecursionDepth maximum number of items in causal chain,
* including parents
* @param excludeItems List of items to exclude in the search. This is
* used in recursion to cumulate entities already visited. Can be null.
* @return whether or not the entity 'putativeRelative' can be reached
* from queryEntity by traversing the specified relations. If specified
* relations = 0, then this call returns false unless qureyEntity ==
* putativeRelative.
*/
public static boolean isRelatedTo(Entity from, Entity to,
int relations, int maxRecursionDepth, Vector excludeItems){
if(excludeItems==null) excludeItems=new Vector();
if(excludeItems.contains(from)) return false;
if(maxRecursionDepth<=0)return false;
if(from==to) { return true;}
//Vector v=queryEntity.listOf(relation);
for(int i=0;i<Entity.relationList.length;i++){
if((relations & Entity.relationList[i]) > 0){
Vector v=from.listOf(Entity.relationList[i]);
for(int j=0;j<v.size();j++){
Entity e=(Entity)v.get(j);
if(e==to) return true; //is it directly related?
Vector newExcludeItems=new Vector(excludeItems);
newExcludeItems.add(from); //don't go back to this element
if(isRelatedTo(e, to, relations, maxRecursionDepth-1,
newExcludeItems) ) return true;
}
}
}
return false;
}
/**
* Blocking call that determines the list of ways in which an entity
* is related to a query entity.
* @param from Entity to start from - the entity to be queried
* @param to Entity to end at - the putative relative
* @param relations An integer representing which relations to follow, as a
* binary 'OR' of Entity.CAUSE, Entity.EFFECT etc.
* @param maxRecursionDepth maximum number of items in causal chain,
* including parents
* @param excludeItems List of items to exclude in the search. This is
* used in recursion to cumulate entities already visited. Can be null.
* @param temporarilyAvoidDirections - a set of relations in which not
* to travel on the next step. This is used to avoid back-traversal on
* successive iterations.
* @return The vector of vectors, each of which is a list of entities
* traversed in order to go from 'from' to 'to'. Each item in the return
* value is a vector which begins with 'from' and ends with 'to', containing
* the relevant intermediate entities. If no routes are found, an empty
* vector is returned.
*/
public static Vector findRelationChains(Entity from, Entity to, int relations,
int maxRecursionDepth, Vector excludeItems,
Vector currentSolutions, Vector currentChain,
int temporarilyAvoidDirections){
if (excludeItems == null) excludeItems = new Vector();
if (currentChain == null) currentChain = new Vector();
if (currentSolutions == null) currentSolutions = new Vector();
if (excludeItems.contains(from))return currentSolutions;
if (maxRecursionDepth <= 0)return currentSolutions;
currentChain = (Vector)currentChain.clone();
currentChain.add(from);
if (from == to) { //found a complete chain!
currentSolutions.add(currentChain);
return currentSolutions; //add to the list of correct solutions
}
for(int i=0;i<Entity.relationList.length;i++){
int currentRelation = Entity.relationList[i];
if((currentRelation & temporarilyAvoidDirections) > 0) continue;
if ( (relations & currentRelation) > 0) {
Vector v = from.listOf(currentRelation);
for (int j = 0; j < v.size(); j++) {
Entity e = (Entity) v.get(j);
Vector newExcludeItems = new Vector(excludeItems);
//don't go back to this element
newExcludeItems.add(from);
findRelationChains(e, to, relations, maxRecursionDepth - 1,
newExcludeItems, currentSolutions, currentChain,
Entity.inverseOf(currentRelation));
//discard return value as currentSolutions always points to the
//same vector.
}
}
}
return currentSolutions;
}
public static Vector findRelationChainsSorted(Entity from, Entity to, int relations,
int maxRecursionDepth, Vector excludeItems,
Vector currentSolutions, Vector currentChain,
int temporarilyAvoidDirections){
Vector solutions = findRelationChains(from, to, relations, maxRecursionDepth,
excludeItems, currentSolutions, currentChain, temporarilyAvoidDirections);
// sort the chains by length - shorter chains are better!
Comparator sorter = new Comparator(){public int compare(Object o1, Object o2){
return ((Vector)o1).size() - ((Vector)o2).size();
}};
Collections.sort(solutions, sorter);
return solutions;
}
public static String toLowerCase(Entity e) {
String n=e.name;
boolean startword=true;
for(int j=0;j<n.length();j++) {
// if starting a word with a capital, and next char is lower case,
if(startword && (j<n.length()-1) && Character.isUpperCase( n.charAt(j) )
&& Character.isLowerCase( n.charAt(j+1) )){
// then decapitalise this letter.
n=n.substring(0,j)+Character.toLowerCase( n.charAt(j) )+n.substring(j+1);
}
startword=Character.isWhitespace( n.charAt(j) ); // next char is beginning of a word?
}
return n;
}
/** Convert a vector of connectivity into a text */
public static String chainText(Vector ch) {
Entity fr = (Entity)ch.get(0);
String out=fr.name;
for(int i=1;i<ch.size();i++) {
Entity to=(Entity)ch.get(i);
boolean found = false; // have we found the path from the 'fr' item to 'to'?
for(int j=0;j<Entity.relationList.length;j++) {
if( fr.listOf(Entity.relationList[j]).contains( to ) ) {
String tmp;
if(i==1) tmp=" is a "; else tmp=", which is a ";
if(Entity.inverseOf(Entity.relationList[j])!=Entity.CHILD)
out+=tmp+Entities.getRelationNamesFromBits( Entity.inverseOf(Entity.relationList[j]) )+" of "+to.name.toLowerCase();
else
out+=tmp+" "+to.name.toLowerCase();
found=true;
break;
}
}
if(!found) throw new IllegalArgumentException("Ill-formed chain, "+ch);
fr=to;
}
return out+".";
}
/** Convert a Vector to a colloquial text list
* (lower case with commas and 'and') */
public static String listToText(Vector v) {
StringBuffer sb=new StringBuffer();
for(int i=0;i<v.size();i++) {
Entity e=((Entity)v.get(i));
String n=Entities.toLowerCase(e);
sb.append(n);
if(i==v.size()-2) sb.append(" and ");
else if(i<v.size()-2) sb.append(", ");
}
if(sb.length()>0) return sb.toString();
else return null;
}
public static class AmbiguityException extends RuntimeException{
public AmbiguityException(String s){ super(s); }
public AmbiguityException(){ }
}
/**
* Group a list according to their standard ultimate parents.
* Returns a hashtable of sublists of entities.
*/
public static Hashtable<String,Object> groupedVectors(Collection<Entity> c, int i) {
Hashtable<String, Object> r = new Hashtable<String, Object>();
for(Entity e:c){
Entity pe = getUltimateParents(e); // parent entity?
String pn;
if(pe!=null){
pn = pe.name; // find parent name
}else{ // no parent? list separately
pn = "Other";
}
Vector<Entity> v = (Vector<Entity>)r.get(pn); // is there a list already for this parent?
if(v==null){ // create one if not
v=new Vector<Entity>();
r.put(pn,v); // and keep it in our table
}
v.add(e); // put item in the appropriate list
}
Hashtable modresult=(Hashtable) r.clone();
for(String k:r.keySet()){
Vector<Entity> l=(Vector<Entity>) r.get(k);
if(l.size()>MAX_LIST_SIZE) {
modresult.put(k,regroup(l));
}
}
return modresult;
}
static int MAX_LIST_SIZE = 5;
static Hashtable regroup(Vector<Entity> v){
int highestlevel=0;
int maxgrp = v.size();
// for each item, create hierarchy of parents
Vector<Vector<Entity>> hier=new Vector();
for(Entity e:v){
Vector h = getChainOfFirstItem(e, Entity.PARENT);
Collections.reverse(h);
hier.add(h);
}
Vector<Entity> uniques=null;
Vector<Vector<Entity>> grpitems=null ;
while(maxgrp>MAX_LIST_SIZE && highestlevel<4){
highestlevel++; // try out different levels of hierarchical organisation,
// starting with the most general (highest level)
uniques=new Vector();
Vector<Integer> grpsize = new Vector();
grpitems = new Vector();
for(Vector<Entity> h:hier){ // get the hierarchy for each entity
Entity top=h.get(Math.max(0,Math.min(highestlevel, h.size()-2))); // find the grouping at the current level
if(!uniques.contains(top)) { // create a new heading if not there
uniques.add(top);
Vector le=new Vector(); // list of entities
grpitems.add(le);
le.add(h.lastElement()); // add the entity
grpsize.add(1);
}else{ // otherwise increment count of entities under that heading
int ix=uniques.indexOf(top);
grpitems.get(ix).add(h.lastElement());
grpsize.set(ix, grpsize.get(ix)+1);
}
}
maxgrp = 0; // find the maximum group size, if we group at this level
for(int i:grpsize) if(maxgrp<i){ maxgrp=i; }
} // we have found a highestlevel that ensures all
// group sizes are <= MAX_LIST_SIZE.
Hashtable<String,Object> result = new Hashtable();
// can be String->Vector<Entity> or String->Entity
if(uniques==null){return null;} // the current grouping is the best! could be due to no parents, or
int MIN_SIZE=2;
for(Entity u:uniques){
Vector<Entity> vi = grpitems.get(uniques.indexOf(u));
if(vi.size()>=MIN_SIZE)
result.put(u.name, vi);
else{
for(Entity ei:vi) result.put(ei.name, ei);
}
}
return result;
}
}
public class EntityNotFoundException extends Exception{
EntityNotFoundException(String s){super(s);}
}
public class Question implements Serializable{
Vector<Stem> getCorrectStems(){
return correctStem;
}
Vector<Stem> getIncorrectStems(){
return errorStems;
}
Vector<Stem> correctStem=new Vector<Stem>();
Vector<Stem> errorStems=new Vector<Stem>();
/** The direction which the mode uses - Enitity.DIRECTIONS */
int direction;
/** the root entity that appears in the question head */
Entity root;
/** the actual text of the head */
String head;
/** the mode of questioning used to generate this question, from Logic.MODE_XXX */
int mode;
/** the difficulty category of the question */
int difficulty;
/** possible difficulty levels */
static final int DIF1=1, DIF2=2, DIF3=3, DIF4=4;
/** status of question */
int status;
/** possible status values */
static final int STAT_OK=3, STAT_CHECK=2, STAT_UNCHECKED=1;
Properties toProps(){
Properties p=new Properties();
for(int i=0;i<correctStem.size();i++) {
p.setProperty("Correct"+i, correctStem.get(i).entity.toString());
p.setProperty("CorrectReasoning"+i, correctStem.get(i).reasoning);
}
for(int i=0;i<errorStems.size();i++) {
p.setProperty("Incorrect"+i, errorStems.get(i).entity.toString());
p.setProperty("IncorrectReasoning"+i, errorStems.get(i).reasoning);
}
p.setProperty("Head", head);
p.setProperty("Root", root.toString());
p.setProperty("Direction", String.valueOf(direction));
p.setProperty("Mode", String.valueOf(mode));
p.setProperty("Difficulty", String.valueOf(difficulty));
return p;
}
void fromProps(Properties p, EntityData ed){
int i=0; Object o;
do {
o=p.getProperty("Correct"+i);
if(o!=null) {
Stem s=new Stem();
s.correct=true;
s.entity=ed.findEntityExact((String)o);
if(s.entity==null)
s.entity=new FakeEntity((String)o); // sometimes the stems are non-entities!
s.reasoning=p.getProperty("CorrectReasoning"+i);
correctStem.add(s);
}
i++;
}while(o!=null);
i=0;o=null;
do {
o=p.getProperty("Incorrect"+i);
if(o!=null) {
Stem s=new Stem();
s.correct=false;
s.entity=ed.findEntityExact((String)o);
if(s.entity==null)
s.entity=new FakeEntity((String)o); // deal with nonentities
s.reasoning=p.getProperty("IncorrectReasoning"+i);
errorStems.add(s);
}
i++;
} while(o!=null);
head= p.getProperty("Head");
root= ed.findEntityExact( p.getProperty("Root") );
direction = Integer.valueOf(p.getProperty("Direction"));
mode = Integer.valueOf(p.getProperty("Mode"));
difficulty = Integer.valueOf(p.getProperty("Difficulty"));
}
/*
public static Vector<Question> readText(BufferedReader r, EntityData ed) throws IOException {
Vector<Question> v=new Vector<Question>();
String s=r.readLine();
StringBuffer sb=new StringBuffer();
while(s!=null) {
if(s.trim().equals("{")) {
while(s!=null && !s.trim().equals("}")) {
s=r.readLine();
sb.append(s+"\n");
}
Question q=new Question();
Properties p= new Properties();
p.load( new ByteArrayInputStream( sb.toString().getBytes("ISO-8859-1") ) );
if(p.size()>0) {
q.fromProps(p, ed);
v.add(q);
}
}else {
s=r.readLine();
}
}
return v;
}
public static void writeText(Vector<Question> v, PrintWriter w) throws IOException {
Vector errors=new Vector();
for(int i=0;i<v.size();i++) {
w.println("{");
try {
v.get(i).toProps().store(w, "Question "+i);
}catch(Exception e) {
errors.add(v.get(i));
}finally {
w.println("}");
}
}
if(errors.size()>0) throw new IOException("Unable to write "+errors.size()+" questions.");
}
*/
public static class FakeEntity extends Entity{
FakeEntity(String s){ super(null,0); name=s; }
}
}
class Stem{
Entity entity;
boolean correct;
String reasoning;
}
public class Essay {
Entity e;
public Essay(Entity e){
this.e=e;
}
String text="";
public String createText() {
text = getText(e);
return text;
}
public static String getText(Entity e){
String text;
text=e.name;
if(e.synonyms.size()>0){
text+=", also known as";
for(int i=0;i<e.synonyms.size();i++){
text+=" "+e.synonyms.elementAt(i).toString()+",";
}
}
// Entity p = Entities.getUltimateParents(e);
// if(p!=null) text+=" is a "+p.name.toLowerCase()+". ";
String tmp="";
if(e.parents.size()==1) {
text += " is a "+((Entity)e.parents.get(0)).name.toLowerCase()+". ";
}else {
text += " is a " + Entities.listToText( e.parents ) + ". ";
}
if(e.children.size()>0) {
if (e.children.size()==1) {
// tmp="It is a generalisation of "+e.children.get(0)+". ";
}else {
tmp="Its subtypes include "+Entities.listToText(e.children);
}
}
String causelist = Entities.listToText(e.causes);
if(causelist!=null) text=text+"It can be caused by "+causelist+". ";
String effectlist = Entities.listToText(e.effects);
if(effectlist!=null) text=text+"It is known to cause "+effectlist+". ";
String rxlist = Entities.listToText(e.treats);
if(rxlist!=null) text=text+"It is used to treat "+rxlist+". ";
rxlist=Entities.listToText(e.treatments);
if(rxlist!=null) text=text+"It can be treated with "+rxlist+". ";
text=text+" "+e.description;
return text;
}
}
|
C++ | UTF-8 | 608 | 2.640625 | 3 | [
"MIT"
] | permissive | #include "matrix.h"
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/gtx/euler_angles.hpp>
#include <glm/gtx/transform.hpp>
namespace pathtrace::matrix {
glm::dmat4 euler_rotation(const glm::dvec3& rotation)
{
return glm::yawPitchRoll(-rotation.x,
rotation.y,
-rotation.z);
}
glm::dmat4 transform(const glm::dvec3& translation, const glm::dvec3& rotation, const glm::dvec3& scale)
{
return glm::translate(translation) * euler_rotation(rotation) * glm::scale(scale);
}
} // namespace pathtrace::matrix
|
C++ | UTF-8 | 1,095 | 2.9375 | 3 | [] | no_license | // Emilio Lopez
// Lab 10 part 6
// 4/21/2012
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
struct data
{
double number;
double miles;
double gallons;
double milespgallon;
};
int main()
{
data dt;
double num[5]={25,36,44,52,68};
double mi[5]={1450,3240,1769,2360,2115};
double gal[5]={62,136,67,105,67};
double mpg[5];
ofstream ofstr("Car_Report.dat");
if (ofstr.fail())
{
cout<<"The file could not be opened."<<endl;
}
ofstr<<"Car #"<<" Miles"<<" Gallons"<<" Miles per Gallon"<<endl<<
"-------------------------------------------------------------------"<<endl<<endl;
double total=0;
for (int i=0;i<5;i++)
{
dt.number=num[i];
dt.miles=mi[i];
dt.gallons=gal[i];
mpg[i]= dt.miles / dt.gallons;
ofstr<<num[i]<<" "<<mi[i]<<" "<<gal[i]<<" "<<mpg[i]<<endl<<endl;
total=total+mpg[i];
}
double avg= total/5;
ofstr<<" Average: "<<avg<<" mpg"<<endl;
ofstr.close();
cout<<"File complete"<<endl;
system ("pause");
return 0;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.