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
Markdown
UTF-8
1,340
2.703125
3
[ "MIT" ]
permissive
# DearInventoryRuby::SaleAdditionalCharge ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **description** | **String** | Name of Service Product referenced by this Line | **price** | **Float** | Decimal with up to 4 decimal places. Price per unit in Customer currency | **quantity** | **Float** | Decimal with up to 4 decimal places. Product or service quantity. Minimal value is 1. | **discount** | **Float** | Decimal with up to 2 decimal places. Discount. Value between 0 and 100. For free items discount is 100. Default value is 0 | [optional] **tax** | **Float** | Decimal with up to 4 decimal places. Tax. | **total** | **Float** | Decimal with up to 4 decimal places. Line Total. For validation | [optional] **tax_rule** | **String** | Line Tax Rule name. | **comment** | **Float** | Comment | [optional] ## Code Sample ```ruby require 'DearInventoryRuby' instance = DearInventoryRuby::SaleAdditionalCharge.new(description: nil, price: nil, quantity: nil, discount: nil, tax: nil, total: nil, tax_rule: nil, comment: nil) ```
Java
UTF-8
467
2.078125
2
[ "CC-BY-4.0" ]
permissive
package com.gps.itunes.media.player.ui.theme; /** * @author leogps * Created on 5/29/21 */ public class UITheme { private String name; private String className; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } }
Python
UTF-8
7,768
2.90625
3
[]
no_license
import numpy as np def debug_signal_handler(signal, frame): import pdb pdb.set_trace() import signal signal.signal(signal.SIGINT, debug_signal_handler) seq_size = 1000 def one_hot_encode_along_channel_axis(sequence): #theano dim ordering, uses row axis for one-hot to_return = np.zeros((len(sequence),4), dtype=np.int8) seq_to_one_hot_fill_in_array(zeros_array=to_return, sequence=sequence, one_hot_axis=1) return to_return def seq_to_one_hot_fill_in_array(zeros_array, sequence, one_hot_axis): assert one_hot_axis==0 or one_hot_axis==1 if (one_hot_axis==0): assert zeros_array.shape[1] == len(sequence) elif (one_hot_axis==1): assert zeros_array.shape[0] == len(sequence) #will mutate zeros_array for (i,char) in enumerate(sequence): if (char=="A" or char=="a"): char_idx = 0 elif (char=="C" or char=="c"): char_idx = 1 elif (char=="G" or char=="g"): char_idx = 2 elif (char=="T" or char=="t"): char_idx = 3 elif (char=="N" or char=="n"): continue #leave that pos as all 0's else: raise RuntimeError("Unsupported character: "+str(char)) if (one_hot_axis==0): zeros_array[char_idx,i] = 1 elif (one_hot_axis==1): zeros_array[i,char_idx] = 1 #https://www.biostars.org/p/710/ from itertools import groupby def fasta_iter(fasta_name): """ given a fasta file, yield tuples of (header, sequence) """ fh = open(fasta_name) # file handle # ditch the boolean (x[0]) and just keep the header or sequence since they alternate fa_iter = (x[1] for x in groupby(fh, lambda line: line[0] == ">")) for header in fa_iter: header = header.next()[1:].strip() # drop the ">" from the header seq = "".join(s.strip() for s in fa_iter.next()) # join all sequence lines to one yield header, seq # take input sequence name and return the onehot encoding def fasta_to_onehot(input_name): fasta_sequences = [] fasta = fasta_iter(input_name) onehot = [] for header, seq in fasta: fasta_sequences.append(seq) onehot_seq = one_hot_encode_along_channel_axis(seq) onehot.append(onehot_seq) return onehot # could be optimized, don't need onehot ''' def get_snp_scores(score_file, seq_file): hyp_scores = np.load(score_file) hyp_scores = hyp_scpres[:100] off = int((seq_size-1)/2) snp_hyp = hyp_scores[:, off] #print("snp_hyp shape=", snp_hyp.shape) #print("snp_hyp[:5]=\n", snp_hyp[:5]) onehot = fasta_to_onehot(seq_file) snp_onehot = [one_seq[off] for one_seq in onehot] #print("onehot done ", len(onehot), snp_onehot[0].shape) #print("onehot[:5]=\n", snp_onehot[:5]) snp_scores = [] for i in range(len(hyp_scores)): snp_score = snp_hyp[i] * snp_onehot[i] snp_scores.append(np.sum(snp_score)) print("snp_scores done ", len(snp_scores)) print(snp_scores[:5]) return snp_scores ''' def get_imp_scores(score_file, seq_file): hyp_scores = np.load(score_file) onehot = fasta_to_onehot(seq_file) #hyp_scores = hyp_scores[:10] #onehot = onehot[:10] #print("onehot done ", len(onehot)) #print("onehot[:5]=\n", onehot[:5]) imp_scores = [] for i in range(len(hyp_scores)): contrib_score = hyp_scores[i] * onehot[i] imp_scores.append(np.sum(contrib_score, axis=-1)) #print("imp_scores shape=", imp_scores[0].shape, len(imp_scores)) #print(imp_scores[:2][:5]) return imp_scores def get_snp_hyp_score_diff(score_file, seq_file): hyp_scores = np.load(score_file) off = int((seq_size-1)/2) snp_hyp = hyp_scores[:, off] print("snp_hyp shape=", snp_hyp.shape) #print("snp_hyp[:5]=\n", snp_hyp[:5]) onehot = fasta_to_onehot(seq_file) snp_onehot = [one_seq[off] for one_seq in onehot] print("onehot done ", len(onehot), snp_onehot[0].shape) #print("onehot[:2]=\n", snp_onehot[:2][:5]) diff_scores = [] for i in range(len(hyp_scores)): snp_score = snp_hyp[i] * snp_onehot[i] diff = snp_hyp[i] - snp_score max_diff = np.max(np.abs(diff), axis=-1) #print(diff.shape, max_diff.shape) diff_scores.append(max_diff) print("diff_scores done ", len(diff_scores)) #print(diff_scores[:5]) return diff_scores def max_sub_array_sum(a, size): max_so_far = 0 max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] if max_ending_here < 0: max_ending_here = 0 # Do not compare for all elements. Compare only # when max_ending_here > 0 elif (max_so_far < max_ending_here): max_so_far = max_ending_here return max_so_far def center_window_sum(a, size): off = int((seq_size-1)/2) win = 1 start = off - int(win/2) end = off + int(win/2) + 1 score = sum(a[start:end]) return score def calc_bis_score(a, size): #return max_sub_array_sum(a, size) return center_window_sum(a, size) snp_alleles = {} snp_diffs = {} def get_diff_scores(score_prefix, seq_prefix): snp_orig = get_imp_scores(score_prefix + "0", seq_prefix + "0") # (10k, 1000) print("snp_orig shape=", snp_orig[0].shape, len(snp_orig)) for i in range(3): snp_allele = get_imp_scores(score_prefix + str(i+1), seq_prefix + str(i+1)) # (10k, 1000) snp_diff = [o - s for o,s in zip(snp_orig, snp_allele)] # (10k, 1000) snp_alleles[i] = snp_allele snp_diffs [i] = snp_diff print("snp_diff " + str(i+1) + " shape=", snp_diff[0].shape) #, "\n" , snp_diff[:2][:5]) return snp_diffs bis_scores = {} def get_bis_scores(snp_diffs): for i in range(3): bis_scores[i] = [calc_bis_score(diff, len(diff)) for diff in snp_diffs[i]] # elementwise max among 3 lists max_bis_score = np.maximum.reduce([bis_scores[0], bis_scores[1], bis_scores[2]]) print("len of max_bis_score=", len(max_bis_score), "\n", max_bis_score[:5]) return max_bis_score from numpy import genfromtxt import math def get_snp_pvals(fname): snp_pvals = [] with open(fname) as in_fh: header = next(in_fh) line_num = 0 for line in in_fh: fields = line.split('\t') snp_chrom = fields[0] snp_pos = int(fields[1]) pval = float(fields[9]) snp_pvals.append(-math.log(pval, 10)) line_num += 1 return snp_pvals #diff_scores = get_snp_hyp_score_diff("scores/hyp_scores_task_0.npy") snp_diffs = get_diff_scores("scores/hyp_scores_task_0.npy", "scores/interpret.fa") bis_scores = get_bis_scores(snp_diffs) #snp_dir = "/Users/kat/kundajelab/tmp/bQTL/bQTL_all_SNPs/" snp_dir = "/home/ktian/kundajelab/tfnet/results/nandi/bQTL/analysis/bQTL_all_SNPs/" snp_file = "SPI1_10k.txt" snp_pvals = get_snp_pvals(snp_dir + snp_file) #print(len(snp_pvals)) #print(len(bis_scores)) #%matplotlib inline tf = 'SPI1' import matplotlib as mpl mpl.use("Agg") import matplotlib.pyplot as plt import numpy as np from scipy.stats import gaussian_kde #fig=plt.figure(figsize=(10, 8), dpi= 100) x=bis_scores y=snp_pvals xy = np.vstack([x,y]) z = gaussian_kde(xy)(xy) plt.scatter(x, y, 1, c=z, alpha=1, marker='o', label=".") plt.xlabel("BIS score ") plt.ylabel("SNP -log10(pval)") plt.colorbar(label='density (low to high)') #plt.legend(loc=2) plt.show() plt.savefig("deeplift_score_vs_pval.png") # https://stackoverflow.com/questions/20105364/how-can-i-make-a-scatter-plot-colored-by-density-in-matplotlib
Python
UTF-8
1,552
3.390625
3
[]
no_license
#Coder: Kbhkn #Kesirlerde 4 işlem yapma. class Kesir: def __init__(self,Pay,Payda): self.pay = Pay self.payda = Payda def __add__(self,DKesir): yenipay = self.pay*DKesir.payda + DKesir.pay*self.payda yenipayda = self.payda*DKesir.payda ortak = Kesir.ebob(yenipay,yenipayda) return Kesir(yenipay/ortak,yenipayda/ortak) def __sub__(self,DKesir): yenipay = self.pay*DKesir.payda - DKesir.pay*self.payda yenipayda = self.payda*DKesir.payda ortak = Kesir.ebob(yenipay,yenipayda) return Kesir(yenipay/ortak,yenipayda/ortak) def __mul__(self, DKesir): yenipay = self.pay*DKesir.pay yenipayda = self.payda*DKesir.payda ortak = Kesir.ebob(yenipay,yenipayda) return Kesir(yenipay/ortak,yenipayda/ortak) def __truediv__(self,DKesir): yenipay = self.pay*DKesir.payda yenipayda = self.payda*DKesir.pay ortak = Kesir.ebob(yenipay,yenipayda) return Kesir(yenipay/ortak,yenipayda/ortak) def __str__(self): return str(self.pay)+"/"+str(self.payda) def ebob(s1,s2): while s2 != 0: s1, s2 = s2, s1%s2 return s1 f1 = Kesir(1,4) f2 = Kesir(1,2) print(f1,"ve", f2, "Kesirlerinin Toplama işlemi sonucu: ",f1+f2) print(f1,"ve", f2, "Kesirlerinin Çıkarma işlemi sonucu: ",f1-f2) print(f1,"ve", f2, "Kesirlerinin Çarpma işlemi sonucu: ",f1*f2) print(f1,"ve", f2, "Kesirlerinin Bölme işlemi sonucu: ",f1/f2)
Python
UTF-8
1,425
3.28125
3
[]
no_license
#!/usr/bin/env python3 # The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, # is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit # numbers are permutations of one another. # There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this # property, but there is one other 4-digit increasing sequence. # What 12-digit number do you form by concatenating the three terms in this sequence? import sys sys.path.insert(0, "..") sys.path.insert(0, ".") from tools.utils import toList from tools.prime import prime from time import time def prop(n): if not prime(n): return False listN = toList(n) listN.sort() i = 1 while i <= 2: m = n + i*3330 if not prime(m): return False listN2 = toList(m) listN2.sort() if listN != listN2: return False i += 1 return True # ******************************************************************** startTime = time() start = 1001 end = 3340 pas = 2 n = start discardList = [1487] while n <= end: if prop(n) and n not in discardList: tmp = str(n) tmp += str(n+3330) tmp += str(n+2*3330) print(tmp) break n += pas print(time() - startTime)
JavaScript
UTF-8
3,547
2.828125
3
[]
no_license
/** * In OJET, we can easily create Web component and use a custom HTML element. * OJET actually allow you to organize the web component in a structure with * sub folder etc. In this example, we will do it inline version and register * the component manually, just so we can easily match to VueJS example for * comparision. * * NOTE That the OJET component properties can accept KO observable, but you must * access it using 'context.properties.<varName>', and not use a field variable. * As soon as you access it, it's no longer a observable! * * Compare to VueJS, 'searchQuery' seems to be pass in and access seamlessly. * The value seems to be observable inside the component without have to treat it * in special form other than declare as 'data'. * * OJET does not have a nice 'click' event binding, so we need to use KO version * here. */ define(['knockout', 'ojs/ojcomposite', 'ojs/ojknockout', 'ojs/ojinputtext' ], function (ko, Composite) { function DemoGridViewModel(context) { //console.log("DemoGridViewModel context: ", context); this.columns = context.properties.columns; this.data = context.properties.data; var sortOrders = {}; this.columns.forEach(function (key) { sortOrders[key] = ko.observable(1); }); this.sortKey = ko.observable(''); this.sortOrders = sortOrders; this.filteredData = ko.computed(function () { var filterKey_ = context.properties.filterKey; // input is an observable! var sortKey = this.sortKey(); var filterKey = filterKey_ && filterKey_.toLowerCase(); var order = this.sortOrders[sortKey] && this.sortOrders[sortKey]() || 1; var data = this.data; if (filterKey) { data = data.filter(function (row) { return Object.keys(row).some(function (key) { return String(row[key]).toLowerCase().indexOf(filterKey) > -1; }); }); } if (sortKey) { data = data.slice().sort(function (a, b) { a = a[sortKey]; b = b[sortKey]; return (a === b ? 0 : a > b ? 1 : -1) * order; }); } return data; }, this); this.capitalize = function (str) { return str.charAt(0).toUpperCase() + str.slice(1); }; this.sortBy = (key) => { // console.log("sortBy event", key); this.sortKey(key); this.sortOrders[key](this.sortOrders[key]() * -1); }; } function ExampleViewModel() { this.searchQuery = ko.observable(''); this.gridColumns = ['name', 'power']; this.gridData = [ {name: 'Chuck Norris', power: Infinity}, {name: 'Bruce Lee', power: 9000}, {name: 'Jackie Chan', power: 7000}, {name: 'Jet Li', power: 8000} ]; this.connected = () => { Composite.register("demo-grid", { viewModel: DemoGridViewModel, view: document.getElementById("grid-template").innerHTML, metadata: { properties: { data: {type: "array"}, columns: {type: "array"}, filterKey: {type: "string", writeback: true} } } }); }; } return ExampleViewModel; });
Java
UTF-8
1,460
2.59375
3
[]
no_license
package org.yaukie.special.rocketmq.event; import java.util.concurrent.atomic.AtomicInteger; import org.apache.rocketmq.client.producer.LocalTransactionState; import org.apache.rocketmq.client.producer.TransactionCheckListener; import org.apache.rocketmq.common.message.MessageExt; import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j; /** * 本地事务回查,, * 回查是由broker发起,生产者调用事务状态检查机制,通知broker当前消息的事务状态 * * @author yaukie * */ @Component @Slf4j public class TransactionCheckListenerImpl implements TransactionCheckListener { private AtomicInteger transactionIndex =new AtomicInteger(); @Override public LocalTransactionState checkLocalTransactionState(MessageExt msg) { Integer value = transactionIndex.getAndDecrement(); if(value==0){ throw new RuntimeException("发送的消息不能为空!"); }else if(value % 5==0){ log.info("TransactionCheckListenerImpl====事务回查状态为["+LocalTransactionState.COMMIT_MESSAGE+"]"); return LocalTransactionState.COMMIT_MESSAGE; }else if(value % 6==0 && value % 5 !=0){ log.info("TransactionCheckListenerImpl====事务回查状态为["+LocalTransactionState.ROLLBACK_MESSAGE+"]"); return LocalTransactionState.ROLLBACK_MESSAGE; } log.info("TransactionCheckListenerImpl====事务回查状态为["+LocalTransactionState.UNKNOW+"]"); return LocalTransactionState.UNKNOW; } }
Rust
UTF-8
782
3.09375
3
[ "MIT" ]
permissive
#![no_std] use core::ops::{Drop, FnOnce}; pub struct Finally<F> where F: FnOnce(), { f: Option<F>, } impl<F> Drop for Finally<F> where F: FnOnce(), { fn drop(&mut self) { if let Some(f) = self.f.take() { f() } } } pub fn finally<F>(f: F) -> Finally<F> where F: FnOnce(), { Finally { f: Some(f), } } #[cfg(test)] mod tests { use super::finally; use core::sync::atomic::{AtomicUsize, Ordering}; #[test] fn executed_on_drop() { let a = AtomicUsize::new(0); { let _f = finally(|| { a.fetch_add(1, Ordering::SeqCst); }); assert_eq!(0, a.load(Ordering::SeqCst)); } assert_eq!(1, a.load(Ordering::SeqCst)); } }
Java
UTF-8
694
3.390625
3
[]
no_license
/* * @author Jorge Alcaraz Bravo * Tema 6 Ejercicio 05 * */ public class Ejercicio05 { public static void main (String[] args) { int maximo=100; int minimo=199; int sumatorioParaMedia=0; int numeroRandom=0; for (int i=0; i<50; i++) { numeroRandom=(int)(Math.random()*100+100); System.out.print(numeroRandom + " "); sumatorioParaMedia += numeroRandom; if (numeroRandom < minimo) { minimo=numeroRandom; } if (numeroRandom > maximo) { maximo=numeroRandom; } } System.out.println("\nMáximo: " + maximo); System.out.println("Mínimo: " + minimo); System.out.println("Media: " + sumatorioParaMedia/50); } }
Java
UTF-8
1,294
2.71875
3
[ "MIT" ]
permissive
package <missing>; public class GlobalMembers { /* * mm.cpp * * Created on: 2012-11-18 * Author: ada */ public static void get_array(int[] a) { int n1; int n2; n1 = Integer.parseInt(ConsoleInput.readToWhiteSpace(true)); n2 = Integer.parseInt(ConsoleInput.readToWhiteSpace(true)); for (int i = 0 ; i < n1 ; i++) { a[i] = Integer.parseInt(ConsoleInput.readToWhiteSpace(true)); } for (int i = 0 ; i < n1 - 1 ; i++) //???? { for (int j = 0 ; j < n1 - 1 - i ; j++) { if (a[j] > a[j + 1]) { int tmp; tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp; } } } System.out.print(a[0]); for (int i = 1 ; i < n1 ; i++) { System.out.print(" "); System.out.print(a[i]); } for (int i = 0 ; i < n2 ; i++) { a[i] = Integer.parseInt(ConsoleInput.readToWhiteSpace(true)); } for (int i = 0 ; i < n2 - 1 ; i++) //???? { for (int j = 0 ; j < n2 - 1 - i ; j++) { if (a[j] > a[j + 1]) { int tmp; tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp; } } } for (int i = 0 ; i < n2 ; i++) { System.out.print(" "); System.out.print(a[i]); } return; } public static int[] a = new int[101]; public static int Main() { get_array(a); } }
JavaScript
UTF-8
721
2.859375
3
[]
no_license
function mostrar() { //tomo la edad var mes var mesDelAño = document.getElementById('mes').value; //alert (mesDelAño); switch (mesDelAño){ case "Febrero": alert("este mes no tiene mas d 28 dias "); break; case "Abril": case "Junio": case "Septiembre": case "Nobiembre": alert("este mes tiene 30 o màs dìas"); break; case "Enero": case "Marzo": case "Mayo": case "Julio": case "Agosto": case "Octubre": case "Diciembre": alert("este mes tiene 31 o màs dìas"); break; default: } }//FIN DE LA FUNCIÓN
C#
UTF-8
658
2.625
3
[]
no_license
using UnityEngine; using System.Collections; public class mouse : MonoBehaviour { public string cubeTag="button"; // Update is called once per frame void Update() { if (Input.GetMouseButtonDown(0)) { Ray ray = new Ray(); RaycastHit hit = new RaycastHit(); ray = Camera.main.ScreenPointToRay(Input.mousePosition); //マウスクリックした場所からRayを飛ばし、オブジェクトがあればtrue if (Physics.Raycast(ray.origin, ray.direction, out hit, Mathf.Infinity)) { if(hit.collider.gameObject.CompareTag(cubeTag)) { hit.collider.gameObject.GetComponent<button>().clicked(); } } } } }
Java
UTF-8
2,471
2.75
3
[ "Apache-2.0" ]
permissive
package com.clevercloud.biscuit.datalog.expressions; import biscuit.format.schema.Schema; import com.clevercloud.biscuit.datalog.Term; import com.clevercloud.biscuit.datalog.SymbolTable; import com.clevercloud.biscuit.error.Error; import io.vavr.control.Either; import io.vavr.control.Option; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.Map; import static io.vavr.API.Left; import static io.vavr.API.Right; public class Expression { private final ArrayList<Op> ops; public Expression(ArrayList<Op> ops) { this.ops = ops; } public ArrayList<Op> getOps() { return ops; } public Option<Term> evaluate(Map<Long, Term> variables, SymbolTable symbols) { /* Create a SymbolTable from original one to keep previous SymbolTable state after a rule or check execution, to avoid filling it up too much with concatenated strings (BinaryOp.Adds on String) */ SymbolTable tmpSymbols = new SymbolTable(symbols); Deque<Term> stack = new ArrayDeque<Term>(16); //Default value for(Op op: ops){ if(!op.evaluate(stack,variables, tmpSymbols)){ return Option.none(); } } if(stack.size() == 1){ return Option.some(stack.pop()); } else { return Option.none(); } } public Option<String> print(SymbolTable symbols) { Deque<String> stack = new ArrayDeque<>(); for (Op op : ops){ op.print(stack, symbols); } if(stack.size() == 1){ return Option.some(stack.remove()); } else { return Option.none(); } } public Schema.ExpressionV2 serialize() { Schema.ExpressionV2.Builder b = Schema.ExpressionV2.newBuilder(); for(Op op: this.ops) { b.addOps(op.serialize()); } return b.build(); } static public Either<Error.FormatError, Expression> deserializeV2(Schema.ExpressionV2 e) { ArrayList<Op> ops = new ArrayList<>(); for(Schema.Op op: e.getOpsList()) { Either<Error.FormatError, Op> res = Op.deserializeV2(op); if(res.isLeft()) { Error.FormatError err = res.getLeft(); return Left(err); } else { ops.add(res.get()); } } return Right(new Expression(ops)); } }
C++
UTF-8
2,963
2.59375
3
[]
no_license
#include "stdafx.h" #include "TileTerrain.h" #include "RectangleTexture.h" #include "ResourceManager.h" #include "Export_Function.h" CTileTerrain::CTileTerrain(eObjectType _eObjectType) : CGameObject(_eObjectType) , m_pVertexTexture(NULL) , m_pTileVertex(NULL) , m_iCountX(0) , m_iCountZ(0) { } CTileTerrain::~CTileTerrain(void) { Release(); } int CTileTerrain::Update(void) { return 0; } CTileTerrain* CTileTerrain::Create(eObjectType _eObjectType, const DWORD& _dwCountX, const DWORD& _dwCountZ, const DWORD& _dwInterval, const wstring& _wstrKey) { CTileTerrain* pTileTerrain = new CTileTerrain(_eObjectType); HRESULT hr = pTileTerrain->Initialize(_dwCountX, _dwCountZ, _dwInterval, _wstrKey); if FAILED(hr) SAFE_DELETE(pTileTerrain); return pTileTerrain; } HRESULT CTileTerrain::Initialize(const DWORD& _dwCountX, const DWORD& _dwCountZ, const DWORD& _dwInterval, const wstring& _wstrKey) { m_iCountX = _dwCountX; m_iCountZ = _dwCountZ; //m_pVertexColor = new VERTEX_COLOR[_dwCountX * _dwCountZ]; //ENGINE::GetResourceManager()->ReadVerticies(RESOURCE_TYPE_DYNAMIC, _wstrKey.c_str(), m_pVertexColor); m_pVertexTexture = new VERTEX_TEXTURE[_dwCountX * _dwCountZ]; ZeroMemory(m_pVertexTexture, sizeof(VERTEX_TEXTURE) * (_dwCountX * _dwCountZ)); int iIndex = 0; for(DWORD z = 0; z < _dwCountZ; ++z) { for(DWORD x = 0; x < _dwCountX; ++x) { iIndex = z * _dwCountX + x; SetD3DXVector3(&m_pVertexTexture[iIndex].vPos, float(x * _dwInterval), 0.f, float(z * _dwInterval)); } } iIndex = 0; for(DWORD z = 0; z < _dwCountZ - 1; ++z) { for(DWORD x = 0; x < _dwCountX - 1; ++x) { iIndex = z * _dwCountX + x; m_pTileVertex = new VERTEX_TEXTURE[4]; m_pTileVertex[0] = m_pVertexTexture[iIndex + _dwCountX]; SetD3DXVector2(&m_pTileVertex[0].vTex, 0.f, 0.f); m_pTileVertex[1] = m_pVertexTexture[iIndex + _dwCountX + 1]; SetD3DXVector2(&m_pTileVertex[1].vTex , 1.f, 0.f); m_pTileVertex[2] = m_pVertexTexture[iIndex + 1]; SetD3DXVector2(&m_pTileVertex[2].vTex , 1.f, 1.f); m_pTileVertex[3] = m_pVertexTexture[iIndex]; SetD3DXVector2(&m_pTileVertex[3].vTex, 0.f, 1.f); CTile* pTile = CTile::Create(OBJECT_TYPE_DYNAMIC, m_pTileVertex); m_vecTile.push_back(pTile); } } return S_OK; } HRESULT CTileTerrain::Initialize(void) { return S_OK; } void CTileTerrain::Render(void) { for(DWORD i = 0; i < m_vecTile.size(); ++i) { m_vecTile[i]->Render(); } } void CTileTerrain::Release(void) { vector<CTile*>::iterator iter = m_vecTile.begin(); for(iter; iter != m_vecTile.end(); ++iter) { delete *iter; } m_vecTile.clear(); if(m_pVertexTexture != NULL) { SAFE_DELETE_ARRAY(m_pVertexTexture); } //if(m_pTileVertex != NULL) //{ // SAFE_DELETE_ARRAY(m_pTileVertex); //} } void CTileTerrain::SetTileTexture(int _iTileIndex, int _iTextureIndex, eTextureRotation _eTextureRotation) { m_vecTile[_iTileIndex]->SetTileTexture(_iTextureIndex, _eTextureRotation); }
C#
UTF-8
2,017
3.3125
3
[]
no_license
using System; using System.Collections.Generic; using CoffeeApp; using FractionApp; namespace UtilitiesApp { class Program { static void Main (string[] args) { //float x = 5.6f; //float y = 3.4f; //Coffee oneCoffee = new Coffee(CoffeeVariation.Double); //Coffee secondCoffee = new Coffee(CoffeeVariation.Small); //ConsoleKey myKey = ConsoleKey.A; //ConsoleKey anotherKey = ConsoleKey.B; //Console.WriteLine("First object "+ oneCoffee + " second object " + secondCoffee); //Utilities<Coffee>.SwapItems(ref oneCoffee, ref secondCoffee); //Console.WriteLine("First object " + oneCoffee + " second object " + secondCoffee); /* * Fraction oneForTwo = new Fraction(1, 2); Fraction threeForFour = new Fraction(3, 4); Fraction sixForTwo = new Fraction(6, 2); List<int> list = new List<int>() { 1,1,1,1, 2, 3, 3, 3, 3, 3, 4, 4, 4 }; List<Fraction> fractions = new List<Fraction>() {oneForTwo, oneForTwo , oneForTwo , sixForTwo , sixForTwo, sixForTwo, sixForTwo, sixForTwo, sixForTwo, threeForFour }; foreach (var item in list) Console.Write(item+ " "); Console.WriteLine(); foreach (var item in Utilities.LongestSubsequenceInteger(list)) Console.Write(item+" "); Console.WriteLine(); foreach (var item in fractions) Console.Write(item + " "); Console.WriteLine(); foreach (var item in Utilities.LongestSubsequence<Fraction>(fractions)) Console.Write(item + " ");*/ double[] results = Utilities.QuadraticEquation(1, -2, 1); foreach (var item in results) { Console.WriteLine(item); } Console.WriteLine("\nPress a key to continue..."); Console.ReadKey(); } } }
Python
UTF-8
1,185
2.671875
3
[ "MIT" ]
permissive
import json from argparse import ArgumentParser import tweepy parser = ArgumentParser() parser.add_argument('friends_repo') parser.add_argument('-a', '--auth-filepath', help='Path to auth file', required=True) args = parser.parse_args() FRIENDS_IDS = args.friends_repo with open(args.auth_filepath) as f: AUTH = json.load(f) auth = tweepy.OAuthHandler(AUTH['consumer_token'], AUTH['consumer_secret']) auth.set_access_token(AUTH['access_token'], AUTH['access_token_secret']) api = tweepy.API(auth) with open(FRIENDS_IDS) as f: friends = json.load(f) iretrieve = 0 retrieved_user = False for friend_id, friend in friends.items(): if friend is None: try: friends[friend_id] = api.get_user(friend_id)._json retrieved_user = True iretrieve += 1 except: print('API retrieve failed, probably too many requests') break friends = {int(friend_id) : friends[friend_id] for friend_id in friends} with open(FRIENDS_IDS, 'w') as f: json.dump(friends, f, indent=2, sort_keys=True) if not retrieved_user: print('No retrieve user API call done') print('Retrieved {0} users'.format(iretrieve))
C#
UTF-8
1,144
2.734375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace Uninstaller { class UninstallManager { private UI outputObj; public UninstallManager() { outputObj = new ConsoleHandler(); } public UninstallManager(UI uiObject) { outputObj = uiObject; } public void BeginUninstall(string[] inputArgs) { outputObj.ShowStartingScreen(); Hashtable results = new Hashtable(); // Batch uninstall if run through the command line. if (inputArgs.Length > 0) { List<string> programs = inputArgs.ToList<string>(); results = Uninstaller.MultipleUninstall(programs); } else { string programName = outputObj.ShowGetProgramNameScreen(); results = Uninstaller.Uninstall(programName); } // Show results. outputObj.ShowUninstallResults(results); } } }
Python
UTF-8
4,704
2.921875
3
[ "MIT" ]
permissive
# coding=utf-8 """ A Diamond collector that collects memory usage of each process defined in it's config file by matching them with their executable filepath or the process name. This collector can also be used to collect memory usage for the Diamond process. Example config file ProcessMemoryCollector.conf ``` enabled=True unit=kB [process] [[postgres]] exe=^\/usr\/lib\/postgresql\/+d.+d\/bin\/postgres$ name=^postgres,^pg [[diamond]] selfmon=True ``` exe and name are both lists of comma-separated regexps. """ import os import re import diamond.collector import diamond.convertor try: import psutil psutil except ImportError: psutil = None def process_filter(proc, cfg): """ Decides whether a process matches with a given process descriptor :param proc: a psutil.Process instance :param cfg: the dictionary from processes that describes with the process group we're testing for :return: True if it matches :rtype: bool """ if cfg['selfmon'] and proc.pid == os.getpid(): return True for exe in cfg['exe']: try: if exe.search(proc.exe): return True except psutil.AccessDenied: break for name in cfg['name']: if name.search(proc.name): return True for cmdline in cfg['cmdline']: if cmdline.search(' '.join(proc.cmdline)): return True return False class ProcessMemoryCollector(diamond.collector.Collector): def get_default_config_help(self): config_help = super(ProcessMemoryCollector, self).get_default_config_help() config_help.update({ 'unit': 'The unit in which memory data is collected.', 'process': ("A subcategory of settings inside of which each " "collected process has it's configuration") }) return config_help def get_default_config(self): """ Default settings are: path: 'memory.process' unit: 'B' """ config = super(ProcessMemoryCollector, self).get_default_config() config.update({ 'path': 'memory.process', 'unit': 'B', 'process': '', }) return config def setup_config(self): """ prepare self.processes, which is a descriptor dictionary in processgroup --> { exe: [regex], name: [regex], cmdline: [regex], selfmon: [boolean], procs: [psutil.Process] } """ self.processes = {} for process, cfg in self.config['process'].items(): # first we build a dictionary with the process aliases and the # matching regexps proc = {'procs': []} for key in ('exe', 'name', 'cmdline'): proc[key] = cfg.get(key, []) if not isinstance(proc[key], list): proc[key] = [proc[key]] proc[key] = [re.compile(e) for e in proc[key]] proc['selfmon'] = cfg.get('selfmon', '').lower() == 'true' self.processes[process] = proc def filter_processes(self): """ Populates self.processes[processname]['procs'] with the corresponding list of psutil.Process instances """ for proc in psutil.process_iter(): # filter and divide the system processes amongst the different # process groups defined in the config file for procname, cfg in self.processes.items(): if process_filter(proc, cfg): cfg['procs'].append(proc) break def collect(self): """ Collects the RSS memory usage of each process defined under the `process` subsection of the config file """ self.setup_config() self.filter_processes() unit = self.config['unit'] for process, cfg in self.processes.items(): # finally publish the results for each process group metric_name = "%s.rss" % process metric_value = diamond.convertor.binary.convert( sum(p.get_memory_info().rss for p in cfg['procs']), oldUnit='byte', newUnit=unit) # Publish Metric self.publish(metric_name, metric_value) metric_name = "%s.vms" % process metric_value = diamond.convertor.binary.convert( sum(p.get_memory_info().vms for p in cfg['procs']), oldUnit='byte', newUnit=unit) # Publish Metric self.publish(metric_name, metric_value)
Java
UTF-8
5,275
2.15625
2
[]
no_license
package com.py.ysl.activity; import android.os.Bundle; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import com.py.ysl.R; import com.py.ysl.base.BaseActivity; import com.py.ysl.bean.RoundInfo; import com.py.ysl.view.myview.BarGraphView; import com.py.ysl.view.myview.ChartView; import com.py.ysl.view.myview.LineaView; import com.py.ysl.view.myview.MonthView; import com.py.ysl.view.myview.RoundView; import com.py.ysl.view.myview.WaveView; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import butterknife.BindView; import butterknife.ButterKnife; /** * @author lizhijun * 自定义view测试 */ public class ViewTestActivity extends BaseActivity{ @BindView(R.id.bar_view) BarGraphView bar_view; @BindView(R.id.cicyle) RoundView roundView; @BindView(R.id.text1) TextView text1; @BindView(R.id.chartview) ChartView chartview; @BindView(R.id.month) MonthView month; @BindView(R.id.wave_view) WaveView wave_view; @BindView(R.id.progressbar) ProgressBar progressbar; @BindView(R.id.lineavire) LineaView lineavire; private List<String>list; private List<RoundInfo>roundList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.my_view1); ButterKnife.bind(ViewTestActivity.this); list = new ArrayList<>(); roundList= new ArrayList<>(); list.add("2500"); list.add("6500"); list.add("500"); list.add("900"); list.add("2597"); list.add("2888"); list.add("2500"); list.add("6500"); list.add("500"); list.add("900"); list.add("2597"); list.add("2888"); RoundInfo info = new RoundInfo(); info.setCount("250"); info.setColor("#ffd862"); info.setName("衣服"); RoundInfo info2 = new RoundInfo(); info2.setCount("1250"); info2.setName("饮食"); info2.setColor("#71c6fe"); RoundInfo info3 = new RoundInfo(); info3.setCount("2250"); info3.setName("购物"); info3.setColor("#5f98fe"); RoundInfo info4 = new RoundInfo(); info4.setCount("10"); info4.setName("桑拿"); info4.setColor("#fe7614"); RoundInfo info5 = new RoundInfo(); info5.setCount("115"); info5.setName("淘宝"); info5.setColor("#a488fe"); RoundInfo info6 = new RoundInfo(); info6.setCount("350"); info6.setName("喝酒"); info6.setColor("#ff9693"); roundList.add(info); roundList.add(info2); roundList.add(info3); roundList.add(info4); roundList.add(info5); roundList.add(info6); // list.add("2500"); // list.add("9500"); // list.add("6500"); // list.add("4500"); // list.add("1500"); // list.add("2500"); roundView.setData(roundList,false); text1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { roundView.setData(roundList,true); } }); List<String>StrList = new ArrayList<>(); List<Integer>intList = new ArrayList<>(); //折线对应的数据 Map<String, Integer> value = new HashMap<>(); for (int i = 0; i < 12; i++) { StrList.add((i + 1) + "月"); } value.put( "1月", 600);//60--240 value.put( "2月", 500);//60--240 value.put( "3月", 800);//60--240 value.put( "4月", 900);//60--240 value.put( "5月", 400);//60--240 value.put( "6月", 900);//60--240 value.put( "7月", 1100);//60--240 value.put( "8月", 1300);//60--240 value.put( "9月", 1800);//60--240 value.put( "10月", 1400);//60--240 value.put( "11月", 1600);//60--240 value.put( "12月", 1000);//60--240 value.put( "1月", 200);//60--240 chartview.setValue(value,StrList,intList); bar_view.setValue(value,StrList,1800*3/2); bar_view.setCurrentMonth(11);//当没有满一年的时候需要用到 List<String>monList = new ArrayList<>(); for (int i=0;i<31;i++){ int val = (int)(Math.random()*100+1); monList.add(val+""); } month.setValue(monList,150,31); month.setCurrentDay(21); progressbar.setMax(100); progressbar.setProgress(50); lineavire.setVaule("#ffd862",10,8); } @Override protected void onDestroy() { super.onDestroy(); } private String getColor(String category){ HashMap<String,String>map = new HashMap<>(); map.put("交通","#5F9BFF"); map.put("衣服鞋包","#FF78E5"); map.put("日常生活","#FFD764"); map.put("医疗卫生","#FF2937"); map.put("通讯","#3EDFFF"); map.put("第三方支付","#FB804F"); map.put("还款","#C977FF"); map.put("其他","#94BCFF"); map.put("","#94BCFF"); map.put(null,"#94BCFF"); return map.get(category); } }
C#
UTF-8
7,275
2.53125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using Business_Logic; namespace AITMediaLibrary { public partial class AdminUserForm : Form { private readonly UserLogic _userLogic; private readonly MediaLogic _mediaLogic; private UserModel _selectedUser; public AdminUserForm() { InitializeComponent(); _userLogic = new UserLogic(); _mediaLogic = new MediaLogic(); } private void AdminForm_Load(object sender, EventArgs e) { try { loggedInUserLabel.Text = @"User: " + CurrentUser.UserName; loggedInLevelLabel.Text = @"Level: " + CurrentUser.UserLevel; RefreshUserList(); userLevelComboBox.DataSource = Enum.GetValues(typeof(AppEnum.UserLevel)); } catch (Exception) { userGridView.Text = @"Sorry, error loading the users!"; } } private void RefreshUserList() { List<UserModel> users = _userLogic.GetListOfUsers(); userGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; userGridView.DataSource = users; SelectedUserOnLoad(users); CleanTextBoxes(); } private void SelectedUserOnLoad(List<UserModel> users) { UserModel user = users[0]; _selectedUser = user; selectedUserLabel.Text = @"Selected User: " + user.UserName; } private void userGridView_CellClick(object sender, DataGridViewCellEventArgs e) { int row = e.RowIndex; if (row > -1) { List<UserModel> users = (List<UserModel>)userGridView.DataSource; _selectedUser = users.ElementAt(row); selectedUserLabel.Text = @"Selected User: " + _selectedUser.UserName; } } private void ArrowKeyUpDown_press(object sender, KeyEventArgs e) { int rowIndex = userGridView.CurrentCell.RowIndex; int colIndex = userGridView.CurrentCell.ColumnIndex; if (e.KeyValue == 40 && (userGridView.Rows.Count - 1) != rowIndex) { rowIndex++; DataGridViewCellEventArgs ev = new DataGridViewCellEventArgs(colIndex, rowIndex); userGridView_CellClick(sender, ev); } if (e.KeyValue == 38 && rowIndex != 0) { rowIndex--; DataGridViewCellEventArgs ev = new DataGridViewCellEventArgs(colIndex, rowIndex); userGridView_CellClick(sender, ev); } } private void refreshButton_Click(object sender, EventArgs e) { RefreshUserList(); } private void listAllButton_Click(object sender, EventArgs e) { RefreshUserList(); } private void updatePasswordButton_Click(object sender, EventArgs e) { if (_selectedUser != null) { int rowsAffected = _userLogic.UpdatePassword(newPasswordTextBox.Text, _selectedUser.UserID, CurrentUser.UserLevel); if (rowsAffected > 0) { //worked MessageBox.Show(_selectedUser.UserName + @" password updated!"); } else { //didnt MessageBox.Show(@"Something wrong! " + _selectedUser.UserName + @" password not updated!"); } RefreshUserList(); } } private bool HasBorrowedOrReserved() { ReserveModel reserve = _mediaLogic.GetReservedByUser(_selectedUser.UserID); List<MediaModel> borroweds = _mediaLogic.GetBorrowedByUser(_selectedUser.UserID); if (reserve != null || borroweds.Count > 0) return true; return false; } private void deleteSelectedUserButton_Click(object sender, EventArgs e) { if (_selectedUser != null && _selectedUser.UserName != CurrentUser.UserName) { if (HasBorrowedOrReserved()) { MessageBox.Show(@"Not possible to delete because this user has borrowed or reserved media"); } else { _userLogic.DeleteUserByUserID(_selectedUser.UserID, CurrentUser.UserLevel); _selectedUser = null; MessageBox.Show(@"Selected user successfully deleted!"); RefreshUserList(); } } else MessageBox.Show(@"Impossible to delete the logged in user!"); } private void addUserButton_Click(object sender, EventArgs e) { if (userNameTextBox.Text != "" && passwordTextBox.Text != "" && emailTextBox.Text != "") { AppEnum.UserLevel userLevel = (AppEnum.UserLevel)Enum.Parse(typeof(AppEnum.UserLevel), userLevelComboBox.Text); _userLogic.AddNewUser(userNameTextBox.Text, passwordTextBox.Text, (int)userLevel, emailTextBox.Text); MessageBox.Show(@"New user successfully created!"); RefreshUserList(); } else { MessageBox.Show(@"Missing information!"); } } private void changeToAdminMediaButton_Click(object sender, EventArgs e) { System.Threading.Thread t = new System.Threading.Thread(OpenAdminMedia); t.Start(); Close(); // closes the form } private static void OpenAdminMedia() { Application.Run(new AdminMediaForm()); } private void logoutButton_Click(object sender, EventArgs e) { CurrentUser.UserName = ""; CurrentUser.UserLevel = 0; System.Threading.Thread t = new System.Threading.Thread(OpenLoginForm); t.Start(); Close(); } private static void OpenLoginForm() { Application.Run(new Login()); } private void CleanTextBoxes(int num = 0) { if (num != 1) searchUserTextBox.Text = ""; if (num != 2) newPasswordTextBox.Text = ""; if (num != 3) { userNameTextBox.Text = ""; passwordTextBox.Text = ""; emailTextBox.Text = ""; } } private void searchUserButton_Click(object sender, EventArgs e) { try { List<UserModel> users = _userLogic.GetListOfUsersByUserName(searchUserTextBox.Text); userGridView.DataSource = users; SelectedUserOnLoad(users); CleanTextBoxes(); } catch (Exception) { MessageBox.Show(@"User(s) not found!"); RefreshUserList(); } } } }
C++
UTF-8
1,013
3.21875
3
[]
no_license
//Main idea: 단순 #include <iostream> #include <algorithm> #include <vector> using namespace std; vector<int> card; vector<int> q; int N, M; void input() { cin >> N; for (int i = 0; i < N; i++) { int tmp; cin >> tmp; card.push_back(tmp); } cin >> M; for (int i = 0; i < M; i++) { int tmp; cin >> tmp; q.push_back(tmp); } sort(card.begin(), card.end()); } bool bs(int start, int end, int& target) { while (start <= end) { int mid = (start + end) / 2; if (card[mid] > target) end = mid - 1; else if (card[mid] == target) return true; else start = mid + 1; } return false; } void run() { for (int i : q) { if (bs(0, N - 1, i)) cout << 1 << " "; else cout << 0 << " "; } } void NumCard() { input(); run(); } int main() { ios::sync_with_stdio(false); cin.tie(NULL); NumCard(); }
JavaScript
UTF-8
732
2.640625
3
[ "MIT" ]
permissive
const customer = require('../datasource/customer') class CustomerRepository { getCustomers() { var customers = []; customers.push(new customer({firstName: "Recipient", lastName: "One", emailAddress: "recipient1@example.com", favoriteColor: "Green"})); customers.push(new customer({firstName: "Recipient", lastName: "Two", emailAddress: "recipient2@example.com", favoriteColor: "Red"})); customers.push(new customer({firstName: "Recipient", lastName: "Three", emailAddress: "recipient3@example.com", favoriteColor: "Blue"})); customers.push(new customer({firstName: "Recipient", lastName: "Four", emailAddress: "recipient4@example.com", favoriteColor: "Orange"})); return customers; } } module.exports = CustomerRepository;
Markdown
UTF-8
2,666
3.640625
4
[]
no_license
### 基础语法 #### 标题 Markdown支持6种级别的标题,对应html标签h1~h6 ![title](assets/title.png) 以上标记效果如下: # h1 ## h2 ### h3 #### h4 ##### h5 ###### h6 除此之外,Markdown还支持另外一种形式标题展示形式,其类似于Setext标记语言的表现形式,使用下划线进行文本大小的空值 #### 段落及区块引用 需要记住的是,Markdown其实就是易于编写的普通文本,只不过加入了部分渲染文本的标签而已。其最终依然会转换为html标签,因此使用Markdown分段非常简单,前后至少保留一个空行即可。 而另外一个比较常见的需求就是,我们可能希望对某段文字进行强调处理。Markdown提供了一个特殊符号>用于段首进行强调,被强调的文字部分将会高亮显示 ![段标签](assets/段标签.png) 以上标记显示效果如下: > 这段文字将被高亮显示... #### 插入链接或图片 Markdown针对链接和图片处理也比较简单,可以使用下面的语法进行标记 [点击跳转至百度](https://www.baidu.com/) 注:引用图片和链接的唯一区别就是在最前方添加一个感叹号。 #### 列表 Markdown支持有序列表和无序列表两种形式: * 无序列表使用*或+或-标识 * 有序列表使用数字加.标识,例如:1. #### 使用列表的一些注意事项 如果在单一列表项中包含了多个段落,为了保证渲染正常,*与段落首字母必须保留四个空格 * 段落一 小段一 * ​ 段落二 ​ 小段二 * 段落一 > 区块标记一 #### 分割线 有时候,为了排版漂亮,可能会加入分割线。Markdown加入分割线非常简单,使用下面任意一种形式都可以 ![分割线](assets/分割线.png) *** --- #### 强调 有时候,我们希望对某一部分文字进行强调,使用*或_包裹即可。使用单一符号标记的效果是斜体,使用两个符号标记的效果是加粗 ![强调](assets/强调.png) *这里是斜体* _这里是斜体_ **这里是加粗** __这里是加粗__ #### 高级用法 ##### 插入代码块 Markdown在IT圈子里面比较流行的一个重要原因是,它能够轻松漂亮地插入代码。 方法是,使用反引号`进行包裹即可。如果是行内代码引用,使用单个反引号进行包裹 这是一段`var x = 3`行内代码 如果插入一整段代码,需要至少使用两个以上反引号进行包裹。 ###### 注:很多人不知道怎么输入反引号。在英文模式下,找到键盘最左侧esc键下面的第一个键点击即可。
Java
UTF-8
2,608
2.578125
3
[]
no_license
package com.daojia.toSql.util; import com.daojia.toSql.util.Constant.SqlConstant; /** * @Title: GeneratorUtil.java * @Description: * @Author:daojia * @CreateTime:2018年6月6日下午10:20:10 * @version v1.0 */ public class GeneratorUtil { public static String buildCreateTable(String tableName){ StringBuilder sb = new StringBuilder("").append(SqlConstant.CREATE_TABLE); sb.append(" ") .append(SqlConstant.FILED_WRAP).append(tableName).append(SqlConstant.FILED_WRAP) .append(" ") .append(SqlConstant.BRACKET_LEFT) .append(SqlConstant.NEXT_LINE); return sb.toString(); } public static String buildTailTable(){ StringBuilder sb = new StringBuilder(); sb.append(" PRIMARY KEY (`id`)") .append(SqlConstant.NEXT_LINE) .append(SqlConstant.BRACKET_RIGHT).append(" ") .append("ENGINE=InnoDB DEFAULT CHARSET=utf8"); return sb.toString(); } /** * @Description:`filed` * @Method: wrapField * @ReturnType String * @Author daojia * @CreateTime 2018年6月6日下午10:19:57 * @throws */ public static String wrapField(String filed){ return new StringBuilder(" ").append(SqlConstant.FILED_WRAP).append(filed).append(SqlConstant.FILED_WRAP).toString(); } /** * @Description:'commnet' * @Method: wrapComment * @ReturnType String * @Author daojia * @CreateTime 2018年6月6日下午10:22:17 * @throws */ public static String wrapComment(String comment){ return new StringBuilder(" ").append(SqlConstant.COMMENT).append(" ").append(SqlConstant.COMMENT_WRAP).append(comment).append(SqlConstant.COMMENT_WRAP).append(",").toString(); } /** * @Description: varchar(100) * @Method: wrapFiledType * @ReturnType String * @Author daojia * @CreateTime 2018年6月6日下午10:24:22 * @throws */ public static String wrapFiledType(String type, int length){ return new StringBuilder(" ").append(type).append(SqlConstant.BRACKET_LEFT).append(length).append(SqlConstant.BRACKET_RIGHT).toString(); } /** * @Description: varchar(100) * @Method: wrapDefaulValue * @ReturnType String * @Author daojia * @CreateTime 2018年6月6日下午10:24:22 * @throws */ public static String wrapDefaulValue(String dafaulValue){ return new StringBuilder(" ").append(SqlConstant.DEFAULT).append(" ").append(dafaulValue).toString(); } /** * @Description: varchar(100) * @Method: wrapNotNull * @ReturnType String * @Author daojia * @CreateTime 2018年6月6日下午10:24:22 * @throws */ public static String wrapNotNull(){ return new StringBuilder(" ").append(SqlConstant.NOT_NULL).toString(); } }
C++
UTF-8
1,488
3.46875
3
[]
no_license
#pragma once class SameGameBoard { public: /* Base Constructor */ SameGameBoard(void); /* Base Destructor */ ~SameGameBoard(void); /* Function to randomly setup the board Plan to have option for number of colors later */ void SetupBoard(void); /* Get color at location on board */ COLORREF GetSpaceColor(int row, int col); /* Accessor functions */ int GetWidth(void) const { return m_nWidth; } int GetHeight(void) const { return m_nHeight; } int GetColumns(void) const { return m_nColumns; } int GetRows(void) const { return m_nRows; } /* Delete board and free up memory */ void DeleteBoard(void); /* Is the game over? */ bool IsGameOver(void) const; /* Get number of remaining blocks */ int GetRemainingCount(void) const { return m_nRemaining; } /* Function to delete blocks */ int DeleteBlocks(int row, int col); private: /* Function to create board and allocate memory */ void CreateBoard(void); /* Direction enumeration (for deleting blocks) */ enum Direction { DIRECTION_UP, DIRECTION_DOWN, DIRECTION_LEFT, DIRECTION_RIGHT }; /* Recursive function for deleting blocks */ int DeleteAdjacentBlocks(int row, int col, int color, Direction direction); /* Fuction to compact board after block deletion */ void CompactBoard(void); /* 2D array pointer */ int** m_arrBoard; /* list of colors, 0 is background */ COLORREF m_arrColors[4]; /* Board size */ int m_nColumns; int m_nRows; int m_nHeight; int m_nWidth; int m_nRemaining; };
Shell
UTF-8
2,595
3.8125
4
[]
no_license
#!/bin/bash . /etc/os-release if [ -z "$PRETTY_NAME" ]; then echo "Cannot get host information" exit 1 fi echo $PRETTY_NAME if [ ! -e /usr/bin/rpmbuild ]; then echo "Cannot find rpmbuild" exit 1 fi # config SPECDIR=~chrism/jd SPEC=$SPECDIR/jd-kernel.spec # [ -z "$REPO" ] && REPO="git@github.com:mishuang2017/linux.git" [ -z "$REPO" ] && REPO="/home1/chrism/linux" [ -z "$BRANCH" ] && BRANCH=${1:-jd-1-mlx5} tmpbase="/home1/chrism/tmp" mkdir -p $tmpbase [ -z $TMPDIR ] && TMPDIR="$tmpbase/tmp$$-kernel" # check for free space free=`df $tmpbase | tail -1 | awk {'print $4'}` ((need=15*1024*1024)) if (( free < need )); then echo "Please check for free space in $tmpbase" exit 1 fi err=0 test $err != 0 && exit $err echo # run set -e echo "REPO: $REPO" echo "BRANCH: $BRANCH" echo "TMPDIR: $TMPDIR" sleep 1 rm -fr $TMPDIR mkdir -p $TMPDIR cd $TMPDIR # clone and prep CLONEDIR="linux-$BRANCH" git clone --depth=100 --branch=$BRANCH --single-branch $REPO $CLONEDIR cd $CLONEDIR # prep rpm build env RPMBUILDDIR=$TMPDIR/rpmbuild mkdir -p $RPMBUILDDIR/{BUILD,RPMS,SOURCES,SPECS,SRPMS} # create rpms export RPMOPTS="--define \"%_topdir $RPMBUILDDIR\" --define \"_tmppath %{_topdir}/tmp\"" export INSTALL_MOD_STRIP=1 export CONFIG_LOCALVERSION_AUTO=y rm -f .scmversion make kernelrelease rel=`scripts/setlocalversion .` # set scm version #scripts/setlocalversion --save-scmversion . #git add -f .scmversion #git commit -m "add scmversion $rel" kver=linux-`make kernelrelease` echo kver $kver #echo "set ver inside the module" #target="drivers/net/ethernet/mellanox/mlx5/core/main.c" #echo $rel $target #sed -i "s/jd_version = \"\(.*\)\";/jd_version = \"\\1$rel\";/" $target #git add drivers/net/ethernet/mellanox/mlx5/core/main.c #git commit -m "set jd version $rel" #kver=linux-3.10.0-693.21.1.el7 #echo kver $kver git archive --format=tar --prefix=$kver/ -o ${kver}.tar HEAD cp $SPEC $RPMBUILDDIR/SPECS cp $SPECDIR/* $RPMBUILDDIR/SOURCES cp ${kver}.tar $RPMBUILDDIR/SOURCES SPEC=$RPMBUILDDIR/SPECS/`basename $SPEC` rel=`echo $rel | cut -d- -f2` sed -i "s/pkgrelease 693.21.1.el7/pkgrelease $rel/" $SPEC echo pkgrelease $rel cmd="rpmbuild $RPMOPTS -ba $SPEC" echo $cmd eval $cmd # locate rpms RPMS=`find $RPMBUILDDIR/RPMS -iname "*.rpm"` SRPM=`find $RPMBUILDDIR/SRPMS -iname "*.rpm"` # copy to output folder REPODIR=$TMPDIR/repo mkdir -p $REPODIR cp $RPMS $REPODIR cp $SRPM $REPODIR echo "Latest commits" RPM=`ls -1tr $REPODIR/kernel-[0-9]*x86_64.rpm` BASE=`basename -s .rpm $RPM` LOG=$REPODIR/$BASE.log git log --oneline -60 > $LOG cat $LOG echo "REPO DIR $REPODIR"
TypeScript
UTF-8
2,546
2.609375
3
[ "MIT" ]
permissive
import { IResource } from '../../../../types/resources'; import { getResourcesSupportedByVersion } from '../../../utils/resources/resources-filter'; import content from '../../../utils/resources/resources.json'; import { createResourcesList, getAvailableMethods, getCurrentTree, getResourcePaths, getUrlFromLink, removeCounter } from './resource-explorer.utils'; const resource = JSON.parse(JSON.stringify(content)) as IResource; describe('Resource payload should', () => { it('have children', async () => { const resources: any = { ...content }; expect(resources.children.length).toBeGreaterThan(0); }); it('return children with version v1.0', async () => { const resources = getResourcesSupportedByVersion(resource.children, 'v1.0'); expect(resources.length).toBe(64); }); it('return links with version v1.0', async () => { const filtered = createResourcesList(resource.children, 'v1.0')[0]; expect(filtered.links.length).toBe(64); }); it('return specific tree', async () => { const version = 'v1.0'; const paths = ['/', 'appCatalogs', 'teamsApps']; const level = 2; const currentTree = getCurrentTree({ paths, level, resourceItems: resource.children, version }); expect(currentTree).not.toBeNull(); }); it('return available methods', async () => { const version = 'v1.0'; const filtered = createResourcesList(resource.children, version)[0]; const resourceLink = filtered.links[0]; const availableMethods = getAvailableMethods(resourceLink.labels, version); expect(availableMethods).not.toBeNull(); }); it('return a string without counters', async () => { const name = 'teamsApps (1)'; const withoutCounter = removeCounter(name); expect(withoutCounter).not.toBe(name); }); it('return a string without counters', async () => { const version = 'v1.0'; const paths = ['/', 'appCatalogs', 'teamsApps']; const level = 2; const currentTree = getCurrentTree({ paths, level, resourceItems: resource.children, version }); const link = currentTree.links[0]; const withoutCounter = getUrlFromLink(link); expect(withoutCounter).toBe('/appCatalogs/teamsApps'); }); it('return a flattened list of links', async () => { const version = 'v1.0'; const filtered = createResourcesList(resource.children, version)[0]; const item: any = filtered.links[0]; const paths = getResourcePaths(item, version); expect(paths.length).toBe(33); }); });
Ruby
UTF-8
1,977
3.40625
3
[]
no_license
require_relative "ingredient" require_relative "drink" require_relative "drink_maker" class Baristomatic INITIAL_QUANTITY = 10 def restok inventory.each { |_, item| item.quantity = INITIAL_QUANTITY } end def drink(drink_number) drinks[drink_number - 1] end def dispense(drink) drink_maker.dispense(drink) if drink end def inventory @inventory ||= { coffee: Ingredient.new("Coffee", INITIAL_QUANTITY, 0.75), decaf_coffee: Ingredient.new("Decaf Coffee", INITIAL_QUANTITY, 0.75), sugar: Ingredient.new("Sugar", INITIAL_QUANTITY, 0.25), cream: Ingredient.new("Cream", INITIAL_QUANTITY, 0.25), steamed_milk: Ingredient.new("Steamed Milk", INITIAL_QUANTITY, 0.35), foamed_milk: Ingredient.new("Foamed Milk", INITIAL_QUANTITY, 0.35), espresso: Ingredient.new("Espresso", INITIAL_QUANTITY, 1.10), cocoa: Ingredient.new("Cocoa", INITIAL_QUANTITY, 0.90), whipped_cream: Ingredient.new("Whipped Cream", INITIAL_QUANTITY, 1.00) }.sort.to_h end def drinks @drinks ||= [ Drink.new("Coffee", coffee: 3, sugar: 1, cream: 1), Drink.new("Decaf Coffe", decaf_coffee: 3, sugar: 1, cream: 1), Drink.new("Caffe Latte", espresso: 2, steamed_milk: 1), Drink.new("Caffe Americano", espresso: 3), Drink.new("Caffe Mocha", espresso: 1, cocoa: 1, steamed_milk: 1, whipped_cream: 1), Drink.new("Cappuccino", espresso: 2, steamed_milk: 1, foamed_milk: 1) ].sort_by(&:name) end def to_s inventory_string << drink_string end private def inventory_string "Inventory\n" << inventory.values.map do |item| "#{item},#{item.quantity}" end.join("\n") end def drink_string "\nMenu:\n" << drinks.map.with_index(1) do |drink, i| "#{i},#{"%s,$%0.2f,%s" % [drink, drink_maker.price(drink), drink_maker.available(drink)]}" end.join("\n") end def drink_maker @drink_maker ||= DrinkMaker.new(inventory) end end
Ruby
UTF-8
1,666
2.875
3
[ "MIT" ]
permissive
require "test_helper" require "talent_scout" class ChoiceTypeTest < Minitest::Test def test_cast_with_valid_value type = TalentScout::ChoiceType.new(MAPPING) MAPPING.each do |value, expected| assert_equal expected, type.cast(value.to_sym) assert_equal expected, type.cast(value.to_s) assert_equal expected, type.cast(expected) end end def test_cast_with_invalid_value type = TalentScout::ChoiceType.new(MAPPING) assert_nil type.cast("BAD") end def test_mapping_with_hash type = TalentScout::ChoiceType.new(MAPPING) assert_kind_of Hash, type.mapping assert_equal MAPPING.stringify_keys.to_a, type.mapping.to_a end def test_mapping_with_array type = TalentScout::ChoiceType.new(MAPPING.values) assert_kind_of Hash, type.mapping assert_equal MAPPING.values.index_by(&:to_s).to_a, type.mapping.to_a end def test_raises_on_non_string_non_symbol_keys assert_raises(ArgumentError) do TalentScout::ChoiceType.new({ 1 => 1 }) end end def test_dup_copies_mapping type1 = TalentScout::ChoiceType.new(MAPPING) type2 = type1.dup assert_equal type1.mapping, type2.mapping refute_same type1.mapping, type2.mapping end def test_attribute_assignment params = { choice1: MAPPING.first[0].to_s } expected = MAPPING.first[1] model = MyModel.new(params) assert_equal expected, model.choice1 end private MAPPING = { one: 1, two: true, three: "abc", four: Date.new(2004, 04, 04) } class MyModel include ActiveModel::Model include ActiveModel::Attributes attribute :choice1, TalentScout::ChoiceType.new(MAPPING) end end
Java
UTF-8
14,082
1.867188
2
[]
no_license
package gordenyou.huadian.activity; import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.SharedPreferences; import android.hardware.barcode.Scanner; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioTrack; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.support.annotation.Nullable; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Toast; import com.mobsandgeeks.saripaar.ValidationError; import com.mobsandgeeks.saripaar.Validator; import org.ksoap2.serialization.SoapObject; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import gordenyou.huadian.common.GlobalConstant; import gordenyou.huadian.common.WebServiceRequest; import gordenyou.huadian.unity.WebParams; import gordenyou.huadian.view.HeaderTitle; import tableLayout.TableAdapter; import tableLayout.TableLayout; /** * Created by Gordenyou on 2018/1/18. */ public abstract class BaseActivity extends AppCompatActivity implements Validator.ValidationListener { private Handler mHandler = new MainHandler(); private final int duration = 1; // seconds private final int sampleRate = 2000; private final int numSamples = duration * sampleRate; private final double[] sample = new double[numSamples]; private final byte[] generatedSnd = new byte[2 * numSamples]; private EditText editText; private TableLayout tableLayout; private String[] header; private LinearLayout linearLayout; private ArrayList<String> table_list = new ArrayList<>(); public String data; public ProgressDialog progressDialog; private static HeaderTitle headerTitle; //网络请求代码 public static int m; public SharedPreferences sharedPreferences; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); initViews(savedInstanceState); initValues(); LogicMethod(); } // public void ReshowTable(@Nullable Bundle savedInstanceState) { // if (savedInstanceState != null) { // Log.i(getBaseContext().toString(), "Save msg_list"); // ArrayList<String> msg_list = savedInstanceState.getStringArrayList("msg_list"); // firstRowAsTitle(msg_list); // } // } // // /** // * 横屏保存列表状态 // * // * @param outState // */ // public void onSaveInstanceState(Bundle outState , ArrayList<String> msg_list) { // outState.putStringArrayList("msg_list", msg_list); // super.onSaveInstanceState(outState); // } /** * 视图初始化 * @param savedInstanceState */ public abstract void initViews(Bundle savedInstanceState); /** * 逻辑初始化 */ public abstract void LogicMethod(); /** * 数据初始化 */ public abstract void initValues(); /** * 处理WebService返回数据。 * @param data 返回数据 * @param m 请求编号 */ public abstract void GetRequestResult(String data, int m); public void SetHeaderTitle(HeaderTitle headerTitle){ this.headerTitle = headerTitle; } public static String getHeadertitle(){ return headerTitle.getHeadertitle(); } @Override protected void onStart() { //赋值handle句柄 Scanner.m_handler = mHandler; //初始化扫描头 Scanner.InitSCA(); Thread thread = new Thread(run1); thread.start(); super.onStart(); } public void SetEdittext(EditText editText) { this.editText = editText; } public void SetTableLayout(TableLayout tableLayout) { this.tableLayout = tableLayout; } public void SetHeader(String[] header) { this.header = header; firstRowAsTitle(table_list); } public void SetLayout(LinearLayout linearLayout) { this.linearLayout = linearLayout; } public void SetValues(String key, String value){ SharedPreferences.Editor editor = getSharedPreferences("data_log", MODE_PRIVATE).edit(); editor.putString(key,value); editor.apply(); } public void SetValues(String key, Set<String> set){ SharedPreferences.Editor editor = getSharedPreferences("data_log", MODE_PRIVATE).edit(); editor.putStringSet(key,set); editor.apply(); } public String getValues(String key){ sharedPreferences = getSharedPreferences("data_log",MODE_PRIVATE); return sharedPreferences.getString(key, null); } public Set<String> getSetValues(String key){ sharedPreferences = getSharedPreferences("data_log",MODE_PRIVATE); return sharedPreferences.getStringSet(key, null); } public void addList(String value){ Set<String> changelist = getSetValues("changelist"); changelist = new HashSet<>(changelist); changelist.add(value); SetValues("changelist", changelist); } /** * 绘制表格 */ public void firstRowAsTitle(ArrayList<String> msg_list) { final ArrayList<String> list = msg_list; tableLayout.setAdapter(new TableAdapter() { @Override public int getColumnCount() { return header.length; } @Override public String[] getColumnContent(int position) { int rowCount = list.size() + 1; String contents[] = new String[rowCount]; for (int i = 0; i < rowCount; i++) { //设置标题栏 if (i == 0) { contents[i] = header[position]; } else { String[] temp = list.get(i - 1).split("○"); contents[i] = temp[position]; } } return contents; } }); } public void ClearData() { firstRowAsTitle(table_list); } /** * 表单校验成功 */ @Override public void onValidationSucceeded() { } /** * 表单校验失败提醒 * @param errors 错误单 */ @Override public void onValidationFailed(List<ValidationError> errors) { for (ValidationError error : errors) { View view = error.getView(); String message = error.getCollatedErrorMessage(this); // 显示上面注解中添加的错误提示信息 if (view instanceof EditText) { ((EditText) view).setError(message); } else { // 显示edittext外的提示,如:必须接受服务协议条款的CheckBox Toast.makeText(this, message, Toast.LENGTH_LONG).show(); } } } Runnable run1 = new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } View rootview = BaseActivity.this.getWindow().getDecorView(); View focus = rootview.findFocus(); if (focus != null) { // if (focus.getId() == R.id.sc_edittext) { // SetEdittext((EditText) focus); // } else { // SetEdittext(null); // } SetEdittext((EditText) focus); } } } }; /** * 扫描头常规事件 * * @param keyCode * @param event * @return */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.getRepeatCount() == 0) { if ((keyCode == 220) || (keyCode == 221)) { Scanner.Read(); Log.i("BASEACTIVITY", "Scanner Start"); } else if (keyCode == 4) { finish(); } } // Log.i("OOOOOOOO", keyCode + ""); return true; } public void StartScan() { Scanner.Read(); } public void WebHttpRequest(final int m) { Thread thread = new Thread(new Runnable() { @Override public void run() { SystemClock.sleep(200); WebServiceRequest webServiceRequest = new WebServiceRequest(); SoapObject soapobj = new SoapObject(GlobalConstant.NAMESPACE, "GetAppData"); soapobj.addProperty("subOperationFunction", WebParams.GetSubOperationFunction()); soapobj.addProperty("param1", WebParams.Getparam1()); soapobj.addProperty("param2", WebParams.Getparam2()); soapobj.addProperty("param3", WebParams.Getparam3()); soapobj.addProperty("param4", WebParams.Getparam4()); soapobj.addProperty("param5", WebParams.Getparam5()); soapobj.addProperty("param6", WebParams.Getparam6()); soapobj.addProperty("param7", WebParams.Getparam7()); soapobj.addProperty("param8", WebParams.Getparam8()); soapobj.addProperty("param9", WebParams.Getparam9()); soapobj.addProperty("param10", WebParams.Getparam10()); soapobj.addProperty("param11", WebParams.Getparam11()); soapobj.addProperty("param12", WebParams.Getparam12()); soapobj.addProperty("param13", WebParams.Getparam13()); soapobj.addProperty("param14", WebParams.Getparam14()); soapobj.addProperty("param15", WebParams.Getparam15()); webServiceRequest.WebServiceRequest("GetAppData", soapobj, m, handler); } }); thread.start(); } public void ErrorEvent(int m){} public void SuccessEvent(int m){} @SuppressLint("HandlerLeak") private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if(progressDialog != null){ progressDialog.dismiss(); } if (msg.what == -99) { ShowErrMsgDialog(msg.obj.toString().trim()); } else{ m= msg.what; Log.e("获取数据",msg.obj.toString().trim()); if(msg.obj.toString().trim().startsWith("Error:")){ ErrorEvent(m); ShowErrMsgDialog(msg.obj.toString().trim().substring(6)); } else if (msg.obj.toString().trim().startsWith("Err:")){ ErrorEvent(m); ShowErrMsgDialog(msg.obj.toString().trim().substring(4)); } else if(msg.obj.toString().trim().startsWith("Success:")){ SuccessEvent(m); ShowWarmMsgDialog(msg.obj.toString().trim().substring(8)); } else { if(!msg.obj.toString().trim().equals("")){ GetRequestResult(msg.obj.toString().trim(), m); } } } } }; public void ShowErrMsgDialog(String ErrorMsg){ new AlertDialog.Builder(BaseActivity.this).setTitle("错误信息") .setMessage(ErrorMsg).setPositiveButton("确定", null).show(); } public void ShowWarmMsgDialog(String ErrorMsg){ new AlertDialog.Builder(BaseActivity.this).setTitle("提示信息") .setMessage(ErrorMsg).setPositiveButton("确定", null).show(); } public void ScannerEvent(){ } private class MainHandler extends Handler { public void handleMessage(final Message msg) { switch (msg.what) { case Scanner.BARCODE_READ: { //显示读到的条码 if (editText != null) { editText.setText((String) msg.obj); Log.i("BaseActivity", "EditText"); ScannerEvent(); //播放声音 play(); } break; } case Scanner.BARCODE_NOREAD: { break; } default: break; } } } void genTone() { // fill out the array for (int i = 0; i < numSamples; ++i) { // HZ double freqOfTone = 1600; sample[i] = Math.sin(2 * Math.PI * i / (sampleRate / freqOfTone)); } // convert to 16 bit pcm sound array // assumes the sample buffer is normalised. int idx = 0; for (double dVal : sample) { short val = (short) (dVal * 32767); generatedSnd[idx++] = (byte) (val & 0x00ff); generatedSnd[idx++] = (byte) ((val & 0xff00) >>> 8); } } void playSound() { AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, numSamples, AudioTrack.MODE_STATIC); audioTrack.write(generatedSnd, 0, numSamples); audioTrack.play(); try { Thread.sleep(30); } catch (InterruptedException e) { e.printStackTrace(); } audioTrack.release(); } void play() { Thread thread = new Thread(new Runnable() { public void run() { genTone(); playSound(); } }); thread.start(); } }
Python
UTF-8
204
3.125
3
[]
no_license
import driver def letter(row, col): if ((row >=2 and row<=4) and (col>=3 and col<=6)): return 'M' else: return 'S' if __name__ == '__main__': driver.compare_patterns(letter)
Java
UTF-8
2,240
2.578125
3
[]
no_license
package YB101_5_VIEW_LOAD; import java.sql.*; import java.io.*; import java.util.*; public class ViewDAO implements IViewDAO { private static final String INSERT_STMT = "INSERT INTO viewinfo VALUES (?, ?, ?, ?, ?, ?,?, ?, ?, ?,?,?,?,?,?,?,?,?,?,?)"; private static final String INSERT_NEIGHBOR_STMT = "INSERT INTO viewneighbor VALUES (?, ?, ?)"; Connection conn = null; public void getConnection() throws SQLException { // String connUrl = "jdbc:sqlserver://localhost:1433;databaseName=Project"; // conn = DriverManager.getConnection(connUrl, "sa", "passw0rd"); String connUrl = "jdbc:mysql://10.120.28.19:3306/db01"; conn = DriverManager.getConnection(connUrl, "yb101", "iii"); } public int insertview(ViewVO view) throws SQLException { int updateCount = 0; PreparedStatement pstmt = conn.prepareStatement(INSERT_STMT); pstmt.setNString(1, view.getViewid()); pstmt.setNString(2, view.getViewname()); pstmt.setNString(3, view.getViewregion()); pstmt.setNString(4, view.getViewtype()); pstmt.setNString(5, view.getViewurl()); pstmt.setNString(6, view.getViewaddress()); pstmt.setNString(7, view.getViewtel()); pstmt.setNString(8, view.getViewstay()); pstmt.setNString(9, view.getViewintro()); pstmt.setNull(10,java.sql.Types.INTEGER); pstmt.setNull(11,java.sql.Types.INTEGER); pstmt.setNull(12,java.sql.Types.INTEGER); pstmt.setNull(13,java.sql.Types.INTEGER); pstmt.setNull(14,java.sql.Types.INTEGER); pstmt.setNull(15,java.sql.Types.INTEGER); pstmt.setNull(16,java.sql.Types.INTEGER); pstmt.setNull(17,java.sql.Types.INTEGER); pstmt.setInt(18,0); pstmt.setNull(19,java.sql.Types.FLOAT); pstmt.setNull(20,java.sql.Types.FLOAT); updateCount = pstmt.executeUpdate(); return updateCount; } public int insertneighbor(ViewNeighborVO nei) throws SQLException { int updateCount1 = 0; PreparedStatement pstmt1 = conn.prepareStatement(INSERT_NEIGHBOR_STMT); pstmt1.setNString(1, nei.getViewid()); pstmt1.setNString(2, nei.getNeighbortype()); pstmt1.setNString(3, nei.getNeighborname()); updateCount1 = pstmt1.executeUpdate(); return updateCount1; } public void closeConn() throws SQLException { if (conn != null) conn.close(); } } // end of class ActivityDAO
C++
UTF-8
1,207
2.796875
3
[]
no_license
#include "input/Controller.h" GibEngine::Input::Controller::Controller(int controllerId) : Controller(controllerId, false) { } GibEngine::Input::Controller::Controller(int controllerId, bool connected) : controllerId(controllerId), connected(connected), axisCount(0), buttonCount(0) { } void GibEngine::Input::Controller::Poll(float deltaTime) { const float* axes = glfwGetJoystickAxes(this->controllerId, &axisCount); const unsigned char* buttons = glfwGetJoystickButtons(this->controllerId, &buttonCount); //if (axes != nullptr) //{ // for (int i = 0; i < axisCount; i++) // { // float axisValue = axes[i]; // Logger::Instance->info("Axis {} Value: {}", i, axisValue); // } //} //if (buttons != nullptr) //{ // for (int i = 0; i < buttonCount; i++) // { // unsigned char buttonState = buttons[i]; // if (buttonState == GLFW_PRESS) // { // Logger::Instance->info("Button Press: {}", i); // } // } //} } bool GibEngine::Input::Controller::IsConnected() const { return this->connected; } int GibEngine::Input::Controller::GetControllerId() const { return this->controllerId; } void GibEngine::Input::Controller::SetConnected(bool value) { this->connected = value; }
Java
UTF-8
18,056
2.359375
2
[]
no_license
import java.util.Calendar; public class CrimeReport { boolean isPrecinctReport; boolean isBoroughReport; boolean isCityReport; /* * precinct set to -1 for borough-level and citywide report otherwise set to * actual precinct */ int precinct; /* * For Queens and Brooklyn, we consider the north and south boroughs * separately * * borough is null for citywide report but has a valid value for the * borough-level and precinct level reports */ String borough; Calendar startCal; Calendar endCal; // week to date stats for current year int numMurdersWTD; int numRapesWTD; int numRobberiesWTD; int numFelAssaultsWTD; int numBurglariesWTD; int numGrandLarceniesWTD; int numGLAWTD; int numTransitWTD; int numHousingWTD; int numPetitLarceniesWTD; int numMisdAssaultsWTD; int numMisdSexCrimesWTD; // int numShootingVicWTD; // int numShootingIncWTD; // week to date stats for previous year int numMurdersWTDPrevYear; int numRapesWTDPrevYear; int numRobberiesWTDPrevYear; int numFelAssaultsWTDPrevYear; int numBurglariesWTDPrevYear; int numGrandLarceniesWTDPrevYear; int numGLAWTDPrevYear; int numTransitWTDPrevYear; int numHousingWTDPrevYear; int numPetitLarceniesWTDPrevYear; int numMisdAssaultsWTDPrevYear; int numMisdSexCrimesWTDPrevYear; // int numShootingVicWTDPrevYear; // int numShootingIncWTDPrevYear; // 28 days stats for current year int numMurders28d; int numRapes28d; int numRobberies28d; int numFelAssaults28d; int numBurglaries28d; int numGrandLarcenies28d; int numGLA28d; int numTransit28d; int numHousing28d; int numPetitLarcenies28d; int numMisdAssaults28d; int numMisdSexCrimes28d; // int numShootingVic28d; // int numShootingInc28d; // 28 day stats for previous year int numMurders28dPrevYear; int numRapes28dPrevYear; int numRobberies28dPrevYear; int numFelAssaults28dPrevYear; int numBurglaries28dPrevYear; int numGrandLarcenies28dPrevYear; int numGLA28dPrevYear; int numTransit28dPrevYear; int numHousing28dPrevYear; int numPetitLarcenies28dPrevYear; int numMisdAssaults28dPrevYear; int numMisdSexCrimes28dPrevYear; // int numShootingVic28dPrevYear; // int numShootingInc28dPrevYear; // year to date stats for current year int numMurdersYTD; int numRapesYTD; int numRobberiesYTD; int numFelAssaultsYTD; int numBurglariesYTD; int numGrandLarceniesYTD; int numGLAYTD; int numTransitYTD; int numHousingYTD; int numPetitLarceniesYTD; int numMisdAssaultsYTD; int numMisdSexCrimesYTD; // int numShootingVicYTD; // int numShootingIncYTD; // year to date stats for previous year int numMurdersYTDPrevYear; int numRapesYTDPrevYear; int numRobberiesYTDPrevYear; int numFelAssaultsYTDPrevYear; int numBurglariesYTDPrevYear; int numGrandLarceniesYTDPrevYear; int numGLAYTDPrevYear; int numTransitYTDPrevYear; int numHousingYTDPrevYear; int numPetitLarceniesYTDPrevYear; int numMisdAssaultsYTDPrevYear; int numMisdSexCrimesYTDPrevYear; // int numShootingVicYTDPrevYear; // int numShootingIncYTDPrevYear; // murder percentage changes double numMurdersWTD1yChange; double numMurders28d1yChange; double numMurders1yChange; double numMurders2yChange; double numMurders5yChange; double numMurders21yChange; // rape percentage changes double numRapesWTD1yChange; double numRapes28d1yChange; double numRapes1yChange; double numRapes2yChange; double numRapes5yChange; double numRapes21yChange; // robberies percentage changes double numRobberiesWTD1yChange; double numRobberies28d1yChange; double numRobberies1yChange; double numRobberies2yChange; double numRobberies5yChange; double numRobberies21yChange; // felony assault percentage changes double numFelAssaultsWTD1yChange; double numFelAssaults28d1yChange; double numFelAssaults1yChange; double numFelAssaults2yChange; double numFelAssaults5yChange; double numFelAssaults21yChange; // 2-year, 5-year and 21-year percentage changes double numBurglariesWTD1yChange; double numBurglaries28d1yChange; double numBurglaries1yChange; double numBurglaries2yChange; double numBurglaries5yChange; double numBurglaries21yChange; // Gr Larceny percentage changes double numGrandLarceniesWTD1yChange; double numGrandLarcenies28d1yChange; double numGrandLarcenies1yChange; double numGrandLarcenies2yChange; double numGrandLarcenies5yChange; double numGrandLarcenies21yChange; // Auto Gr Larceny percentage changes double numGLAWTD1yChange; double numGLA28d1yChange; double numGLA1yChange; double numGLA2yChange; double numGLA5yChange; double numGLA21yChange; // Transit percentage changes double numTransitWTD1yChange; double numTransit28d1yChange; double numTransit1yChange; double numTransit2yChange; double numTransit5yChange; double numTransit21yChange; // 2-year, 5-year and 21-year percentage changes double numHousingWTD1yChange; double numHousing28d1yChange; double numHousing1yChange; double numHousing2yChange; double numHousing5yChange; double numHousing21yChange; // 2-year, 5-year and 21-year percentage changes double numPetitLarceniesWTD1yChange; double numPetitLarcenies28d1yChange; double numPetitLarcenies1yChange; double numPetitLarcenies2yChange; double numPetitLarcenies5yChange; double numPetitLarcenies21yChange; // 2-year, 5-year and 21-year percentage changes double numMisdAssaultsWTD1yChange; double numMisdAssaults28d1yChange; double numMisdAssaults1yChange; double numMisdAssaults2yChange; double numMisdAssaults5yChange; double numMisdAssaults21yChange; // 2-year, 5-year and 21-year percentage changes double numMisdSexCrimesWTD1yChange; double numMisdSexCrimes28d1yChange; double numMisdSexCrimes1yChange; double numMisdSexCrimes2yChange; double numMisdSexCrimes5yChange; double numMisdSexCrimes21yChange; public CrimeReport(boolean isPrecinctReport, boolean isBoroughReport, boolean isCityReport, int precinct, String borough, Calendar startCal, Calendar endCal, int numMurdersWTD, int numRapesWTD, int numRobberiesWTD, int numFelAssaultsWTD, int numBurglariesWTD, int numGrandLarceniesWTD, int numGLAWTD, int numTransitWTD, int numHousingWTD, int numPetitLarceniesWTD, int numMisdAssaultsWTD, int numMisdSexCrimesWTD, int numMurdersWTDPrevYear, int numRapesWTDPrevYear, int numRobberiesWTDPrevYear, int numFelAssaultsWTDPrevYear, int numBurglariesWTDPrevYear, int numGrandLarceniesWTDPrevYear, int numGLAWTDPrevYear, int numTransitWTDPrevYear, int numHousingWTDPrevYear, int numPetitLarceniesWTDPrevYear, int numMisdAssaultsWTDPrevYear, int numMisdSexCrimesWTDPrevYear, int numMurders28d, int numRapes28d, int numRobberies28d, int numFelAssaults28d, int numBurglaries28d, int numGrandLarcenies28d, int numGLA28d, int numTransit28d, int numHousing28d, int numPetitLarcenies28d, int numMisdAssaults28d, int numMisdSexCrimes28d, int numMurders28dPrevYear, int numRapes28dPrevYear, int numRobberies28dPrevYear, int numFelAssaults28dPrevYear, int numBurglaries28dPrevYear, int numGrandLarcenies28dPrevYear, int numGLA28dPrevYear, int numTransit28dPrevYear, int numHousing28dPrevYear, int numPetitLarcenies28dPrevYear, int numMisdAssaults28dPrevYear, int numMisdSexCrimes28dPrevYear, int numMurdersYTD, int numRapesYTD, int numRobberiesYTD, int numFelAssaultsYTD, int numBurglariesYTD, int numGrandLarceniesYTD, int numGLAYTD, int numTransitYTD, int numHousingYTD, int numPetitLarceniesYTD, int numMisdAssaultsYTD, int numMisdSexCrimesYTD, int numMurdersYTDPrevYear, int numRapesYTDPrevYear, int numRobberiesYTDPrevYear, int numFelAssaultsYTDPrevYear, int numBurglariesYTDPrevYear, int numGrandLarceniesYTDPrevYear, int numGLAYTDPrevYear, int numTransitYTDPrevYear, int numHousingYTDPrevYear, int numPetitLarceniesYTDPrevYear, int numMisdAssaultsYTDPrevYear, int numMisdSexCrimesYTDPrevYear, double numMurdersWTD1yChange, double numMurders28d1yChange, double numMurders1yChange, double numMurders2yChange, double numMurders5yChange, double numMurders21yChange, double numRapesWTD1yChange, double numRapes28d1yChange, double numRapes1yChange, double numRapes2yChange, double numRapes5yChange, double numRapes21yChange, double numRobberiesWTD1yChange, double numRobberies28d1yChange, double numRobberies1yChange, double numRobberies2yChange, double numRobberies5yChange, double numRobberies21yChange, double numFelAssaultsWTD1yChange, double numFelAssaults28d1yChange, double numFelAssaults1yChange, double numFelAssaults2yChange, double numFelAssaults5yChange, double numFelAssaults21yChange, double numBurglariesWTD1yChange, double numBurglaries28d1yChange, double numBurglaries1yChange, double numBurglaries2yChange, double numBurglaries5yChange, double numBurglaries21yChange, double numGrandLarceniesWTD1yChange, double numGrandLarcenies28d1yChange, double numGrandLarcenies1yChange, double numGrandLarcenies2yChange, double numGrandLarcenies5yChange, double numGrandLarcenies21yChange, double numGLAWTD1yChange, double numGLA28d1yChange, double numGLA1yChange, double numGLA2yChange, double numGLA5yChange, double numGLA21yChange, double numTransitWTD1yChange, double numTransit28d1yChange, double numTransit1yChange, double numTransit2yChange, double numTransit5yChange, double numTransit21yChange, double numHousingWTD1yChange, double numHousing28d1yChange, double numHousing1yChange, double numHousing2yChange, double numHousing5yChange, double numHousing21yChange, double numPetitLarceniesWTD1yChange, double numPetitLarcenies28d1yChange, double numPetitLarcenies1yChange, double numPetitLarcenies2yChange, double numPetitLarcenies5yChange, double numPetitLarcenies21yChange, double numMisdAssaultsWTD1yChange, double numMisdAssaults28d1yChange, double numMisdAssaults1yChange, double numMisdAssaults2yChange, double numMisdAssaults5yChange, double numMisdAssaults21yChange, double numMisdSexCrimesWTD1yChange, double numMisdSexCrimes28d1yChange, double numMisdSexCrimes1yChange, double numMisdSexCrimes2yChange, double numMisdSexCrimes5yChange, double numMisdSexCrimes21yChange) { super(); this.isPrecinctReport = isPrecinctReport; this.isBoroughReport = isBoroughReport; this.isCityReport = isCityReport; this.precinct = precinct; this.borough = borough; this.startCal = startCal; this.endCal = endCal; this.numMurdersWTD = numMurdersWTD; this.numRapesWTD = numRapesWTD; this.numRobberiesWTD = numRobberiesWTD; this.numFelAssaultsWTD = numFelAssaultsWTD; this.numBurglariesWTD = numBurglariesWTD; this.numGrandLarceniesWTD = numGrandLarceniesWTD; this.numGLAWTD = numGLAWTD; this.numTransitWTD = numTransitWTD; this.numHousingWTD = numHousingWTD; this.numPetitLarceniesWTD = numPetitLarceniesWTD; this.numMisdAssaultsWTD = numMisdAssaultsWTD; this.numMisdSexCrimesWTD = numMisdSexCrimesWTD; this.numMurdersWTDPrevYear = numMurdersWTDPrevYear; this.numRapesWTDPrevYear = numRapesWTDPrevYear; this.numRobberiesWTDPrevYear = numRobberiesWTDPrevYear; this.numFelAssaultsWTDPrevYear = numFelAssaultsWTDPrevYear; this.numBurglariesWTDPrevYear = numBurglariesWTDPrevYear; this.numGrandLarceniesWTDPrevYear = numGrandLarceniesWTDPrevYear; this.numGLAWTDPrevYear = numGLAWTDPrevYear; this.numTransitWTDPrevYear = numTransitWTDPrevYear; this.numHousingWTDPrevYear = numHousingWTDPrevYear; this.numPetitLarceniesWTDPrevYear = numPetitLarceniesWTDPrevYear; this.numMisdAssaultsWTDPrevYear = numMisdAssaultsWTDPrevYear; this.numMisdSexCrimesWTDPrevYear = numMisdSexCrimesWTDPrevYear; this.numMurders28d = numMurders28d; this.numRapes28d = numRapes28d; this.numRobberies28d = numRobberies28d; this.numFelAssaults28d = numFelAssaults28d; this.numBurglaries28d = numBurglaries28d; this.numGrandLarcenies28d = numGrandLarcenies28d; this.numGLA28d = numGLA28d; this.numTransit28d = numTransit28d; this.numHousing28d = numHousing28d; this.numPetitLarcenies28d = numPetitLarcenies28d; this.numMisdAssaults28d = numMisdAssaults28d; this.numMisdSexCrimes28d = numMisdSexCrimes28d; this.numMurders28dPrevYear = numMurders28dPrevYear; this.numRapes28dPrevYear = numRapes28dPrevYear; this.numRobberies28dPrevYear = numRobberies28dPrevYear; this.numFelAssaults28dPrevYear = numFelAssaults28dPrevYear; this.numBurglaries28dPrevYear = numBurglaries28dPrevYear; this.numGrandLarcenies28dPrevYear = numGrandLarcenies28dPrevYear; this.numGLA28dPrevYear = numGLA28dPrevYear; this.numTransit28dPrevYear = numTransit28dPrevYear; this.numHousing28dPrevYear = numHousing28dPrevYear; this.numPetitLarcenies28dPrevYear = numPetitLarcenies28dPrevYear; this.numMisdAssaults28dPrevYear = numMisdAssaults28dPrevYear; this.numMisdSexCrimes28dPrevYear = numMisdSexCrimes28dPrevYear; this.numMurdersYTD = numMurdersYTD; this.numRapesYTD = numRapesYTD; this.numRobberiesYTD = numRobberiesYTD; this.numFelAssaultsYTD = numFelAssaultsYTD; this.numBurglariesYTD = numBurglariesYTD; this.numGrandLarceniesYTD = numGrandLarceniesYTD; this.numGLAYTD = numGLAYTD; this.numTransitYTD = numTransitYTD; this.numHousingYTD = numHousingYTD; this.numPetitLarceniesYTD = numPetitLarceniesYTD; this.numMisdAssaultsYTD = numMisdAssaultsYTD; this.numMisdSexCrimesYTD = numMisdSexCrimesYTD; this.numMurdersYTDPrevYear = numMurdersYTDPrevYear; this.numRapesYTDPrevYear = numRapesYTDPrevYear; this.numRobberiesYTDPrevYear = numRobberiesYTDPrevYear; this.numFelAssaultsYTDPrevYear = numFelAssaultsYTDPrevYear; this.numBurglariesYTDPrevYear = numBurglariesYTDPrevYear; this.numGrandLarceniesYTDPrevYear = numGrandLarceniesYTDPrevYear; this.numGLAYTDPrevYear = numGLAYTDPrevYear; this.numTransitYTDPrevYear = numTransitYTDPrevYear; this.numHousingYTDPrevYear = numHousingYTDPrevYear; this.numPetitLarceniesYTDPrevYear = numPetitLarceniesYTDPrevYear; this.numMisdAssaultsYTDPrevYear = numMisdAssaultsYTDPrevYear; this.numMisdSexCrimesYTDPrevYear = numMisdSexCrimesYTDPrevYear; this.numMurdersWTD1yChange = numMurdersWTD1yChange; this.numMurders28d1yChange = numMurders28d1yChange; this.numMurders1yChange = numMurders1yChange; this.numMurders2yChange = numMurders2yChange; this.numMurders5yChange = numMurders5yChange; this.numMurders21yChange = numMurders21yChange; this.numRapesWTD1yChange = numRapesWTD1yChange; this.numRapes28d1yChange = numRapes28d1yChange; this.numRapes1yChange = numRapes1yChange; this.numRapes2yChange = numRapes2yChange; this.numRapes5yChange = numRapes5yChange; this.numRapes21yChange = numRapes21yChange; this.numRobberiesWTD1yChange = numRobberiesWTD1yChange; this.numRobberies28d1yChange = numRobberies28d1yChange; this.numRobberies1yChange = numRobberies1yChange; this.numRobberies2yChange = numRobberies2yChange; this.numRobberies5yChange = numRobberies5yChange; this.numRobberies21yChange = numRobberies21yChange; this.numFelAssaultsWTD1yChange = numFelAssaultsWTD1yChange; this.numFelAssaults28d1yChange = numFelAssaults28d1yChange; this.numFelAssaults1yChange = numFelAssaults1yChange; this.numFelAssaults2yChange = numFelAssaults2yChange; this.numFelAssaults5yChange = numFelAssaults5yChange; this.numFelAssaults21yChange = numFelAssaults21yChange; this.numBurglariesWTD1yChange = numBurglariesWTD1yChange; this.numBurglaries28d1yChange = numBurglaries28d1yChange; this.numBurglaries1yChange = numBurglaries1yChange; this.numBurglaries2yChange = numBurglaries2yChange; this.numBurglaries5yChange = numBurglaries5yChange; this.numBurglaries21yChange = numBurglaries21yChange; this.numGrandLarceniesWTD1yChange = numGrandLarceniesWTD1yChange; this.numGrandLarcenies28d1yChange = numGrandLarcenies28d1yChange; this.numGrandLarcenies1yChange = numGrandLarcenies1yChange; this.numGrandLarcenies2yChange = numGrandLarcenies2yChange; this.numGrandLarcenies5yChange = numGrandLarcenies5yChange; this.numGrandLarcenies21yChange = numGrandLarcenies21yChange; this.numGLAWTD1yChange = numGLAWTD1yChange; this.numGLA28d1yChange = numGLA28d1yChange; this.numGLA1yChange = numGLA1yChange; this.numGLA2yChange = numGLA2yChange; this.numGLA5yChange = numGLA5yChange; this.numGLA21yChange = numGLA21yChange; this.numTransitWTD1yChange = numTransitWTD1yChange; this.numTransit28d1yChange = numTransit28d1yChange; this.numTransit1yChange = numTransit1yChange; this.numTransit2yChange = numTransit2yChange; this.numTransit5yChange = numTransit5yChange; this.numTransit21yChange = numTransit21yChange; this.numHousingWTD1yChange = numHousingWTD1yChange; this.numHousing28d1yChange = numHousing28d1yChange; this.numHousing1yChange = numHousing1yChange; this.numHousing2yChange = numHousing2yChange; this.numHousing5yChange = numHousing5yChange; this.numHousing21yChange = numHousing21yChange; this.numPetitLarceniesWTD1yChange = numPetitLarceniesWTD1yChange; this.numPetitLarcenies28d1yChange = numPetitLarcenies28d1yChange; this.numPetitLarcenies1yChange = numPetitLarcenies1yChange; this.numPetitLarcenies2yChange = numPetitLarcenies2yChange; this.numPetitLarcenies5yChange = numPetitLarcenies5yChange; this.numPetitLarcenies21yChange = numPetitLarcenies21yChange; this.numMisdAssaultsWTD1yChange = numMisdAssaultsWTD1yChange; this.numMisdAssaults28d1yChange = numMisdAssaults28d1yChange; this.numMisdAssaults1yChange = numMisdAssaults1yChange; this.numMisdAssaults2yChange = numMisdAssaults2yChange; this.numMisdAssaults5yChange = numMisdAssaults5yChange; this.numMisdAssaults21yChange = numMisdAssaults21yChange; this.numMisdSexCrimesWTD1yChange = numMisdSexCrimesWTD1yChange; this.numMisdSexCrimes28d1yChange = numMisdSexCrimes28d1yChange; this.numMisdSexCrimes1yChange = numMisdSexCrimes1yChange; this.numMisdSexCrimes2yChange = numMisdSexCrimes2yChange; this.numMisdSexCrimes5yChange = numMisdSexCrimes5yChange; this.numMisdSexCrimes21yChange = numMisdSexCrimes21yChange; } }
C
UTF-8
1,198
3.046875
3
[]
no_license
#include <stdio.h> #define cls system("cls") void capt(int); void ini(float*, int); void jacobi(int o, float m[][o+1],float*, int); int main(){ int o; printf("Cuantas ecuaciones seran?");scanf("%d",&o); capt(o); return 0; } void capt(int o){ float m[o][o+1]; float rf[o]; int in, i, j; printf("Introduce las ecuaciones sin resultados:\n"); for(i=0;i<o;i++) for(j=0;j<o;j++) { printf("Captura el d[%d][%d]",i,j);scanf("%f", &m[i][j]); } printf("Introduce los resultados:\n"); for(i=0;i<o;i++) { printf("Captura el r[%d][%d]",i,o);scanf("%f", &m[i][o]); } printf("Cuantas interaciones quiere que pase? ");scanf("%d",&in); ini(rf,o); for(i=0;i<o;i++) for(j=0;j<=o;j++) { printf("%.1f\t",m[i][j]); if(j==o)printf("\n"); } for(i=1;i<=in;i++){ for(j=0;j<o;j++)seidel(o,m, rf,j); } for(i=0;i<o;i++)printf("x%d = %.4f\n",i+1,rf[i]); } void ini(float r[0], int o){ int i; for(i=0;i<=o;i++)r[i]=0; } void seidel(int o, float m[][o+1], float rf[0], int j){ int i; rf[j]=m[j][o]; for(i=0;i<o;i++){ if(i==j)continue; rf[j]=rf[j]+(-(m[j][i])*rf[i]); } rf[j]=rf[j]/m[j][j]; }
Java
UTF-8
255
1.648438
2
[]
no_license
package org.iqvis.nvolv3.mobile.bean; import org.codehaus.jackson.annotate.JsonIgnore; import org.iqvis.nvolv3.domain.EventConfiguration; public abstract class EventModifire { @JsonIgnore(false) abstract EventConfiguration getEventConfiguration(); }
Markdown
UTF-8
3,810
2.65625
3
[]
no_license
## N1DES ## 题目代码 ```python # -*- coding: utf-8 -*- import hashlib,base64 def f(a,b): digest = hashlib.sha256(a + b).digest() return digest[:8] def str_xor(a,b): return ''.join( chr(ord(a[i]) ^ ord(b[i])) for i in range(len(a))) def round_add(a, b): res = str_xor(f(a,b),f(b,a)) return res def permutate(table, block): return list(map(lambda x: block[x], table)) def str_permutate(table, block): t = map(lambda x: block[x], string_to_list(table)) return ''.join(chr(i) for i in t) def string_to_bits(data): data = [ord(c) for c in data] l = len(data) * 8 result = [0] * l pos = 0 for ch in data: for i in range(0,8): result[(pos<<3)+i] = (ch>>i) & 1 pos += 1 return result def string_to_list(data): a = [] a.extend(ord(i) for i in data) return a s_box = [55, 87, 54, 131, 139, 71, 3, 147, 34, 212, 231, 22, 170, 230, 154, 112, 81, 225, 218, 246, 227, 23, 8, 114, 65, 111, 189, 202, 136, 250, 179, 60, 177, 28, 166, 151, 50, 224, 25, 152, 221, 219, 242, 27, 115, 93, 208, 153, 35, 162, 30, 191, 105, 140, 129, 243, 245, 186, 132, 6, 41, 63, 254, 249, 165, 217, 49, 21, 210, 241, 159, 188, 44, 200, 37, 67, 144, 197, 205, 232, 211, 69, 80, 160, 252, 84, 76, 158, 173, 157, 204, 79, 62, 86, 237, 38, 171, 51, 17, 229, 148, 39, 43, 196, 103, 57, 142, 77, 155, 46, 45, 164, 91, 133, 16, 161, 141, 190, 47, 116, 26, 207, 61, 72, 137, 56, 104, 176, 2, 75, 123, 100, 236, 9, 180, 203, 183, 128, 13, 124, 89, 58, 83, 182, 201, 233, 175, 130, 122, 52, 138, 220, 29, 178, 213, 145, 113, 127, 174, 7, 167, 214, 146, 98, 48, 14, 194, 156, 42, 206, 110, 235, 238, 18, 4, 96, 228, 149, 0, 253, 101, 107, 119, 32, 117, 134, 92, 53, 193, 94, 90, 172, 143, 185, 244, 199, 109, 102, 15, 85, 11, 209, 251, 10, 163, 12, 120, 222, 255, 126, 226, 135, 40, 192, 150, 215, 240, 99, 1, 97, 64, 36, 248, 82, 234, 68, 70, 184, 125, 198, 31, 5, 73, 187, 118, 106, 239, 169, 74, 95, 24, 20, 223, 19, 33, 78, 216, 168, 108, 59, 88, 247, 195, 66, 181, 121] def generate(o): k = permutate(o,s_box) b = [] for i in range(0, len(k), 7): b.append(k[i:i+7] + [1]) c = [] for i in range(32): pos = 0 x = 0 for j in b[i]: x += (j<<pos) pos += 1 c.append((0x10001**x) % (0x7f)) return permutate(o,s_box) class N1ES_2: def __init__(self, key): if len(key) != 32 : raise Exception("key must be 32 bytes long") self.key = key self.gen_subkey() def gen_subkey(self): o = string_to_bits(self.key) k = [] for i in range(8): o = generate(o) k.extend(o) o = string_to_bits([chr(c) for c in o[0:32]]) self.Kn = [] for i in range(32): t = map(chr, k[i * 8: i * 8 + 8]) self.Kn.append(''.join(i for i in t)) return def encrypt(self, plaintext): if (len(plaintext) % 16 != 0 or isinstance(plaintext, bytes) == False): raise Exception("plaintext must be a multiple of 16 in length") res = '' for i in range(len(plaintext) / 16): block = plaintext[i * 16:(i + 1) * 16] L = block[:8] R = block[8:] for round_cnt in range(32): L, R = R, str_xor(round_add(R, self.Kn[round_cnt]),L) L, R = str_permutate(L,s_box) , str_permutate(R,s_box) L, R = R, L res += L + R return res key = "7056b257805ec2b8325795b0e6061f89" n1es = N1ES_2(key) cipher = n1es.encrypt(FLAG) print base64.b64encode(cipher) # TZPvbvJQ8l2T7G5NmrlDWPLoymq2See29B16+/xf+qk= ``` ## 题目Flag n1book{4_3AsY_F3istel_n3tw0rk~~} ## WriteUp 关注Nu1L Team公众号,回复7-crypto-wp-2获取WP
PHP
UTF-8
1,562
3.15625
3
[]
no_license
<?php $str = isset($_POST['myHTML']) ? $_POST['myHTML'] : ""; $res = htmlspecialchars($str); echo "your input is: ".$res; ?> <html> <head> <title> Exercice 1 </title> </head> <script> function HTMLElements(str) { let openingTags = str.match(/<\w+>/g) let closingTags = str.match(/(<\/\w+>)/g).reverse(); let strObj = { '<div>': '</div>', '<p>': '</p>', '<i>': '</i>', '<p>': '</p>', '<em>': '</em>', '<b>': '</b>', }; const max = Math.max(openingTags.length, closingTags.length); for (let i = 0; i < max; i++) { if (strObj[openingTags[i]] !== closingTags[i]) { return (openingTags[i] || closingTags[i]).replace(/<|>/g, ''); } } return true; } function demo(str) { const res = HTMLElements(str); console.log(str, '\t--> ', res); document.getElementById("text").innerHTML = res } function click(){ document.getElementById("b1").click(); } </script> <body onload="click()" style="text-align:center;" id="body"> <h1 style="color:blue;" id="h1"> HTML Checker </h1> <p id="first" style="font-size: 15px; font-weight: bold;" > </p> <button id="b1" hidden onclick="demo('<?php echo $res; ?>')"> click here </button> <p id="second" style="color:green; font-size: 20px; font-weight: bold;"> </p> <label id="text" ></label> </body> </html>
JavaScript
UTF-8
620
2.625
3
[]
no_license
aroCityApp.filter('unique',function(){ return function(collection, keyname) { //console.log('col --->' , collection , 'keyname--->',keyname); var output = [], keys = []; angular.forEach(collection, function(item) { //console.log('City --->' , item ,'Key Name--->' , keyname); //Bangalore[city] var key = item[keyname]; //Bangalore //console.log(key); if(keys.indexOf(key) === -1) { keys.push(key); output.push(item); } }); //console.log('filter ', output) return output; }; });
Java
UTF-8
357
3.265625
3
[]
no_license
public class SelectionSort { public void DoSelectionSort( int[] array ) { for( int i=0; i<array.length; i++ ) { int keyindex = i; for( int j=i+1; j<array.length; j++ ) { if( array[j] < array[keyindex] ) { keyindex = j; } } int swp = array[i]; array[i] = array[keyindex]; array[keyindex] = swp; } } }
Python
UTF-8
413
3.6875
4
[]
no_license
import numpy as np def end(): print() # 2.15.1 함수의 사용 def my_func1(): print("Hi!") my_func1() def my_func2(a, b): c=a+b return c print(my_func2(1, 5)) end() # 2.15.2 인수와 반환값 def my_func3(D): m = np.mean(D) s = np.std(D) return m, s data=np.random.randn(100) data_mean, data_std=my_func3(data) print("mean:{0:3.2f}, std:{1:3.2f}".format(data_mean, data_std))
Java
UTF-8
265
1.507813
2
[]
no_license
package com.action.repo; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.action.entity.Audit; @Repository public interface AuditRepo extends JpaRepository<Audit, Integer> { }
JavaScript
UTF-8
2,881
3.640625
4
[]
no_license
//Adiciona evento ao botão document.getElementById("button").addEventListener("click", //cria uma function para: function mudarPaleta(){ //pegar uma paleta de cor através do id de forma aleatória const pegaPaleta = document.getElementById('a'+`${Math.floor(Math.random() * 100 )}`); //armazenar o código Hexadecimal const hexCode = pegaPaleta.children[0].getElementsByTagName('span'); //exibir código Hexadecimal em forma de texto document.getElementById("main-text").innerText = hexCode[0].innerText; document.getElementById("head-text").innerText = hexCode[1].innerText; document.getElementById("side-text").innerText = hexCode[2].innerText; document.getElementById("foot-text").innerText = hexCode[3].innerText; //alterar o fundo da div main com a primeira cor da paleta document.getElementById("main").style = hexCode[0].parentElement.getAttribute('style'); //alterar o fundo da div header com a segunda cor da paleta document.getElementById("header").style = hexCode[1].parentElement.getAttribute('style'); //alterar o fundo da div side bar com a terceira cor da paleta document.getElementById("sidebar").style = hexCode[2].parentElement.getAttribute('style'); //alterar o fundo da div footer com a quarta cor da paleta document.getElementById("footer").style = hexCode[3].parentElement.getAttribute('style'); //console.log da funçao console.log(hexCode); }); //criar uma function para rotacionar as cores entre as áreas document.getElementById("rotate").addEventListener("click", function rodarCores(){ //armazenar estilos const mainBack = document.getElementById("footer").style.backgroundColor; const headBack = document.getElementById("main").style.backgroundColor const sideBack = document.getElementById("header").style.backgroundColor const footBack = document.getElementById("sidebar").style.backgroundColor //armazenar textos const mainText = document.getElementById("foot-text").innerText; const headText = document.getElementById("main-text").innerText; const sideText = document.getElementById("head-text").innerText; const footText = document.getElementById("side-text").innerText; //efetuar troca de textos document.getElementById("main-text").innerText = mainText; document.getElementById("head-text").innerText = headText; document.getElementById("side-text").innerText = sideText; document.getElementById("foot-text").innerText = footText; //efetuar troca do background document.getElementById("main").style.backgroundColor = mainBack; document.getElementById("header").style.backgroundColor =headBack; document.getElementById("sidebar").style.backgroundColor = sideBack; document.getElementById("footer").style.backgroundColor = footBack; // console.log(mainBack); });
Markdown
UTF-8
2,644
2.546875
3
[ "MIT" ]
permissive
--- title: About permalink: /about/ --- # Austin Apple Admins <img src="/assets/images/aaa.png" alt="Austin Apple Admins" style="width: 200px;align: center;" /> Our goal is simple: to create a social network of Apple admins in and around Austin and Central Texas. We continually strive for this network to facilitate the sharing of knowledge, the ability to grow and learn, to foster professional development, bolster camaraderie amongst peers, and have some fun along the way. ### Social Media We share information and connect with our colleagues using the following social networks: * Twitter: [https://twitter.com/austinappleadmn](https://twitter.com/austinappleadmn) * Facebook: [https://www.facebook.com/austinappleadmins](https://www.facebook.com/austinappleadmins) * LinkedIn: [https://www.linkedin.com/groups/6974270](https://www.linkedin.com/groups/6974270) * Slack: [https://macadmins.slack.com/archives/austin](https://macadmins.slack.com/archives/austin) * Google Calendar: [https://goo.gl/WwYdQ2](https://goo.gl/WwYdQ2) * TinyLetter: [https://www.tinyletter.com/austinappleadmins](https://www.tinyletter.com/austinappleadmins) ### Meetups Every 1-2 months, we organize and coordinate a meetup involving 1-2 presenters and sponsors that provide both a meeting space and/or food and beverage. Past sponsors include: * [Jamf Software](http://www.jamfsoftware.com/) * [Business Team, The Domain Apple Store](http://www.apple.com/retail/thedomain/) * [HomeAway](http://www.homeaway.com/) * [Trusource Labs](http://www.trusourcelabs.com/) * [ChaiOne](https://chaione.com/) * [Favor Austin](http://favordelivery.com) ### Happy Hours and Social Events Periodically we organize happy hours or general social outings so that members of the community can socialize and commiserate without involving a more formal presentation-style meeting. Past venues include: * [Punch Bowl Social](http://www.punchbowlsocial.com/location/austin) * [The Beer Plant](http://www.thebeerplant.com) * [Fado Austin](http://www.fadoirishpub.com/austin/) * [Geeks Who Drink](http://www.geekswhodrink.com/venue?id=199270) * [Mean-Eyed Cat](http://themeaneyedcat.com/) * [Black Star Co-op](http://www.blackstar.coop/) ### Speaking & Hosting We are always open to adding more hosts, sponsors, and presenters to our community. If you or your organization would like to sponsor an event, please email [hello@austinappleadmins.org](mailto:hello@austinappleadmins.org). If you or your organization would like to host a meetup, please fill out our [hosting form](https://goo.gl/forms/cKaOxNaMgm0N8M4c2). If you would like to present at a future meetup, please fill out our [speakers form](https://goo.gl/forms/SlplkdmkkyKpG7982).
Java
UTF-8
1,136
3.484375
3
[]
no_license
import java.util.Arrays; public class TwoSum { public static int[] findTwoSum(int[] list, int sum) { int[] returnArray = new int[list.length]; Arrays.sort(list); // printArray(a); int top = 0; int bott = list.length - 1; while (top < bott) { while (list[bott] > sum) bott--; int num = list[top] + list[bott]; if (sum == num) { System.out.println(list[top] + " " + list[bott]); returnArray[0] = list[top]; returnArray[1] = list[bott]; top++; bott--; } if (num < sum) top++; if (num > sum) bott--; } return returnArray; //throw new UnsupportedOperationException("Waiting to be implemented."); } public static void main(String[] args) { int[] indices = findTwoSum(new int[] { 1, 3, 5, 7, 9 }, 12); // for (int i = 0; i<indices.length; i++) { // System.out.println(indices[0] + " " + indices[1]); // } } }
Markdown
UTF-8
19,762
3.0625
3
[ "MIT" ]
permissive
--- layout: post title: "Celebrating 10 years of datajournalism" category: posts --- _This essay was written for my talk at the MINDS conference in Copenhagen, on 20 October 2016._ Datajournalism is turning 10! The starting point has been set (by me) to September 2006, when Adrian Holovaty published his oft-quoted piece [A Fundamental Way Newspapers Websites Need to Change](http://www.holovaty.com/writing/fundamental-change/), which serves as a manifesto for many datajournalists. Datajournalism means doing journalism with structured data. Because working with structured data requires strong computer skills, datajournalism mostly means journalists working together with computer developers. This combination of skills enabled all the datajournalism projects you heard of, from the Wikileaks Cablegate to the Panama Papers. Before I reflect on what datajournalism has achieved and look whether or not newspapers websites changed in a fundamental way, let's go back to the beginnings of datajournalism, in a small town, in rural America<sup><a name='note_1' href='#foot_1'>1</a></sup>. ### It all starts in Kansas In the early 2000's, a 20-something named Rob Curley was employed at the Topeka Capital Journal. He was in charge of online publishing. It wasn't much of a prestigious job. A the time, less than a quarter of Americans went online regularly. The strategy of most newspapers on the internet was to re-publish print articles online, usually after they had been printed. Of course, things were already moving. The 1998 Starr report, which gave the details of the Clinton-Lewinsky affair and was published online, had shown that online users could access source documents without the filters of editors<sup><a name='note_2' href='#foot_2'>2</a></sup>. The 2001 attacks had shown that publishing online first and print second might make sense. Most media people did not understand what these changes meant, but Rob Curley did. Curley understood that a website was not a clone of a newspaper on a screen. He understood that you could serve information and content to different audiences much more effectively than in print. He offered users free email and wallpapers (this was 2002!) and pioneered trends that proved more long-lasting. He built a database of all records for the local sports teams, going back to their creation in the late 19<sup>th</sup> century. After every game, his team would add new statistics on each players<sup><a name='note_3' href='#foot_3'>3</a></sup>. He also pioneered new formats, such as interactive maps. In 2004, for the 50<sup>th</sup> anniversary of the _Brown v. Board of Education of Topeka_ decision, which declared segregation in schools illegal in the United States, the Journal published an interactive map, where users could click on dots to see more information<sup><a name='note_4' href='#foot_4'>4</a></sup>. It sounds very unremarkable, until you realize that Google Maps did not even exist at the time (it was launched in 2005)<sup><a name='note_5' href='#foot_5'>5</a></sup>. Rob Curley left the Topeka Capital Journal in 2002 and moved 40 kilometers to Lawrence, Kansas, to work at the LJ World. There, he hired Adrian Holovaty, a self-taught programmer and journalism graduate who had worked at the online operation of the Atlanta Journal-Constitution<sup><a name='note_6' href='#foot_6'>6</a></sup>. The team at the LJ World had developers and journalists working hand-in-hand. They replicated what worked at the Topeka Capital Journal and brought it to a whole new level. To give you an idea of the kind of work they did, let me quote at length from a job offer they posted in 2004<sup><a name='note_7' href='#foot_7'>7</a></sup>: >If you're in the online media field, or trying to get into it, this is the place to be for innovation. >From a content perspective, we pride ourselves on being hyper-local, converged across multiple media (TV, newspaper, Web) and focused on overkill. This is the type of place that doesn't just cover little-league baseball games with a story or two in the Sunday paper; it devotes an entire print publication and Web site to it, with **cell-phone updates**, **weblogs** and **intensive team/league/field databases**. >Our Web-news operation relies heavily on custom development; **pretty much everything is built in-house**. The small-but-nimble development team handles everything technical for our network of sites. **We're the people our newsroom comes to** for implementing special features and workflow optimizations, and we're the people the online boss comes to for building the frameworks for new sites and subsites. The emphasis is mine. It shows that the LJ World worked at the cutting-edge of technology (in 2004, blogs and SMS alerts were a novelty) and that they were working _with_ journalists, not in a separate IT section. At the LJ World, Curley and Holovaty built a new content management system (CMS) because they felt the current one was not good enough. In the process, they created the [Django](https://en.wikipedia.org/wiki/Django_(web_framework)) framework, which is now a very popular tool to build and maintain websites. It is used by the likes of Instagram and Pinterest, which you wouldn't expect to use a tool that came out of a newsroom. ### Spreading over the world The pioneering work of Holovaty and Curley did not go unnoticed. Publishers were already flying to Topeka in 2002 to see Curley's team from close up. The reluctance of newsrooms to work with developers slowly ebbed away. In Europe, the wake-up call came in June 2010, when Wikileaks published the Afghan War Diaries. Wikileaks shared a database of exclusive reports from NATO troops in Afghanistan with Der Spiegel, the New-York Times and the Guardian. It also published most of the source database online, in SQL format. In most European newsroom, no one had a clue how to open such an SQL file. Many realized that, had they had a developer in-house on that day, they could have broken new stories. That's what the company I worked in at the time, OWNI.fr, did. Because we were journalists working hand-in-hand with developers, we did publish some stories and interactives based on the Afghan documents. This got the attention of French publishers, who started to build their own datajournalism teams. Since 2010, dozens of datajournalism operations were created. They are everywhere: at local newspapers like Le Télégramme de Brest (France) or Heilbronner Stimme (Germany), at national newsrooms like Nu.nl (Netherlands) or El Mundo (Spain) and at broadcasters like Yle (Finland) or Český rozhlas (Czechia)<sup><a name='note_8' href='#foot_8'>8</a></sup>. More importantly, datajournalism works. It works for investigations, as the Panama Papers showed. Süddeutsche Zeitung, which received the leak, had to hire a datajournalist (Vanessa Wormer) to better cope with the documents. It works for traffic, too. Pieces from the datajournalism team routinely top the most-viewed rankings of news websites<sup><a name='note_9' href='#foot_9'>9</a></sup>. The European conference on datajournalism, Dataharvest, grew tenfold from its creation in 2010 and now brings together hundreds of specialists. The American equivalent, NICAR, grows from year to year. Specialized conferences emerge, such as Tapestry (for storytelling) in the United States or NODA in the Nordics. Academics now study datajournalism as a field in itself. Journalism schools have also integrated datajournalism to their curriculum. Students now receive ECTS credits in datajournalism course. That scraping data and coding can contribute to students receiving degrees in journalism is a considerable achievement. Some schools even have specialized postgraduate programs, such as the [Máster en Periodismo de Investigación, Datos y Visualización](http://www.escuelaunidadeditorial.es/masteres/master-en-periodismo-de-investigacion-datos-y-visualizacion) in Madrid. The platform we built to teach datajournalism, jQuest, is in use at over 20 schools, just one month after launch! All this growth and appetite for datajournalism is reason enough to celebrate. However, the "fundamental change" Holovaty argued for in his article ten years ago did not happen. ### No fundamental change Ten years is not a short amount of time. You might feel as young as you were in 2006, but keep in mind that 10 years is all it took for cinema to grow from a technical curiosity to the industry we know today. Hollywood studios, the star system, movie theaters and feature films all appeared in the first decade of the twentieth century. If datajournalism had the potential to fundamentally change the news industry, it could have done so in the past ten years. In his landmark article, Holovaty argued that news organization should move from an article-centric worldview, where every piece of information is stored in big blobs of text (the articles), and move to a data-centric one, where different pieces of information are stored separately. By storing structured data instead of text, news organizations could re-purpose a piece information after is has been published. It made business sense then, as it does now. (If the difference between an article-centric and a data-centric organization isn't clear to you, do read [Holovaty's piece](http://www.holovaty.com/writing/fundamental-change/) in full). In 2002, exactly when Holovaty and Curley were creating databases of sports results in Lawrence, Kansas, a small European company was doing pretty much the same thing. That company was called SportingStatz and worked exactly like the journalists of the LJ World did: Whenever a game was played, they collected a lot of data and used it to create visualizations of the game, provide readers with detailed reports and a valuable archive. SportingStatz changed its name to Opta Sports and is now the world leader in sports data. It was acquired in 2013 for about €50 million<sup><a name='note_10' href='#foot_10'>10</a></sup>. The LJ World was also acquired recently, for an undisclosed sum. Upon buying the company, the new owner fired a third of the staff<sup><a name='note_11' href='#foot_11'>11</a></sup>. While Opta grew to world dominance, the LJ World shrunk into irrelevance. Why did two company that did the same thing 14 years ago have such different fates? Maybe it is simply a question of corporate culture. 100-year-old organizations such as newspapers might have a hard time nurturing fast-growing activities. Despite having developed a CMS and one of the most popular web frameworks under Holovaty, for instance, the LJ World failed to turn it into a profitable venture and exited the business in 2012<sup><a name='note_12' href='#foot_12'>12</a></sup>. In Holovaty's 2006 piece, most of the links to the project he showcased are dead. When it comes to his work at the Washington Post, _all_ of the links are dead. Can corporate culture also explain such a disregard for archives? Blaming culture is the lazy thing to do. It does not explain why a certain corporate culture would fail to nurture two successful business and jettison work it paid dearly to produce. The reason why newspapers did not embrace datajournalism, why they did not fundamentally change their websites, to paraphrase Holovaty's title, lies somewhere else. It lies in the purpose newspapers give themselves. ### The change that did happen Holovaty's article was built on the assumption that newspapers are "essential sources of information for their communities". While this might have been true in the early 2000's, it isn't today. To check the weather, you probably have a widget on your phone (or just trust Facebook). To check on events, you probably use Meetup or Ticketmaster (or Facebook). Movies? Rotten Tomatoes (or Facebook). Dates? Tinder (via Facebook Connect). New album from your favorite band? Spotify (or Facebook). Most of our essential sources of information now lie outside of newspapers. Of course, all these competitors structure their data. Otherwise, they could not provide us with powerful search features, automated alerts and tailored offers. Facebook's dominance, for instance, is due in large part to its ability to structure information about its users and put them into very specific groups that advertisers can target. Not a single company that aims at being an essential source of information would think for even a second to store information in blobs of text. Not a single company, except news outlets. Let's recap. Newspapers want to be essential sources of information. Essential sources of information must store their information as structured data. Newspapers know how to store information as structured data, but do not do so. The only possible explanation to this conundrum is that newspapers relinquished their mission to be essential sources of information for their communities. That newspapers give up on their role as providers of essential source of information is only normal. Ever since their creation in the early modern period, newspapers have carried several missions: Provide information, publish opinions and debates or demand change through hard-hitting investigations. We tend to think of these missions as a bundle, because the technology and economics of content ensured that whoever provided one provided the other two. Digitization allowed for each mission to be conducted separately more easily. This was not lost on publishers. Some of them (such as Axel Springer, Schibsted or Le Figaro in Europe) understand that it makes a lot of sense to create subsidiaries to provide essential information on verticals where business models are easy to find. Platforms providing job, housing or car classifieds are largely owned by traditional publishers. For other verticals, such as politics, crime or road accidents, the same publishers did not choose to pursue their role of providers of information. Instead, they focused on discussion and opinions, for which blobs of text are great<sup><a name='note_13' href='#foot_13'>13</a></sup>. Holovaty's life story is here again enlightening. After the Washington Post, he created a company that provided structured data at the micro-local level, EveryBlock.com. The company was acquired by MSNBC in 2009, which simply killed it four years later. Tellingly, EveryBlock wasn't shut down because it was unprofitable, but because _it didn't fit with the owner's strategy_<sup><a name='note_14' href='#foot_14'>14</a></sup>. *** In the last ten years, datajournalism became a great resource for some investigations and enabled new forms of storytelling that users love. Meanwhile, structured data transformed the classified industry and let Facebook take over most online conversations. Some websites did change in a fundamental way, as Holovaty argued. It just wasn't newspapers'. <h4>Newsletter</h4> <p>In case you want to read my next essay in your e-mail inbox, type you email below and you'll be all set.</p> <form style="padding:3px;" action="https://tinyletter.com/nkb" method="post" target="popupwindow" onsubmit="window.open('https://tinyletter.com/nkb', 'popupwindow', 'scrollbars=yes,width=800,height=600');return true"><p><label for="tlemail">Enter your email address</label></p><p><input type="text" style="width:300px" name="email" id="tlemail" /></p><input type="hidden" value="1" name="embed"/><input type="submit" value="Subscribe" /></form> <a name='notes' ></a> ### Notes <a href='#note_1' name='foot_1'>1.</a> This entire history of datajournalism is made of white dudes in their 20's. It's likely that I'm missing out on contributions from others, being myself a white dude in my 20's at the time. If you think I should mention someone, do tell me so: hi@nkb.fr <a href='#note_2' name='foot_2'>2.</a> For more on how the Starr report impacted the media ecosystem, read [Sept. 11, 1998: Starr Report Showcases Net’s Speed](https://archive.is/20161013/https://www.wired.com/2009/09/dayintech_0911starrreport). <a href='#note_3' name='foot_3'>3.</a> An archived version of this database can be [found at the web Archive](https://archive.is/20161013/Catzone http://web.archive.org/web/20020901144026/http://catzone.com/data/womensbasketball/2001_2002/teams/619_stats.shtml). <a href='#note_4' name='foot_4'>4.</a> Still [online here](https://archive.is/20161013/Historic map http://cjonline.com/indepth/brown/historic-spots-map.shtml). <a href='#note_5' name='foot_5'>5.</a> For more background on Curley's work at the Topeka Capital Journal, read [Innovation in the Heartland](https://archive.is/20161013/http://www.ojr.org/ojr/lasica/1029874865.php), a 2002 piece of the Online Journalism Review. <a href='#note_6' name='foot_6'>6.</a> You'll find a nicely written portrait of Holovaty at the Chigaco Tribune: [EveryBlock's Adrian Holovaty can't find "individuality or entrepreneurship" in the news business](https://archive.is/20161013/http://featuresblogs.chicagotribune.com/technology_internetcritic/2008/08/everyblocks-adr.html) <a href='#note_7' name='foot_7'>7.</a> Find the job application on Holovaty's blog: [Job: Web developer for World Online in Lawrence, Kansas](https://archive.is/20161013/http://www.holovaty.com/writing/280/). <a href='#note_8' name='foot_8'>8.</a> I started compiling a list of all datajournalism operations in Europe [on an Etherpad](https://archive.is/20161013/https://public.etherpad-mozilla.org/p/Datajournalism_Teams_in_Europe). The total count is over 50. <a href='#note_9' name='foot_9'>9.</a> [The World at 7 Billion](https://archive.is/20161013/http://helenesears.co.uk/?projects=the-world-at-seven-billion) was the most shared news story on Facebook in 2011, for instance. A dialect quiz at the New-York Times [was the most-viewed article of 2013](https://archive.is/20161013/http://www.wbur.org/hereandnow/2014/02/19/vaux-dialect-quiz). The list could go on. <a href='#note_10' name='foot_10'>10.</a> Read [Perform Group buys sports data company Opta](https://archive.is/20161013/http://www.reuters.com/article/perform-opta-idUSL5N0F90L520130703). <a href='#note_11' name='foot_11'>11.</a> Read [30 people elminated at LJWorld](https://archive.is/20161013/http://6lawrence.com/news/local-news/19709-30-people-elminated-at-ljworld). <a href='#note_12' name='foot_12'>12.</a> Read [The Lawrence Journal-World gets out of the CMS business, losing out to freebies like WordPress](https://archive.is/20161013/http://www.niemanlab.org/2012/06/the-lawrence-journal-world-gets-out-of-the-cms-business-losing-out-to-freebies-like-wordpress/). The LJ World did not sell Django, which is free. Instead, it sold Ellington, a CMS based on Django. The economics of open source software are complex and not the focus of this essay. What must be noted, however, is that most companies that manage successful open source software do have a business around it, through sales of services, certification, conferences etc. <a href='#note_13' name='foot_13'>13.</a> It's important to note that many organizations do provide structured information on these other verticals. In politics, Regards Citoyens in France or VoteWatch.eu at the European level do just that. Even though many journalists within newspapers would love to launch such projects, very few attempts were made. <a href='#note_14' name='foot_14'>14.</a> Read [NBC closes hyperlocal, data-driven publishing pioneer EveryBlock](https://archive.is/20161013/http://www.poynter.org/2013/nbc-closes-hyperlocal-pioneer-everyblock/203437/). While the financials of EveryBlock have never been made public, NBC said it wasn't _profitable enough_, not that it was bleeding money. For the 5-year-old project that EveryBlock was at the time, such an achievement is already a financial success.
JavaScript
UTF-8
2,058
2.75
3
[]
no_license
import { useState, useEffect } from "react"; import { createStage } from "../gameHelpers"; export const useStage = (player, resetPlayer) => { const [stage, setStage] = useState(createStage()); const [rowsCleared, setRowsCleared] = useState(0); //dolanda 1 columu bosalt useEffect(() => { setRowsCleared(0); const sweepRows = newStage => newStage.reduce((acc, row) => { // console.log(row); if (row.findIndex(cell => cell[0] === 0) === -1) {//sil //eger 0-a beraber bir sey tapmazsa (bos yer tapmazsa) setRowsCleared(prev => prev + 1); acc.unshift(new Array(newStage[0].length).fill([0, "clear"])); //sildiyimiz qeder arrayin evveline column ekle return acc; } acc.push(row);//davam ele return acc; },[]);//reduce ucun initial valu const updateStage = prevState => { //array verir mene boyuk stegi //first flush the stage const newStage = prevState.map( row => row.map(cell => (cell[1] === "clear" ? [0, "clear"] : cell)) //burda menim sehvim var idi 4 saata hell eledim [cell] yazmisdim))))) ); //then draw the tetramano //mes bunu goturur // [0, "I", 0, 0], // [0, "I", 0, 0], // [0, "I", 0, 0], // [0, "I", 0, 0] player.tetromino.forEach((row, y) => { row.forEach((value, x) => { if (value !== 0) { newStage[y + player.pos.y][x + player.pos.x] = [ value, `${player.collided ? "merged" : "clear"}` ]; //newStage[3][4]===I } }); }); // console.log(newStage) //then check if we collided if (player.collided) { //eger deydise reset ele resetPlayer(); return sweepRows(newStage) } return newStage; }; setStage(prev => updateStage(prev)); //deyis funca uygun YENI newstage ile deyissin }, [player, resetPlayer]); //bos array olanda yeni seh yuklenenede return [stage, setStage,rowsCleared]; };
C++
UTF-8
690
2.734375
3
[]
no_license
/** * Filename: Bullet.BULLET_HPP * * Represents a bullet. **/ #ifndef BULLET_HPP #define BULLET_HPP #include <math.h> #include <SFML/Graphics.hpp> #include "GameApp.hpp" #include "Player.hpp" class Bullet { public: Bullet(GameDataRef data); ~Bullet(); void draw(); sf::CircleShape getShape(); void move(float shot); sf::Vector2f position; void set(int x, int y); void update(float secs); void modify(std::string power); std::string getType(); void backmove(float shot); void setFillColor(); std::string power; private: sf::CircleShape bullet; GameDataRef gameData; sf::Clock clock; Player *spaceship; }; #endif
JavaScript
UTF-8
867
3.015625
3
[]
no_license
'use strict'; const Notes = require('../lib/notes.js'); // Spies! // Wouldn't it be great to know if something got called the right way? // Or the right number of times? // Or with the right arguments? // This "spies" on console.log() so that we can watch it being called by our // code and letting us make assertions on if it got called correctly jest.spyOn(global.console, 'log'); describe('Note Module', () => { it('execute() does nothing with invalid options', () => { const notes = new Notes({ command: {} }); notes.execute(); expect(console.log).not.toHaveBeenCalled(); }); it('notes() can add a note', () => { const action = 'add'; const payload = 'test note'; const notes = new Notes({ command: { action, payload } }); notes.execute(); expect(console.log).toHaveBeenCalledWith(`Adding Note: ${payload}`); }); });
Java
UTF-8
10,324
1.585938
2
[]
no_license
package ru.a5x5retail.frontproductmanagement.packinglistitems; import android.annotation.SuppressLint; import android.arch.lifecycle.ViewModelProviders; import android.content.Intent; import android.graphics.Rect; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v4.widget.SwipeRefreshLayout; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import com.arellomobile.mvp.presenter.InjectPresenter; import java.sql.SQLException; import java.util.UUID; import ru.a5x5retail.frontproductmanagement.DocType; import ru.a5x5retail.frontproductmanagement.ProdManApp; import ru.a5x5retail.frontproductmanagement.adapters.abstractadapters.IRecyclerViewItemShortClickListener; import ru.a5x5retail.frontproductmanagement.adapters.viewadapters.BasicRecyclerViewAdapter; import ru.a5x5retail.frontproductmanagement.adapters.viewholders.BasicViewHolder; import ru.a5x5retail.frontproductmanagement.adapters.BasicViewHolderFactory; import ru.a5x5retail.frontproductmanagement.base.BaseAppCompatActivity; import ru.a5x5retail.frontproductmanagement.base.BaseViewModel; import ru.a5x5retail.frontproductmanagement.configuration.AppConfigurator; import ru.a5x5retail.frontproductmanagement.configuration.Constants; import ru.a5x5retail.frontproductmanagement.db.models.CheckingListHead; import ru.a5x5retail.frontproductmanagement.db_local.ProjectMap; import ru.a5x5retail.frontproductmanagement.newdocumentmaster.extendinvoicemasters.ExtendInvoiceMasterActivity; import ru.a5x5retail.frontproductmanagement.newdocumentmaster.invoicemasters.decommissionspoilmaster.DecommissionSpoilMasterActivity; import ru.a5x5retail.frontproductmanagement.newdocumentmaster.inventorymaster.InventoryMasterActivity; import ru.a5x5retail.frontproductmanagement.R; public class PackingListItemsActivity extends BaseAppCompatActivity implements IPackingListItemsView { @InjectPresenter PackingListItemsPresenter presenter; @Override protected void onCreate(Bundle savedInstanceState) { overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right); super.onCreate(savedInstanceState); setContentView(R.layout.activity_packing_list_items); init(); } @Override public void finish() { super.finish(); overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); } private RecyclerView docItemsRecyclerView; private BasicRecyclerViewAdapter<CheckingListHead> adapter ; private FloatingActionButton fab; private SwipeRefreshLayout mSwipeRefreshLayout; @SuppressLint("RestrictedApi") private void init() { if (ProjectMap.getCurrentTypeDoc() == null) { throw new NullPointerException("Object currentDoc not initialized!"); } DocType td = ProjectMap.getCurrentTypeDoc(); if (td != null) { this.setTitle(td.getShortName()); } getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); fab = findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { createIntent(); } }); docItemsRecyclerView = findViewById(R.id.DocItemsRecyclerView); initRecyclerView(); mSwipeRefreshLayout = findViewById(R.id.swipe_container); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mSwipeRefreshLayout.setRefreshing(false); presenter.load(); } }); } private void initRecyclerView(){ adapter = new BasicRecyclerViewAdapter<>(); CheckingListHeadViewHolderFactory factory = new CheckingListHeadViewHolderFactory(); adapter.setHolderFactory(factory); adapter.setLayout(R.layout.item_packing_list_items_rv); adapter.setShortClickListener(new IRecyclerViewItemShortClickListener<CheckingListHead>() { @Override public void OnShortClick(int pos, View view, CheckingListHead innerItem) { /* for (int i =0; i < 100; i++){ try { ProjectMap.setCurrentCheckListHead(innerItem); } catch (Exception e) { e.printStackTrace(); } try { CheckingListHead ccc = ProjectMap.getCurrentCheckingListHead(); Log.e("sss",ccc.Guid) ; UUID bb = UUID.fromString(innerItem.Guid); } catch (Exception e) { e.printStackTrace(); } }*/ ProjectMap.setCurrentCheckListHead(innerItem); ProdManApp.Activities .createPackingListPreviewActivity (PackingListItemsActivity.this); } }); docItemsRecyclerView.setAdapter(adapter); docItemsRecyclerView.addItemDecoration(new PackingListItemsRvDecoration()); } /* private void initViewModel() { viewModel = ViewModelProviders.of(this).get(PackingListItemsViewModel.class); viewModel.addDataChangedListener(new BaseViewModel.IDataChangedListener() { @Override public void dataIsChanged() { adapter.setSourceList(viewModel.getHeadList()); adapter.notifyDataSetChanged(); } }); DocType td = ProjectMap.getCurrentTypeDoc(); if (td != null) { this.setTitle(td.getShortName()); } // loadViewModel(); }*/ /* private void loadViewModel() { if (viewModel.getState() == Constants.ViewModelStateEnum.LOADED) { return; } loadVm(); } private void reLoadViewModel() { loadVm(); }*/ /* private void loadVm(){ try { viewModel.Load(); } catch (SQLException e) { e.printStackTrace(); setErrorToast(e,Constants.Messages.SQL_EXEPTION_MSG); } catch (ClassNotFoundException e) { e.printStackTrace(); } }*/ @Override public void updateView() { adapter.setSourceList(presenter.getHeadList()); adapter.notifyDataSetChanged(); } @SuppressLint("HardwareIds") private void createIntent() { /* if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { return; }*/ switch (ProjectMap.getCurrentTypeDoc().getTypeOfDocument()){ case PARTIAL_INVENTORY: CreateIntent(InventoryMasterActivity.class,ProjectMap.getCurrentTypeDoc().getTypeOfDocument()); break; case INNER_INCOME: CreateIntent(ExtendInvoiceMasterActivity.class,ProjectMap.getCurrentTypeDoc().getTypeOfDocument(),1); break; case OUTER_INCOME: CreateIntent(ExtendInvoiceMasterActivity.class,ProjectMap.getCurrentTypeDoc().getTypeOfDocument(),1); break; case DISCARD: CreateIntent(DecommissionSpoilMasterActivity.class,ProjectMap.getCurrentTypeDoc().getTypeOfDocument()); break; } } private void CreateIntent(Class<?> c,Constants.TypeOfDocument td){ ProdManApp.Activities .createNewDocumentActivity(this,c,1); } private void CreateIntent(Class<?> c,Constants.TypeOfDocument td, int requestCode){ ProdManApp.Activities .createNewDocumentMasterActivity(this,c,td, requestCode); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.packing_list_items_menu,menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()){ case R.id.itemUpd : presenter.load(); return true; case android.R.id.home : finish(); return true; } return true; } @Override public boolean onContextItemSelected(MenuItem item) { return true; } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); presenter.load(); } public class CheckingListHeadViewHolder extends BasicViewHolder<CheckingListHead> { private TextView text_view_1,text_view_2,text_view_3,text_view_4; public CheckingListHeadViewHolder(@NonNull View itemView) { super(itemView); text_view_1 = itemView.findViewById(R.id.text_view_1); text_view_2 = itemView.findViewById(R.id.text_view_2); text_view_3 = itemView.findViewById(R.id.text_view_3); text_view_4 = itemView.findViewById(R.id.text_view_4); } @Override public void setSource(CheckingListHead source) { text_view_1.setText(source.NameDoc); text_view_2.setText(source.contractorName); text_view_3.setText(source.summ.toString()); text_view_4.setText(source.summVat.toString()); } } public class CheckingListHeadViewHolderFactory extends BasicViewHolderFactory { @Override public BasicViewHolder getNewInstance(View itemView) { return new CheckingListHeadViewHolder(itemView); } } public class PackingListItemsRvDecoration extends RecyclerView.ItemDecoration { @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { outRect.top = 2; } } }
Java
UTF-8
2,286
2.25
2
[]
no_license
package com.farmatodo.tienda.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="cliente") public class Cliente { // `id_cliente` int(11) NOT NULL AUTO_INCREMENT, @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id_cliente") private int idCliente; // `nombre_completo` varchar(100) DEFAULT NULL, @Column(name="nombre_completo") private String nombreCompleto; // `edad` int(3) DEFAULT NULL, @Column(name="edad") private int edad; // id_tipo_documento int(11) NOT NULL , @Column(name="id_tipo_documento") private int idTipoDocumento; // `numero_documento` varchar(20) DEFAULT NULL, @Column(name="numero_documento") private String numeroDocumento; // `correo` varchar(60) DEFAULT NULL, @Column(name="correo") private String correo; // `usuario` varchar(60) NOT NULL, @Column(name="usuario") private String usuario; // `contrasegna` varchar(60) DEFAULT NULL, @Column(name="contrasegna") private String contrasegna; public int getIdCliente() { return idCliente; } public void setIdCliente(int idCliente) { this.idCliente = idCliente; } public String getNombreCompleto() { return nombreCompleto; } void setNombreCompleto(String nombreCompleto) { this.nombreCompleto = nombreCompleto; } public int getEdad() { return edad; } public void setEdad(int edad) { this.edad = edad; } public int getIdTipoDocumento() { return idTipoDocumento; } public void setIdTipoDocumento(int idTipoDocumento) { this.idTipoDocumento = idTipoDocumento; } public String getNumeroDocumento() { return numeroDocumento; } public void setNumeroDocumento(String numeroDocumento) { this.numeroDocumento = numeroDocumento; } String getCorreo() { return correo; } void setCorreo(String correo) { this.correo = correo; } public String getUsuario() { return usuario; } public void setUsuario(String usuario) { this.usuario = usuario; } public String getContrasegna() { return contrasegna; } public void setContrasegna(String contrasegna) { this.contrasegna = contrasegna; } }
Markdown
UTF-8
655
3.78125
4
[]
no_license
#### [1. 两数之和](https://leetcode-cn.com/problems/two-sum/) 给定一个整数数组 `nums` 和一个目标值 `target`,请你在该数组中找出和为目标值的那 **两个** 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。 ```c++ class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int,int> map; for(int i=0;i<=nums.size();i++){ if(map.count(target-nums[i])) return {i,map[target-nums[i]]}; map[nums[i]] = i; } return {}; } }; ```
Python
UTF-8
228
3.0625
3
[]
no_license
# -*- coding: utf-8 -*- from typing import List class Solution: def missingNumber(self, nums: List[int]) -> int: return int((1 + len(nums)) * (len(nums) / 2) - sum(nums)) print(Solution().missingNumber([3,0,1]))
Java
UTF-8
2,855
2.28125
2
[]
no_license
package com.ipartek.formacion.springsecurityejemplo.configuraciones; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { //Ver en https://spring.io/guides/gs/securing-web/ //Configura los accesos @Override protected void configure(HttpSecurity http) throws Exception { http //Permite a todo el mundo entrar a home .authorizeRequests() .antMatchers("/", "/home").permitAll() .anyRequest().authenticated() .and() //Permite a todo el mundo entrar en login .formLogin() .loginPage("/login") .permitAll() .and() //Se permite a todo el mundo salir .logout() .permitAll(); } //https://www.baeldung.com/spring-security-jdbc-authentication @Autowired private DataSource dataSource; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { //Pongo el 1 porque en mi tabla no hay ese campo. Es como si pusiera enabled a todo //Filtrado por usuario auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(new BCryptPasswordEncoder()) .usersByUsernameQuery("select email,password,1 " + "from usuarios " + "where email = ?") //Filtrado por rol .authoritiesByUsernameQuery("select email,rol " + "from usuarios " + "where email = ?"); } // https://www.browserling.com/tools/bcrypt // CREATE TABLE users ( // username VARCHAR(50) NOT NULL, // password VARCHAR(100) NOT NULL, // enabled TINYINT NOT NULL DEFAULT 1, // PRIMARY KEY (username) // ); // // CREATE TABLE authorities ( // username VARCHAR(50) NOT NULL, // authority VARCHAR(50) NOT NULL, // FOREIGN KEY (username) REFERENCES users(username) // ); // // CREATE UNIQUE INDEX ix_auth_username // on authorities (username,authority); // -- User user/pass // INSERT INTO users (username, password, enabled) // values ('user', // '$2a$10$8.UnVuG9HHgffUDAlk8qfOuVGkqRzgVymGe07xd00DMxs.AQubh4a', // 1); // // INSERT INTO authorities (username, authority) // values ('user', 'ROLE_USER'); }
TypeScript
UTF-8
416
2.8125
3
[]
no_license
export interface Episode { id?: number, name: string, air_date?: string, episode?: string, characters?: string[], url?: string, created?: string, }; const fetchEpisodeData = async (url: string) => { if(url) { const result = await fetch(url); const json = await result.json(); return { ...json } as Episode; } return { name: 'Unknown' } as Episode; }; export { fetchEpisodeData };
C++
UTF-8
4,343
3.03125
3
[]
no_license
//========================================================== // // Filename: P2PGMPicture.cpp // // Description: Laedt und speichert ein Bild im P2 Format // // Version: 1.0 // Created: 31.10.2015 // Compiler: g++ // // Author: Sebastian Hoelscher, sebastian@hoelshare.de // //========================================================== #include <iostream> #include <fstream> #include <iomanip> #include <string> #include <sstream> #include "head/InputHandler.h" #include "head/Picture.h" #include "head/P2PGMPicture.h" #include "head/EnumConverter.h" #include "head/FILETYPE.h" #include "exception/NotImplementedException.h" #include "exception/InvalidPictureException.h" #include "exception/FileNotFoundException.h" using namespace std; /** * Ladekontruktor */ P2PGMPicture::P2PGMPicture(InputHandler* inputHandle) { this->inputHandle = inputHandle; this->filetype = P2; loadData(); } /** * Kopier Konstruktor */ P2PGMPicture::P2PGMPicture(const Picture* origPic) { // Bild kopieren this->filename = origPic->getFilename(); this->filetype = origPic->getFiletype(); this->greydepth = origPic->getGreydepth(); this->height = origPic->getHeight(); this->width = origPic->getWidth(); this->data = new Pixel*[this->height]; for (int row = 0; row < this->height; row++) { // Speicher pro Zeile beschaffen this->data[row] = new Pixel[this->width]; for (int col = 0; col < this->width; col++) { this->data[row][col] = origPic->getData(row, col); } } } /** * Leerer Destruktor */ P2PGMPicture::~P2PGMPicture() { // Der Data Pointer wird im Destruktor von Picture freigegeben } /** * Speichert das Bild im P2 Format * Dateityp * Breite Hoehe * Maximale Grautiefe * [Breite*Hoehe] Grauwerte * * Laut Dateibeschreibung ist die Position eines Zeilenumbruchs nicht von * bedeutung und wird oft nach max 75 Zeichen gesetzt */ void P2PGMPicture::savePicture(std::string filename) { ofstream dateiStream; dateiStream.open(filename.c_str()); int ausgaben = 0; if (!dateiStream) { throw FileNotFoundException(filename.c_str()); } // Kopfdaten ausgeben dateiStream << EnumConverter::toString(this->filetype) << endl; dateiStream << this->width << " "; dateiStream << this->height << endl; dateiStream << this->greydepth << endl; dateiStream << right; // Bilddaten speichern for (int row = 0; row < this->height; row++) { for (int col = 0; col < this->width; col++) { dateiStream << " " << setw(3) << (int) (this->data[row][col]); if (++ausgaben % 18 == 0) // Eine Zeile darf maximal 75 Zeichen beeinhalten { dateiStream << endl; } } } dateiStream.flush(); dateiStream.close(); } /** * Laedt das Bild im P2 Format * Format (bereits gelesen an diesem Punkt) * Breite Hoehe * Maximale Grautiefe * [Hoehe*Breite] Grauwerte */ void P2PGMPicture::loadData() { // Der Filetyp wurde bereits ausgelesen! this->width = inputHandle->readInt(); this->height = inputHandle->readInt(); this->greydepth = inputHandle->readInt(); // Dynamisch speicher beschaffen zum abspeichern der Bildpunkte this->data = new Pixel*[this->height]; for (int row = 0; row < this->height; row++) { // Speicher pro Zeile beschaffen this->data[row] = new Pixel[this->width]; for (int col = 0; col < this->width; col++) { int tempValue = inputHandle->readInt(); // Pruefe den Wert, ob dieser im Wertebereich liegt if(tempValue > this->greydepth) { stringstream ssErrortext; ssErrortext << "Current greyvalue(" << tempValue << ") higher than max greydepth (" << this->greydepth << ")"; string errorText = ssErrortext.str(); throw InvalidPictureException(errorText); } this->data[row][col] = tempValue; } } } /** * Prueft die Fachlichen Daten des Bildes */ bool P2PGMPicture::checkData() { if (this->filetype != P2) { throw NotImplementedException(EnumConverter::toString(this->filetype)); } if (this->greydepth < 0 || this->greydepth > 255) { throw InvalidPictureException(); } return (true); }
Markdown
UTF-8
101,925
2.875
3
[]
no_license
The Logical Form of Action Sentences Davidson 1967 * _Jones did it slowly, deliberately, in the bathroom, with a knife, at midn._ * What he did was butter a piece of toast. We are roo familiar * language of action * the _it_ seems to refer to some entity, preswnably an action, that is chen characterized in a number of ways. Asked for the * logical form of this sentence: 'There is an action x such that Jones did x slowly and Jones did x delibera' * no singular term to substirure for 'x' * substitute for 'x' and get 'Jones buttered a piece of toast slowly and Jones buttered a piece of t..' * Another sign that we don't have the logical form of the sentence is that in this last version there is no implication that a single action was slow, deliberate, and in the bathr, * The present Essay is devoted to trying to get * the logical form of simple sentences about anions straight. I would like to * an account of the logical or grammatical role of the parts or words of such sentences that is consistent with the entailment relations between such sentences and with whar is known of the role of those same parts or words in other (non-action} sentences * = showing how the meanings of acrion sentences depend on their structure. I * nor concerned with * eg the meaning of deiiberarely' as opposed, perhaps, to 'voluntary'; bur I * the difference between 'Joe believes/knows that there is life on Mars' and 'Joe * no difference in logical form. That the * second, bur nor the first, entails 'There is life on Mars' is plausible * but emerges only from the meaning analysis of 'believes' and 'knows'. * there is something arbitrary in how much of logic to pin on logical form. * uncover enough structure co make it possible to scare, for an arbitrary sentence, how its meaning depends on that StfUCCUre, and we must nor attribute more structure than such a theory of meaning can accommodate. * eg (1) Jones buttered the coast slowly, deliberately, in the bathroom, with a knife, at midnight. * cannot treat the 'deliberately' on a par with the other modifying clauses. * It alone imputes intention, for of course Jones may have buttered the coast * postpone dis­ cussion of the 'deliberately' and its intentional kindred. * 'Slowly', unlike the other adverbial clauses, fails co introduce a new entity (a place, an instrument, a time), and also * eg Susan says, 'I crossed the Channel in fifteen hours.' 'Good grief, that was slow/%slowly.' * what does 'that' refer to? No appropriate singular rerm appears in 'I * Now Susan adds, 'But I swam.' 'Good grief, that was fast.' We do * not withdraw the claim that it was a slow crossing; this is consistent * its being a fasr swimming. Here we have enough to show, I think, * 'It was a slow crossing' != 'It was slow and it was a crossing' since the crossing may also be a swimming that was nor slow, in which case we => "It was slow & it was a crossing & it was a swimming & it was not slow.' * not specific for actions, * the logical role of the attributive adjectives in 'Grundy was a short basketball player, but a tall than', and 'This is a good memento of the murder, but a poor steak knife.' * The problem of arrriburives is indeed a problem abouc logical form, bur it may be put to one side here because it is not spec for action sentences * We have decided co ignore, for the moment ar least, the first two adverbial (2) Jones buttered the toast in the bathroom with a knife at midnight. Kenny (ch vii same vol): most philosophers today would, as a Start, analyse this sentence as containing a five-place predicate with the * argument places filled with singular terms or bound variables. If we go on * arity depends on the number of modifiers * obliterate that (2) entails the others. Or, to put the objecrion * the original sentences contain a common syntactic element ('buttered') * But the proposed analyses show no such common element. * Kenny rejects the suggestion that 'Jones burrered the toast' be considered as elliptical for 'Jones buttered the toast somewhere with something ar s time', * would rescore the wanted entailments, on the ground that * we could never be sure how many standby positions to provide in each ac pred * 'by/hile holding it between the toes of his left foot' adds/not a place to the predicate only if they differ in meaning and it is nor quite clear that this is so * we cannot view verbs of acrion as usually containing many srandby positions. * but no knock-down argument (eg a method for increasing the number of places indefinirely.) * footnote Kenny seems to mink there is such a method, for he write.'>, 'If we cast our net widely enough, we C4Jl make "Brutus killed Caesar" ineo a sentence which describes, with a certain lack of speci­ fication, the whole history of the world (op. cit., 1(0) * hE But he does not show how to make each addition to the scnrence one that irreducibly modify the killing as opposed, say, to Brutus or Caesar, or the place or the time * Kenny proposes that we may exhibit the logical form of (2) the following mannr (3) Jones brought it about that the toasr was buttered in the barhroorn with a knife at midnight. * there are merits in this proposal (I shall consider some of them presently) * it does not solve the problem Kenny raises. For it is, if anything * even more obscure how (3) entails 'Jones brought it about that the coast was buttered' or 'The toast was buttered' * Kenny seems to have confused two independent problems. * how to represent the idea of agency: it is this that prompts Kenny to assign 'Jones' a logically distinguished role in (3) * 'variable polyadicity' (as Kenny calls it) of action verbs. And it is clear * arises with respecr ro the sentences that replace 'p' in 'brings it about that p'. * If I say I bought a house downtown that has four bedrooms, two fireplaces, and * the logical form of the sentences I use presents no problem (in this resp). * 'There is a house such that I bought it, it is downtown, it has four bedroom * the iterated relative pronoun will carry the reference back co the same entity as often as desired * action suggests the same idea: that there are such things as actions, and that a sentence like (2) describes the action in a number of ways * 'Jones did it with a knife.' 'Please rell the more about it.' The 'it' here doesn't refer to Jones or the knife, bur to what Jones did---or so it seems. * Austin's discussion of excuses illustrates over and over the faer that our common talk and reasoning about actions is most naturally analysed by supposing that there are such entities. * what is the relation between my pointing the gun and pulling the trigger, and my sheering the victim? The natural and, 1 think, correct answer is that * the relation is that of identity * The logic of this sort of excuse includes, it seems, at least this : I am accused of doing b, which is deplorable 1 admit I did a, which is excusable My excuse for doing b rests upon my claim that 1 did nor know that a = b. * Anomer pattern of excuse would have the allow that I shot the victim intentionally, bur in self-defence * Now the structure includes something more. * I am still accused of b (my shooting the victim), which is deplorable * I admit 1 did c (my shooting the victim in self-defence), which is excusable * My excuse for doing b rests upon my claim that I knew or believed that b = c * Again I shoot the victim, again inten­ tionally * What 1 am asked to explain is my shooting of the bank president (d), for the * My excuse is that I shot the escaping murderer (e), and surprising and * my shooting the escaping murderer and my shooting of the bank president were one and the same action __since__ it is the same person * To justify the 'since' we must presumably think of 'my shooting of x' as a functional expression that names an action when the 'x' is replaced by an appropriate singular term. The relevant reasoning would then be an application of x= y => fx = fy * Excuses provide endless examples of cases where we seem compelled to rake talk of 'alternative descriptions of the same action' seriously, i.e., literally. * plenry of other contexts in which the same need presses * Explaining an action by giving an intention with which it was done provides new descriptions of the action: I am writing my name on a piece of paper with the intention of writing a cheque withthe intention of paying my gambling debt * to have a coherent theory of action tell that of these sentences is made true by the same action * Redescription may supply the motive ('I was getting my revenge'), place the action in the context of a rule ('I am castling'), give the outcome ('I killed him'), or provide evaluation ('I did the right thing'). * Kenny:, action sentences have the form 'Jones brought it about that p * The senrence that replaces 'p' is to be in the present tense, and it * p is newly true of the patient'. 4 Thus, 'The doctor removed the patient's * ? the sentence that replaces 'p' describe a terminal state (not event), => avoid the criticism made above that the problem of the logical form of action sentences rums up within the sentence that replaces 'p' * 'The patient has no appendix' presents no relevant problem. The difficulry is that neither [így sem] will the analysis stand in ics present form. * The doctor may bring it about that the patient has no appendix by turning the patient over to anomer doctor who performs the operation; or by running the patient down with his Lincoln Continental * In neither case would we say the doctor removed the patient's appendix. * Closer approximations to a correct analysis might be, 'The doctor brought it about that the doctor has removed the patient's appendix' or perhaps, 'The doctor brought it about that the patient has had his appendix removed by the donor.' One may still have a few * doubts as to whether these sentences have the same truth conditions as 'The * But in any case it is plain that in these versions, the problem of the logical form of action sentences does turn up in the sentences that replace 'p': ' * p is no easier to analyse than 'The doctor removed the patient's appendix' By the same roken, = d), since the bank president and the escaping murderer were one and ~ * 'Cass walked to the score' can't be given as 'Cass brought it about that Cass is at the store' since this drops the idea of walking * 'Smith coughed.' * 'Smith brought it about that Smith is in a state of just having coughed'? At * would be correct only if Smith coughed on purpose. * Kenny wants to represent every (completed) action in terms only of the agent, the notion of bringing it about that a state of affairs obtains, and the state of affairs brought about by the agent * hE many action sentences yield no description of the state of affairs brought about by the * A natural move, then, is to allow that the sentence that replaces 'p' in 'x brings it about that p' may (or perhaps must) describe an event. * Chisholm has suggesred an analysis that at least permits the sentence that replaces 'p' to describe an event." His * 'x makes p happen', though he uses such variants as 'x brings it abour that p' or 'x makes it true that p'. Chisholm * the entities to which the expressions that replace 'p' refer := 'states of affairs', and explicitly adds chat states of affairs may be changes or events (as weJl as 'unchanges'). An * eg if a man raises his arm, then we may say he makes it happen that his arm goes up. I do not know whether Chisholm * I think the proposal would be wrong because although the second of these senrences does perhaps email the firsr the first does not entail the second.' * other puzzle about Chisholm's analysis of action sentences, and it is * independent of the question what sentence we substitute for 'p'o Whatevet * we are to interpret `p` as describing some event * whole sentences of the form 'x makes it happen that p' also describe events * are these events the same evenr, or they are different? If they are the * if same , as many people would claim (perhaps including Chisholm), then no maner what we put for 'p', we cannot have solved the general problem * If different events, how has the elemenc of agency been introduced inro the larger sentence though it is lacking in the sentence for which `p` stands; for each has the agenr as its subject. The answer Chisholm gives, I think, is that the special notion of making it happen chat he has in mind is intentional, and thus co be disringuished from simply causing something eg we want to say that Alice broke the mirror without implying that she did it intentionally. Then * Chisholm's special idiom is not called for; but * we could say, 'Alice caused it to happen that the mirror broke.' * Suppose we now want to add that she did it intentionally. Then the * Chisholm-sentence would be: 'Alice made it happen that Alice caused it to happen that the mirror broke.' And now we want co know, what is the event that che whole sentence reports, and that the contained sentence does not? It is, apparently, just whar used ro be called an act of the will. I will not dredge up the standard objections co the view thee acts of the will are special events distinct from, say. our bodily movements. and perhaps the causes of them. But even if Chisholm is willing co accept such a view, the problem of the logical form of the sentences that can replace `p` remains, and these describe the things people do as we describe them when we do nor impute intention. A somewhat different view has been developed with care and precision by von Wright. 6 In effect, von Wright puts action sentences into the following form: "x brings it about that a state where p changes into a state where q'. Thus the important relevanr difference between von Wright's analysis and the ones we have been considering is the more complex srrucrure of the description of the change or event the agenr brings about: where Kenny and Chisholm were conrenr to describe the result of the change, von Wright includes also a description of the initial state, Von Wright is interested in exploring the logic of change and action and not, at least primarily, in giving the logical form of our common sentences about acts or events. For the purposes of his study, it may be vecy fruitful to think ofevents as ordered pairs of states. But I think it is also fairly obvious that this does nor give us a standard way of translating or representing the form of most sentences about acts and events. If I walk from San Francisco ro Pittsburgh, for example, my initial state is that I am in San Francisco and my terminal srare is that I am in Pittsburgh; bur the same is more pleasantly true if I fly. Of course, we may describe the terminal state as my having walked to Pittsburgh from San Francisco, bur then we no longer need the separate statement of the initial state, Indeed, viewed as an analysis of ordinary sentences about actions, von Wright's proposal seems subject co all the difficulties I have already outlined plus the extra one that mosr action sentences do not yield a non-trivial description of the initial scare (try 'He circled the field', 'He recited the Odyssey', 'He Airted with Olga). In two matters, however, it seems ro the von Wright suggests important and valuable changes in the pattern of analysis we have been considering, or at least in our interpretation of it. Pirsr, he says that an action is not an event, bur rather the bringing about of an event. I do not mink chis can be correct. If I fall down, chis is an event whether I do it intentionally or not. If you thought my falling was an accident and later discovered I did it On purpose, you would not be tempted to withdraw your claim that you had witnessed an event. I rake von Wrighr's refusal to call an action an event to reflect embarrassment we found to follow if we say that an act is an event, taking agency to be introduced by a phrase like 'brings it about that', The solution lies, however, not in distinguishing acts from events, but in finding a different logical form for action sentences. The second important idea von Wright introduces comes in the context of his distinction between genn-icand individual propositions about events." The distinction, as von Wright makes it, is not quite clear, for he says both: that an individual proposition differs from a generic one in having a uniquely determined truth value, while a generic proposition has a truth value only when coupled with an occasion; and that. that Brutus killed Caesar is an individual proposition while that Brutus kissed. Caesar is a generic proposition, because 'a person an be kissed by another on more than one occasion'. In facr the proposition that Brutus kissed Caesar seems to have a uniquely determined truth value in the same sense that the proposinon that Brutus killed Caesar does. But it is, I believe, a very important observarion that 'Brutus kissed Caesar' does nor, by virtue of its meaning alone, describe a single act. It is easy ro see that the proposals we have been considering concerning the logical form of action sentences do not yield solutions to the problems with which we began. I have already pointed our that Kenny's problem, that verbs of action apparently have 'variable polyadicity', arises within the sentences that can replace 'p' in such formulas as 'x broughr it about that p'. An analogous remark goes for von Wright's more elaborate formula. The other main problem may be put as chat of assigning a logical form to action sentences that will justify claims that two sentences describe 'the same action'. Our study of some of the ways in which we excuse, Or attempt ro excuse, acts shows that we want to make infer­ ences such as chis: I flew my spaceship to the Morning Star, che Morning Star is identical with the Evening Star; so, I flew my spaceship to the Evening Star. (My leader told the not (0 go the Evening Star; 1 headed for the Morning Star not knowing.) But suppose we translate the action sentences along the lines suggested by Kenny or Chisholm or von Wright. Then we have somerhing like. 'I brought it about that my spaceship is on the Morning Star.' How can we infer, given the well-known identity, 'I broughr it abour that my spaceship is on the Evening Star'? We know that if we replace 'the Morning Star' by 'the Evening Srar' in, 'My spaceship is on the Morning Star' the truth-value will not be disturbed; and so if the Occurrence of this sentence in, 'I broughr it about that my spaceship is on the Morning Star' is trurh-hmctional, the inference is justified. But of COurse the occurrence can't be truth-hmctional: otherwise, from the facr that the 7 von Wright. op. cir., 23. 45 I brought about one actual state of affairs it would follow that I brought about every actual state of affairs. lt is no good saying that after the words 'bring it about that' sentences describe something between trum-values and propositions, say states of affairs. Such a claim must be backed by a semantic theory telling us how each sentence determines the state of affairs it does; otherwise the claim is empry. Israel Scheffier has put forward an analysis of sentences about choice that can be applied without serious modification to sentences about intentional acts.e Scheffier makes no suggestion concerning action sentences that do nor impute intention, and so has no solution to the chief problems I am discussing. Nevertheless, his analysis has a fearure I should like to mention. Scheffler would have us render, 'Jones intentionally buttered the toast' as, 'Jones made-true a that Iones-buttered-the-roasc inscription.' This cannot, for reasons 1 have urged in detail elsewhere,s be considered a finally satisfying form for such sentences because it COntains the logically unstructured predicate 'is a that Jones-buttered­ the-toast inscription', and there are an infinite number of such semancical pri­ mitives in the language. But in one respect, I believe Scheffler's analysis is clearly superior ro the others, for it implies that inrroducing the elemenr of intention­ aliry does not call for a reduction in the COntent of the sentence that expresses what was done intentionally. This brings out a faCt otherwise suppressed, that, to use Ourexample, 'Jones' turns up twice, Once inside and once outside the scope of the intensional operator. I shall return to this point. A discussion of the logical form of action sentences in ordinary language is to be found in the justly famed Chapter VII of Reichenbach's Elements o[Symbolic IO Logic. According to Reichenbach's doctrine, we may transform a sentence like (4) Amundsen flew to the North pole into: (5) (3x) (x consists in the fact that Amundsen Aew to the North Pole). The expression 'is an event that COnsists in the fact chat' is to beviewed as an operator which, when prefixed to a sentence, forms a predicate ofevents. Reichenbach does nor think of (5) as shOwing or revealing the logical form of (4), for he thinks (4) is unproblematic. Rather he says (5) is logically equivalent to (4). (5) has its coun­ terparr in a more ordinary idiom: (6) A flight by Amundsen to the North Pole took place. Thus Reichenbach seems to hold that we have two ways of expressing the same idea, (4) and (6); they have quite different logical forms, but they are logically equivalenr, one speaks lirerally of events while the other does nor. I believe chis ~ brad Scheffler. The Anatomy of In.quiry, 104-5. Donald Davidson, 'Theories of Meaning and Learnable Languages", 390--1. 10 Hans Reichenbach, Ekmems ofSymbolu Logic, § 48. 'I 46 view spoils much of the merit in Reichenbach's proposal, and chat we must abandon the idea that (4) has an unproblematic logical form distinct from that of (5) or (6). Following Reichenbach's formula for putting any action sentence inro the form of (5) we translate (7) Arnunsden flew to the North Pole in May 1926 47 ()' consists in the fact that (3x) (x consists in the fact that 2 + 3 = 5))'? And so on. Ir isn't clear on what principle the decision to apply the analysis is based. The second objection is worse. We have: (10) (3x) (x consists in the fact that I flew my spaceship to the Morning Star) and mro: (II) the Morning Star = the Evening Srar (8) (3x) (x consists in the fact that Amundsen flew Co the North Pole in May 1926). The fact that (8) entails (5) is no more obvious than that (7) entails (4); what was obscure remains obscure. The correct way to render (7) is: (9) (3x) (x consists in [he fact mar Amundsen flew to the North Pole and x took place in May 1926). But (9) does nor bear the simple relation to the standard way of interpreting (7) that (8) does. We do not know of any logical operation on (7) as it would usually be formalised (with a three-place predicate) that would make it logically equi­ valent to (9). This is why I suggest that we trear (9) alone as giving the logical form of (7). If we follow this sttategy, Kenny', problem of the 'variable poly­ adicity' of action verbs is on the way to soiunon: there is, of course, no variable polyadicity. The problem is solved in the natural way, by introducing events as entities about which an indefinite number of things can be said. Reichenbach's proposal has another attractive feature: it eliminates a peculiar confusion that seemed to attach to the idea that sentences like (7) 'describe an event'. The difficulty was thac one wavered between thinking of the sentence as describing or referring to that one flight Amundsen made in May 1926, or as describing a kind ofevent, or perhaps as describing (potentially?) several. A5 von Wtight pointed out, any number of events might be described by a sentence like 'Brutus kissed Caesar.' This fog is dispelled in a way I find entirely persuasive by Reichenbach's proposal that ordinary action sentences have, in effect, an exist­ ential quantifier binding the action-variable. \'Qhen we were tempted into chinking a sentence like (7) describes a single evenr we were misled: it does not describe any event at all. But if (7) is true, then there is an event that makes it true. (This unrecognized element of generality in action sentences is, I think, of the utmost importance in understanding the relation between actions and desires.] There are two objections to Reichenbach's analysis of acrion sentences: The first may noc be fatal. It is that as matters stand the analysis may be applied to any sentence whatsoever, whether it deals with actions, events, or anything else. Even '2+3=5' becomes '(3x) (x consisrs in the fact that 2+3=5)'. Why uot say '2 + 3 = 5' does not show ics true colours until pur through the machine? For that matter, are we finished when we get to the first step? Shouldn't we go on to '(3)') and we want to make the inference to (12) (3x) (x consists in the fact that I flew my spaceship to the Evening Star). The likely principle to jusrify the inference would be: (13) (x) (x consists in the fact that S+-+x consists in the fact that S') where '5" is obtained from '5' by substituting, in one or more places, a co-referring singular term. Ir is plausible co add that (13) holds if'S' and'S' are logically equivalent. But (13) and the last assumption lead to trouble. For observing that '5' is logically equivalent to 'j (y=)' & 5) = j ()'=)')' we get (14) (x) (x consists in the face that 5 f - I S) = j (y= y))). X consists in the fact that (j(y=)' & Now suppose 'R' is any sentence materially equivalent to '5': then 'j()'=)' & 5)' and 'y(y=)' & R)' will refer to the same thing. Subsriruring in (14) we obtain (15) (x) (x consists in the facr that 5 e-e X consists in che fact that (j()' = )' & R) =.Y<.r= y)), which leads co (16) (x) (x consists in the fact that 5 f - I X consists in the facr that R) when we observe the logical equivalence of'R' and :9(y=.r & R) = j(y=y)'. (16) may be interpreted as saying (considering that the sale assumption is that 'R' and '5' are materially equivalent) that all events that occur (= all events) are identical. This demonstrates, I think. that Reichenbach's analysis is radically defective. Now I would like to put forward an analysis of action sentences that seems co the to combine most of the merirs of the alternatives already discussed, and (Q avoid the difficulties. The basic idea is that verbs of action-verbs that say 'what someone did'<c-should be construed as containing a place, for singular terms or variables, that they do not appear (0. For example, we would normally suppose that 'Shem kicked Shaun' consisted in two names and a two-place predicate. I suggesr, though, that we thinkof'kicked' as a three-place predicate, and that the sentence to be given in [his form: (17) (3x) (Kicked(Shem, Shaun, .». If we try foe an English sentence that directly reflects this form, we run into difficulties. 'There is an evenr x such that x is a kicking of Shaun by Shern' is about the best I can do, but we must remember 'a kicking' is not a singular term. Given this English reading, my proposal may sound very like Reichenbach's; but of course it has quite different logical properties. The sentence 'Shem kicked Shaun' nowhere appears inside my analytic sentence, and this makes it differ from all the theories we have considered. The principles that license the Morning Srar-Evening Srar inference now make no trouble: they are the usual principles of extensionaliry. fu a result, nothing now stands in the way of giving a standard theory of meaning for action sen­ tences, in the form of a Tarski-rype truth definicion; nothing stands in the way. that is, of giving a coherent and constructive account of how the meanings [truth conditions) of these sentences depend upon their structure. To see how one of the troublesome inferences now goes through. consider (10) rewritten as the Morning Star is an eclipse of the Evening Star. Our ordinary ralk of events, of causes and effects, requires constant use of the idea ofdifferent descriptions of the same event. "When it is pointed our that striking the march was nor sufficient to light it, what is nor sufficient is nor the event, bur the descriprion of it-it was a dry march, and so on. And of course Kenny's problem of 'variable polyadicity', though he cakes ic to be a mark of verbs of acrion, is common to all verbs that describe events. It may now appear chat the apparent success of the analysis proposed here is due ro the facr that ic has simply omitted what is peculiar ro acrion sentences as conrrasred with ocher sentences abour events. Bur 1do nor think so. The concepr of agency contains two elements, and when we separare them clearly, I think we shall see that the present analysis has noc lefr anything our. The first of these two elements we try, rather feebly, to elicit by saying that the agent acts, or does something, insread of being acted upon, or having something happen ro him. Or we say that the agent is active rather chan passive; and perhaps try co make nse of the moods of the verb as a grammatical clue. And we may cry ro depend upon some fixed phrase like 'brings it abour that' or 'makes it the case that'. Bur only a lirrle thoughr will make ic clear thac there is no satisfactory grammatical rest for verbs where we wanr ro say there is agency. Perhaps it is a necessary condition of attributing agency charone argument-place in the verb is filled wirh a reference ro the agent as a person; it will nor do to refer ro his body, or his members, or to anyone else. Bur beyond that it is hard ro go. I sleep, I snore, 1 push buttons, I recite verses, 1 carch cold. Also others are insulted by the, struck by the, admired by the, and so on. No grammatical resr I know of, in terms of the things we may be said to do, of acrive or passive mood, or of any ocher sort, will separare our the cases here where we want ro speak of agency. Perhaps it is true that 'brings it about that' guarantees agency; bur as we have seen, many sentences that do attribute agency cannot be cast in this grammarical form. I believe the correct ching ro say abour this element in the concepr of agency is that it is simply introduced by cerrain verbs and nor by others: when we understand the verb we recognize whether or nor it includes the idea of an agenr. Thus, 'I fought' and 'I insulred him' do impure agency to the person referred to by the first singular rerm, 'I caughr cold' and, 'I had my thirceenrh birthday' do nor. In these cases, we do seem to have the following rest: we impure agency only where it makes sense ro ask whether the agent acred intentionally. Bur there are other cases, or so it seems to the, where we impure agency only when the answer ro the question whether the agent acred inrencionally is 'yes'. If a than falls down by accident or because a truck knocks him down, we do nor impure agency; bur we do if he fell down on purpose. This introduces the second element in checoncepr ofagency, for we surely impure agency when we say or imply thac the act is intentional. Instead of speaking of two elements in the concepr of agency, perhaps it would be berrer ro say there are 48 (18) (3x) (Flew(I, my spaceship, x) & Tofrhe Morning Star, x)). which, along with (11), entails (19) (3x) (Flew(I, my spaceship, x) & Tofrhe Evening Star, x)). It is nor necessary, in representing this argument, ro separate off the To-relation: instead we could have taken, 'Flew' as a four-place predicare. Bur that would have obscured another inference. namely that from (19) ro (20) (3x) (Flew(I, my spaceship, x)). In general, we conceal logical structure when we trear prepositions as integral parts of verbs; it is a merir of the presem proposal that it suggesrs a way of treating preposirions as contributing structure. Nor only is it good ro have the inference from (19) to (20); it is also good ro be able ro keep track of the common element in <fly ro' and 'Ry away from' and this of course we cannot do if we trear these as unstructured predicates. The problem that threatened in Reichenbach's analysis, that there seemed no clear principle on which ro refrain from applying the analysis ro every sentence, has a natural solurion if my suggesrion is accepted. Part of what we must learn when we learn the meaning of any predicare is how many places it has, and whac sorts of entities the variables thac hold these places range over. Some predicates nave an event-place, some do nor. In general, what kinds of predicares do have event-places? Wirhour pursuing this quesrion very far. I think it is evident that if action predicates do, many predicares mar have Iicrle relation to action do. Indeed, the problems we have been mainly concerned with are nor at all unique ro ralk of actions: they are common ro ralk of events of any kind. An acrion of flying ro the Morning Star is identical with an action of Rying ro the Evening Star; bur equally, an eclipse of two ways we can imply that a person acted as an agent: we may use a verb that implies it directly, or we may use a verb that is non-committal, and add that the act was intentional But when we rake the second course, it is important not to trunk of the inreutionaliry as adding an extra doing of the agenr, we must not make the expression that introduces intention a verb of action. In particular, we cannot use "intentionally brings it about that' as the expression mar introduces intention, for 'brings it about mar' is in itself a verb of action, and imputes agency. but it is neutral with respect to question whether the action was intentional as described. This leaves the question what logical form (he expression that introduces intention should have. It is obvious, I hope. that adverbial form must be in some way deceptive; intentional actions are not a class of actions, or, to pm (he point a little differendy, doing something intentionally is noc a manner of doing k. To say someone did something intentionally is to describe the action in a way that bears a special relation co the beliefs and artirudes of the agene; and perhaps further to describe the action as haviug been caused by those beliefs and artirudes.!' Bur of course to describe the action of the agenr as having been caused in a certain way does not mean that the agent is described as performing any further action. From a logical poinr of view, there are thus these imporranr conditions governing the expression that introduces intention: it must nor be interpreted as a verb of action, it must be intensional, and the intention must be tied to a person. I propose then that we use some form of words like 'It was intentional of x that p' where 'x' names the agem, and 'p' is a sentence that says the agent did somerhing. lr is useful, perhaps necessary, that the agenc be named rwice when we try co make logical form explicit. lr is useful, because it reminds us that co describe an action as intentional is to describe the action in the lighc of certain attitudes and beliefs of a particular person; it may be necessary in order co illuminate what goes on in those cases in which the agenc makes a mistake about who he is. [t was intentional of Oedipus, and hence of the slayer of Laius, that Oedipus sought the slayer of Laius, but it was not intentional of Oedipus [the slayer of Laius) mac the slayer of Laius sought the slayer of Laius. the nexr year under the editorship of Nicholas Rescher. At the conference, E. J. Lemmon, H.-N. Casrafieda, and R M. Chisholm commenred on my paper, and I replied. Ir is my replies (as rewrirren for publication) that appeat here (somewhat further edited). In November of 1966 The Universiry ofWestetn Ontario held a colloquium on Fact and Existence at which I replied to a paper 'On Evenrs and Evenr-Descriprions' by R M. Marrin. Both his paper and my reply were published by Blackwells in 1969 under the editorship of Joseph Margolis. Martin had nor seen my Essay 6 when he wrore his paper, and in fairness to him it should be noted that his views on the semantics of sentences abour events have been modified subsequently. I reprint my reply ro him for the light it throws on my views, nor on his. Finally, the journal Inquiry devoted its Summer, 1970, issue to the subject of action, and it contained ['NO criticisms of my work. One was by Carl G. Hedman, 'On the Individuation of Actions', the other was by James Cargile, 'Davidson's Notion of Logical Form'. My replies were primed under the title 'Action and Reaction', and are reprinted here. 50 the the # CRITICISM, COMMENT, AND DEFENCE The above Essay brought in irs wake a number of comments and criticisms from ocher philosophers, and in a few cases I responded. In chis appendix to the Essay, I bring together some of my replies, for although they repeat much that em be found elsewhere in this volume, they often pur a point in a newwayor modifyan old one. I havedone someediting (0 make these replies intelligible wirhour the comments to which they were replies, but of course some readers may want ro look up the original work of the critic or commentator. This Essaywas first read at a three-day conference on The Logic ofDecision and Action held at the University of Pittsburgh in March 1966; the proceedings were published II See Essay I. 51 A. Reply to Lemmon on Tenses. My goal was to gee clear about the logical form of acrion sentences. By action senrences I mean sentences in En.glish about actions. Ar the level of abstraction on which the discussion moved, little was said that would not apply co sentences abour actions in many ocher languages if it applied to sentences in English. The ideal implicit in the paper is a theory that spells our every element of logical form in every English sentence about actions. I dream of a theory that makes the transirion from the ordinary idiom to canonical notation purely mechanical, and a canonical notation rich enough ro caprure, in its dull and explicit way, every difference and connection legirimately considered the business of a theory of meaning. The poinr of canonical norarion so conceived is not to improve on somerhing left vague and defective in narural language, but to help elicit in a perspicuous and general form the understanding of logical grammar we all have that conscirures (part of) our grasp of our native tongue. In exploring the logical form of sentences about actions and events, I con­ centrated on certain features of such senrences and neglected orhers. One feature I torally neglected was that of tense; Lemmon is absolutely right in pointing our mar some of the inferences I consider valid depend (in a standard way we have become hardened co) on fudging with respect to time. The necessity for fudging shows that we have failed co bring OUt a feature of logical form. I accepr the implication that my own account was incomplete through neglect of the element of cense, and I welcome Lemmon's attempt to remedy the situ­ arion. I am very much in sympathy with the methods he apparently thinks appropriate. Logicians have almost always assumed thac the demonstrative element in natural languages necessarily resists serious semantic trearment, and they have accordingly cried to show how ro replace tensed expressions wirh ochers containing no demonstrative feature. What recommends this srraregy co logicians {the elimination of sentences with variable truth-values) also serves co show that it is not a strategy for analysing the senreuces of English. Lemmon makes no attempt to eliminate the demonstrative element from his canonical noracion (subsriruring <before now' for the past tense is a way of articulating the relation between the different tenses of the same verb, not of eliminating the demonstrative element). At the same time, he obviously has in mind that the structure he introduces must lend itself to formal semantic treatment. It is simply a mistake, Lemmon correctly assumes, to think that senrences with a demonstrative element resist the application of systematic semantic analysis. and counts his blessings. fue these all the same event? I suspccc there may be a good argument ro show they are; but until one is produced, we must suspend judgement on Lemmon's interesting proposal.'? 52 B. Reply to Lemmon on Identity Condition; for Events. If we are going to quantify over evenrs and interpret singular terms as referring to events, we need to say something about the conditions under which expressions of the form 'a= b' are true where 'a' and 'h' refer, or purport to refer, co events. This is a difficult and complex subject, and I do not propose to do more here than comment briefly on some of Lemmon's remarks. But I think he is right to raise the issue; before we decide that our general approach to the analysis of event senrences is correct, there must be much more discussion of the criteria for individuating and idenrifying events. Lemmon is surely right that a necessary condirion for the identity of events is that they rake place over exactly the same period of time. He suggests, very tentatively, that if we add that the events 'rake the same place', then we have necessary and sufficient conditions for identity. I am nor ar all certain this suggestion is wrong, but before we accept it we shall need to remove two doubts. The first centres on the question whether we have adequate criteria for the location of an event. As Lemmon realizes, his principle that if R...a,z) then a is a participant in z, cannot be true for every F (rake 'F' as 'took place a thousand miles south of' and 'a' as 'New York'; we would not, presumably, say New York participated in every event that took place a thousand miles south of New York). And how do we deal with examples like this: if a than's arm goes up, the event takes place in the space-time zone occupied by the arm; but if a than raises his arm, doesn't the event fill the zone occupied by the whole than? Yet the events may be identical. If a than drives his car into his garage, how much of the garage does the event occupy? All of it, or only the zone occupied by the car? Finally, if events are to have a location in an interesting sense, we need to see what is wrong with rue following argument: if an event is a change in a certain object, then the event occupies ar least the zone occupied by the object during the time the event takes place. But if one object is part of another, a change in the first is a change in the second. Since an object is part of the universe, it folloW'S that every event that is a change in an object rakes place everywhere (rhroughonr the uni­ verse). This argument is, I believe, faulry, but it must be shown to be so before we can talk intelligibly of the locarion of events. The second doubr we must remove if we are to identify events with space-rime zones is that there may be two differenc events in the same zone. Suppose that during exactly the same rime interval Jones catches cold, swims the Hellespont, 53 C. &ply to Castatieaa on Agmt and Patient. Castaneda very usefully summarizes the main points in my paper, and raises some questions abour the principles that ace implicit in my examples. My lack of explicitness has perhaps misled him in one respect. It is not part of my programme ro make all entailments matters of logical form. 'x > y' entails 'y < x', bur not as a marrer of form. 'x is a grand­ farber' entail s 'x is a father', hut not a." :l matter of form. And 1 think there Me cases where, to use Castaneda's words, 'a larger polyadic action statement entails a shorter one which is a part of it' and yet this is not a matter of logical form. An example, perhaps, is this: 'I flew my spaceship' may entail, 'I flew', but if it does, it is not, I think. because of the logical form of the sentences. My reason for saying this is that I find no reason ro believe the logical form of 'I flew my spaceship' differs from that of"I sank the Bismarck', which does not entail 'I sank' though it does happen to entail 'The Bismarck sank'. A comparison of these examples oughr ro go a long way ro persuade us that simple sentences containing transitive verbs do not, as a marrer of logical form, entail sentences with intransitive verbs. Putting sentences in the passive will nor radically change things. If I sank the Bismarck. the Bismarce was sunk and the Bismarck sank. But 'The Bismarck was sunk' and 'The Bismarck sank' are not equivalent, for the econd does nor entail the first. Thus even if we were to accept Cascafieda's view that 'The Bismarck was sunk' has a logically intransitive verb, the passivity of the subject remains a feature of this verb distinguishing it from the verb of 'The Bismarck sank'. Thus there is no obvious economy in Casrafieda's idea of indicating the distinction between agent and patient by position in verbs of action. There would be real merit, however, in keeping track of the relation between 'The Bismarck was snnk' and 'The Bismarck sank', which is that the first encails the second; but Castafieda's nocarion does not help with this. Castaneda would have us put 'The King insulted the Queen' in this form: (3x) (Insulted (the King, x) & Insulted (x, the Queen) What is this relation, that relares a person and an event or, in the same way, an event and a person? 'What logical feature is preserved by this form that is nor as well preserved, and less misleadingly, by (3x) (Insulted (the King, x) & Was insulted (the Queen, x)) [i.e., 'There was an event that was an insulnog by the King and of the Queen')? But I remain unconvinced of the advantages in splirring transitive verbs up in this way. The gain is the entailment of 'My spaceship was flown' by 'I flew my rz For more on {he individuation of events, see Essay 4. spaceship'; the loss becomes apparent when we realize that 'My spaceship was Hown' has been interpreted so as not to email 'Someone flew my spaceship".'? problem then looks, even with Casrafieda's revision, much like the problem of analysing sentences about other propositional attitudes. S4 D. R£ply to Castaneda on Prepositions. My proposal to treat certain prepositions as verbs does seem odd, and perhaps it will rum out to be radically mistaken. But I am not quite convinced of this by what Casrafieda says. My analysis of '1 flew my spaceship to the Moening Star does entail '(3x) (To (the Moening Stat, xl)', and Castaneda turns this into words as 'There was a to the Morning Star'. But I think we can do better: 'There was an event involving motion toward the Morning Scar' or 'There was an eveut characterized by being to (toward) the Morning Scar'. Castafieda himself proposes 'flying-to', which shows he understands the SOrt of verb I have in mind. But of course I don't like 'flying­ co' as an unstructured predicate, since this breaks the connection with 'walking­ co' and its kin. Castaneda complains, of my use of plain 'co', that there are many different senses ofro'. depending on the verb it is coupled with. Let us suppose we undecsrand this difficulty, with irs heavy dependence on the concept of sameness of relation. I shall meet Casrafieda half-way by inrroducing a special form of 'to' which means, 'motion-toward-and-rerminaring-ar'; this is more general than his 'flying-to' and less general than my former, plain, 'to'. And I assume that if Castaneda understands '(3x) (flying-to [the Morning Srar, x»' he will understand '(3x) (Mocion-towards-and-terminating-at (the Morning Star, x)', for this verb differs from his merely in degree of generality. E. Reply to Castaneda on Intention. First Castaneda makes the point, also made by Lemmon, that I would have done well to make basic a notion of intention that does not imply that whar is intended is done. I think they ate tight in this. Castaneda then goes on to claim that my analysis of 'Oedipus intentionally sought the slayer of Laius' as 'It was intentional of Oedipus that Oedipus sought the slayer of Laius' is faulty because the first sentence might be true and the second false if Oedipus failed to know that he was Oedipus. Casrafieda suggests that to correct the analysis, we should put 'he (himself)' for the second occur­ rence ofOedipus'. In my opinion, Castaneda is right both in his criticism and in his correction. There is, as he maintains, an irreducibly demonstrative element in the full analysis of sentences about intentions, and my proposal concealed it. Perhaps I should remark here that I do not think it solves the problem of the analysis of sentences about intention to put them in the form of 'It was inren­ rional of x that p '; such. sentences are notoriously hard co bring under a semantical theory. I view putting such sentences in this form as a first step; the U On the general poinr raised by Castaneda, whether transirive verhs email their inrrarnicive counterparrs as a marrer of logical form, and {a related matter} whether passive transformation is a matter of logical form, I would now side with Casrafieda. SS F. Rrply to Chisholm on Making Happen. I am happy to have Chisholm's careful comments on the section of my paper that deals with his views; he has made the realize that I had not appreciated the subtlety of his analysis. It is not clear to the now whether, on the issues discussed in my paper, there is any disagreement herween us. Let the formulate the questions that remain in my mind as I now understand them. I assume that since he has not attempted an analysis of event sentences gen­ erally, and the p'in, 'He made it happen that p'refers to an event, Chisholm does nor dispute my claim that he has not solved the main problems with which I deal in my paper. The question is rather whether there are any special problems in his analysis of action and agency. The first difficulty I raised for Chisholm was whether he could produce, in a reasonably mechanical way, for every sentence of the form 'He raised his arm' or 'Alice broke the mirror', another sentence of the form 'He made it happen that p' or 'Alice made it happen that r' where does not have the agent as subject. Chisholm shows, I think, that there is a chance he can handle 'He raised his arm' and 'Alice broke the mirror' except, perhaps, in the case where intention is not involved at all, and this is not under discussion. The cases I would now worry about are rather 'He walked to the corner', 'He carved the roast', 'He fell down', or 'The doctor removed the patient's appendix', In each. of these examples I find I am puzzled as to what the agent makes happen. My problem isn't that I can't imagine that there is some bodily movement that the agent might be said to make happen, bur that I see no way automatically to produce the right description from the original senrence. No doubt each time a than walks to the corner there is some way he makes his body move; but of course it does not follow that there is some one way he makes his body move every rime he walks to the corner. The second difficulty I raised for Chisholm concerned the question whether his analysis committed him to 'acts of the will', perhaps contrary to his own intentions. It is clear that Chisholm does not want to be committed to acts of the will, and that his analysis does not say that there are acts of the will but I believe the question can still be raised. It can be raised by asking whether the event said to occur in <Jones made it happen chat his arm went up' is the same event or a different one from the event said to occur in 'Jones's arm Went up'. Ir seems to the Chisholm can avoid acts of the will only by saying the events are the same. He is free to say this, of course, and then the only objection is terminological. And 'Jones's arm went up' would then be, when it was something Jones made happen, a description of an acrion. At the end of his reply, Chisholm conjectures that I may nor agree with him that agents may be causes. Actually I See no objection to saying that agents are causes, but I think we understand this only when we can reduce it to the case of 'I an event being a cause; and here I do disagree with Chisholm. He asks how we are to render 'He made it happen that p' in terms merely of relations among events. If the problem is that of giving the logical form of action sentences, then I have made a suggestion in present paper. If the problem is to give an analysis of the concept of agency using other concepts, then I am not sure it can be done. Why must it be possible? rather the doings and havings of relations and properties of those objects; in two words, the facts. It Seems that a fact contains, in appropriate array, just the objects any sentence it verifies is about. No wonder we may not be satisfied with the colourless 'corresponds to' for the relation between a true sentence and irs face; there is something, we may feel, to be said for 'is true to', 'is faithful to', or even 'pictures'. To specify a fact is, then, a way of explaining what makes a sentence true. On the other hand, simply to say that a sentence is true is to say there is some fact or other to which it corresponds. On this account, is true to (or corresponds to) the facts' means more literally corresponds to a fact'. Just as we can say there is a fact to which a sentence corresponds when the sentence is true, we can also say there is a true sentence corresponding to a particular fact; this larter comes down to saying of the facr that it is one. English sentences that perhaps express this idea are 'That the cat has mange is a fact' and 'It is a fact that London is in Canada', and even 'London is in Canada, and that's a fact.' It is evident that we must distinguish here between idioms of at least two sorts, those that attribute fact­ hood to an entity (a facr), and those that say of a sentence that it corresponds to a fact (or 'the facts'). Let us use the following sentences as our samples of the two sorts of idiom: 56 the G. Reply to Martin. There is a more or less innocent sense in which we say that a sentence refers co, describes, or is about, some enriry when the sentence contains a singular term that refers to that entity. Speaking in this vein, we declare that, 'The cat has mange' refers to the cat, 'Caesar's death was broughr on by a cold' describes Caesar and his death, and 'Jack fell down and broke his crown' is about Jack and Jack's crown. Observing how the reference of a complex singular term like 'Caesar's death' or 'Jack's crown' depends systematically on the reference of the contained singular term ('Caesar' or 'Jack') it is tempting co go on co ask what a sentence asa whole is about (or refers co, or describes), since it embraces singular terms like 'Caesar's dearh' in much the way 'Caesar's death' embraces 'Caesar'. There is now a danger of ambiguity in the phrases 'what a sentence refers co' or 'what a sentence is about': let us resolve it by using only 'refers co' for the relation between patent singular terms and what they are about, and only 'corresponds co' for the relation between a sentence and whar it is about. Just as a complex singular rerm like 'Caesar's death' may fail of reference though contained singular terms do not, so a sentence may not correspond ro anything, even though its contained singular terms refer; wiruess 'Caesar's death was brought on by a cold'. Clearly enough, it is JUSt the true sentences that have a corresponding entity; 'The cat has mange' corresponds to the eat's having of mange, which alone can make it true; because there is no entity that is Caesar's death having been brought on by a cold, 'Caesar's death was broughr on by a cold' Is not true.t't These gerunds can get to be a bore, and we have a way around them in 'fact that' clauses. The entity to which 'The cat has mange' corresponds is the eat's having of mange; equivalently, it is the face that the cat has mange. Quite generally we get a singular term for the entity to which a sentence corresponds by prefixing 'the face that' co the sentence; assuming, of course, there are such entities. Philosophical inreresr in facts springs partly from their promise for explaining truth. It's clear that most sentences would not have the truth value they do if the world were not the way it is, but what in the world makes a sentence true? Not just the objects to which a sentence refers (in the sense explained above), bur 14 For simpliciry's sake I speak as if truth were a propeny of sentences; more properly if is a relation berween a sentence, a person and a lime. (We could equally think of truth as a property of utterances, of tokens, or of speech acts.} l assurne here that when truth is anribured to a sentence, or reference to a singular term, the suppressed relarivizarion to a speaker and a time could always be supplied; if so, [he ellipsis is harmless. ~ s 57 s (I) That the cat has mange is a fact, (2) The sentence, 'The car has mange' corresponds to a fact. Professor Martin says his analysis is intended to apply to sentences of the form 'So-and-so is a fact' where I suppose 'so-and-so' is to be replaced, typically. by a that-clause, and he suggests we interpret such sentences as saying of a sentence that it is true {non-analytically-c-but [shall ignore this twist). Which of the two idioms represented by (1) and (2) is Marrin analysing? The senrences Marrin says he wants to analyse apparently have the form of (1); his analysis, on the other hand, seems suited to sentences like (2). Suppose we tty the second rack. Then Martin's proposal comes to this: where we appear to say of a sentence that there is a fact to which it corresponds we might as well say simply that the sentence is true. There is nothing in this yet to offend the most devoted friend of facts. Marrin has not explained. away a singular term that ever purported to refer to a fact; On his analysis, as on the one the friend of facts would give, the only singular term in, 'The sentence "The cat has mange" corresponds to the facts' refers to a sentence. Nor would the friend of faces want to deny the equivalence of is true' and 's corresponds to a face' when's' is replaced by the name or description of a sentence. The friend of facts would, however, balk at the claim that this shows how, in general, to eliminate quan­ tification over facts, or singular terms that refer to them. He would contend that it is only sentence (1) with irs apparent singular term 'that the cat has mange' which clearly calls for an ontology of facts. Martin may reply that it is sentence (I) he had his eye on from the start. This reply leaves (2) out in the cold unless. of s 59 The Essential Davidson The Logical Fonn ofAction Sentences course, (1) and (2) can be given the same analysis. The partisan of faces will resist this idea. and plausibly, I think, on the ground that (2) is merely an existential more inreresdng: generalizarion of and 'fact' as synonyms, or so he says.t? The pressure to treat events as facts is easy, in a way, co understand: both offer themselves as what senrences-c-sorne sentence at ieasr-c-reter to or are about. Causal laws, we are cold, say that every event of a certain sort is followed by an event of another SOft. According to Hempel, the sentence, 'The length of copper rod r increased between 9.00 and 9.01 a.m.' describes a particular evenr.w In philosophical discussion of action these days we very often learn such things as that 'Jones raised his arm' and 'Jones signalled' may describe the same action, or that an age-or may perform an action inren­ rionally under one description and not under another. It is obvious that most of the sentences usually said to be about events contain no singular terms that even appear to refer to events, nor are they normally shown to have variables that rake events as values when put over into ordinary quantificarional noration. The natural conclusion is that sentences as wholes describe or refer to events, JUSt as they were said to correspond as wholes to facts, and this. as we have seen, must he wrong. Marrin does not fall inro this common trap, for although he COnstructs singular rerrns for events from the marerial of a senrence, he does nor have the sentence itself refer ro an event. His procedure is to view an event as an ordered a-tuple made up of the extensions of the n - I singular terms and the n - l vplace pre­ dicate of a true sentence. So, 'Leopold mer Stephen on Bloomsday' gives us the singular term, '(M, I, 5, b)' which refers eo Leopold's meeting of Stephen on Bloomsday provided Leopold did meet Srephen on Bloomsday. [ shall ignore the further step by which Martin eliminates ordered e-ruples in favour of virtual ordered e-rupies: the difficulties about to appear are independent of that idea.>' Given the premise that Bloomsday is 16 June 1904, we may infer from, 'Leopold mer Stephen on Bloomsday' the sentence, 'Leopold mer Stephen on 16 June 1904', and, events being the ordered. x-ruples they are, Leopold's meeting of Stephen on Bloomsday is identical with Leopold's meeting of Stephen on 16 June 1904. This is surely as it should be so far; bur not, I'm afraid, farther. Nor every encounter is a meeting; according to the Story, some encounters between Leopold and Stephen are meetings and some are not. But then by Martin's account no meeting is identical with an encounter, though between the same individuals and at the same time. The reason is that if any encounter IS not a meeting, (E, I, s, b) is not idenrical with (M, l; s, b). Indeed, Leopold's first mccring with Stephen on Bloomsday in Dublin cannot be identical with Leopold's first meeting with Stephen on Bloomsday (since a fourplace predicate can't have the same extension as a three-place predicate); nor can a meeting between Stephen and Bloom be identical with a meeting bcrween Bloom and Stephen (since entities will be ordered in a different way). No stabbing can be a 58 the (3) The sentence, 'The cat has mange' corresponds to the face that the cat has mange. Here Martin's attempt to treat faces as sentences cannot be made co work without reducing (3) co the statement that the sentence, 'The cat has mange' corresponds to itself, and this cannot be right since (3), like (2), is clearly srmantical in character; it relates a sentence to the world. Martin recognizes the semantic thrusr in calk of faces, but docs uot notice that it cannot be reconciled with his analysis of (I). Marrin's thesis chat we do not need an oncology of faces could still be saved by an argument co show that there is at most one facr, for the interest in raking sentences like (3) as containing singular terms referring to facts depends on the assumption that there is an indefinitely large number of different facts to be referred ro: if there were only one, we could submerge reference to it into what might as well be considered a one-place predicate. IS And an argument is handy, thanks to F rege, showing that if sentences refer ar all, all true sentences must refer to the same thing.'? We may then with easy conscience side with Marrin in viewing 'corresponds to a face", when said of a sentence, as conveying no more than 'is true'. What should we say of the senrences like (1) that appear to attribute facrhood to entities? As we have seen, such sentences cannot be analysed as being about sentences. Bearing in mind the unity of fact, we might say (l ) affirms The Grear Fact, or tells The Truth, byway of one of its infiniry of rags, 'The car has mange.' We could equally well accept the universe with 'Thar London is in Canada is a fact.' Equivalently, we could have sim ply said, 'London is in Canada.' So, on my accounr, 'The sentence "The car has mange" corresponds to the faces' corncs our 'The sentence "The car has mange" is true', but 'That the cat has mange is a fact' comes out just 'The cat has mange'; nor at all the same thing. I? It is often assumed or argued (rhongh nor by Marrin) that events are a species of fact. Austin, fat example, says, 'Phenomena, events, situations, states of affairs are commonly supposed to be genuinely-in-the-world.... Yet surely of all these we can say that they are filets. The collapse of the Germans is an event and is a fuce-was an event and was a fact'.I 8 Reichenbach even treats the words 'event' l~ For a more general trcatment of'on,ologica.l reducnon' by incorporation of a finire number of singular terms into predicates, see Quine's 'ExiHence and Quanoficacon' and 'Onrclogical Reduction and the World of Numbers', 203. 16 For the argumenc, see Essay 2. For the argumenl and discussion, see A. Church, Introduction (Q MllrhnTlllriud ugic, 24-5. 17 I think that failure to observe {he disrincrion berween these two cases is the cause of some of the endless debate whether attributions of trurh are redundant. 18 J. L. Austin, 'Un&it ro has', 104. Hans Reichenbach, Flemerus ofSymholir I..ogir. 269_ Carl Hempel, Aspects tJfScientific frpLznation, 421. Zl Substantially the same analysis of events 25 Marrin's has been given by ]aegwon Kim, 'On the Psycho-Physical ldenriry Theory'. Kim does not take the extra step from real to virtual e-ruples. 19 20 60 The Essential Davidson killing and no killing can be a murder, no arm-raising a signalling, and no birthday party a celebration. I protest. Marcin's conditions on identity of events are clearly not necessary, bur are they perhaps sufficient! Again I think answer is no. Marrin correcdy remarks on his analysis the expressions that are supposed to refer co events refer to one enriry at most; bur are these entities the events they should be? Suppose Leopold met Stephen more than once on Bloomsday; what unique meeting does Marrin's ordered a-tuple pick our? 'Leopold's meeting with Stephen on Bloomsday', like Marcin's <{M, I, s, b)', is a true singular term. But there is this difference, that the first refers co a meeting if it refers co anything, while (he second does nor. Being more specific about time will nor really mend matters: John's kissing of a girl at precisely noon is not a unique kissing if he kissed two girls simultaneously. Marrin's method cannot be systematically applied to form singular terms guar­ anteed to pick out a particular kissing, marriage, or meering if anything; but this is easy, with gerund phrases, in English. Martin's mistake is natural, and it is connected with a basic confusion abour the relation between a sentence like 'Leopold met Stephen on Bloomsday' or 'Caesar died' and particular events like Leopold's meeting with Stephen on Bloomsday or Caesar's death. The mistake may be encapsulated in the idea (common to Martin and many others) that 'Leopold met Stephen on Blooms­ day' comes to the same as 'Leopold's meeting with Stephen on Bloomsday occurred' or that 'Caesar died' may be rendered 'Caesar's death took place'. 'Caesar's death', like 'Leopold's meeting with Stephen', is a true singular term, and so 'Caesar's death rook place' and 'Leopold's meeting with Srephen occurred' are true only if there was just one such meeting or death. But 'Caesar died' is true even if Caesar died a thousand deaths, and Leopold and Stephen may meet as often as they please on Bloomsday without falsifying 'Leopold met Stephen on Bloomsday.' A sentence such as 'Vesuvius erupted in A.D. 79' no more refers to an individual event than There's a By in here' refers to an individual By. Of course there may be JUSt one emption that verifies the first sentence and just one By that verifies the second; but that is beside the point. The point is that neither sentence can properly be interpreted as referring or describing, or being about, a particular eruption or By. No singular term for such is in the offing. 'There's a By in here' is existential and general with respect to flies in here; 'Vesuvius erupted in A.D. 79' is existential and general with respect to eruptions of Vesuvius in A.D. 79-if there are such things as eruptions, of course. Here I am going along wirh Ramsey who, in a passage quoted by Martin, wrote, "That Caesar died" is really an existential proposition, asserting the existence of an event of a certain sort, thus resembling "Italy has a King", which asserts the existence of a than of a certain sorr. The event which is of that sort is called the dearh of Caesar, and should no more be confused with the fact that Caesar died than the King of Iraly should be confused wirh the fact that Italy has the that 61 a King. '22 This seems to the nearly exactly right: facts, if such there are, corres­ pond to whole sentences, while events, if such there are, correspond to singular terms like 'Caesar's death', and are quantified over in sentences such as 'Caesar died.'23 Martin says he doubts that 'Caesar died' must, or perhaps even can, be con­ strued as asserting the existence of an event of a certain sort. I want to demon­ strate briefly first that it can, and then, even more briefly, why I think it must. It can be done by providing event-verbs with one more place than we generally think necessary, a place for events. I propose that 'died' in 'Caesar died' be taken as a two-place predicate, one place for 'Caesar' and another for a variable ranging over events. The sentence as a whole then becomes '(3x) (Died (Caesar, x))', that is, there ex.isrs a Caesar-dying event, or there exists an event that is a dying of Caesar. There is no problem in forming a singular term like 'Caesar's death' from these materials: it is '(IX) (Died (Caesar, x))'. We may then say truly, though this is nor equivalent co 'Caesar died', that Caesar died JUSt once: '(3y) (y= (IX) (Died (Caesar, x)))'; we may even say Caesar died Caesar's death: 'Died (Caesar, (IX) (Died (Caesar, x)))'. This gives us Some idea what it would be like to treat events seriously as individuals, with variables ranging over them, and with corresponding singular terms. It is clear, I think, that none of the objections I have considered to Reichenbach's, Kim's, or Marrin's analyses apply to the present snggesrion. We could introduce an ontology of events in this way, bur of course the question remains whether there is any good reason to do so. I have already mentioned some of the contexts, in (he analysis of action, of explanation, and of causality in which we seem to need to talk of events; still, faced with a basic ontological decision, we might well try to explain the need as merely seeming. There remains however a clear problem that is solved by admitting events, and that has no other solution I know of. The problem is simple, and ubiquitous. It can be illustrated by pointing Out that 'Brutus stabbed Caesar in the back in the Forum with a knife' entails 'Brutus stabbed Caesar in the back in the Forum' and both these entail 'Brutus stabbed Caesar in the back' and all these entail 'Brutus stabbed Caesar'; and yet OUr common way of symbolizing these sentences reveals no logical connection. It may be thought the needed entailments could be supplied by interpreting 'Brutus stabbed Caesar' as elliptical for 'Brurus stabbed Caesar somewhere (in Caesar) somewhere (in the world) with something', but this is a general solution only if we know some fixed number of places for the predicate 'stabbed' large enough to Ramsey, F. P., Foundauons ofMathemd.tics, 138ff. Ausrin blundered when he thoughr a phrase like '[he collapse of [he Germans' conld unambiguously refer ro a face and to an event. Zeno Veudler very shrewdly uncovers the error. remarking that 'in as much as [he collapse of [he Germans is a face. it can be memioned or denied, it can be unlikely or probable, it can shock or surprise us; in as much as it is an event, however, and net a fan, it can be observed and followed, it can be sudden, violent, or prolonged, it can occur, begin. lasr and eud.' This is from 'Comments' by Vendler (on a paper by Jerrold Katz). 11 U Th~ 62 Essential Davidson accommodate all evenrualities. It's unlikely we shall succeed, for a phrase like 'by' can introduce an indefinitely large number of modifications, as in 'He hung the picture by putting a nail in the wall, which in turn he did by hitting the nail with a hammer. which in turn he did by... .'24 Intuitively, there is no end to what we can say about the causes and consequences ofevents, our theory of language has gone badly astray if we must treat each adverbial modification as introducing a new place into a predicate. The problem, you can easily persuade yourself, is not peculiar to verbs of action. My proposed analysis of sentences with event-verbs solves this difficulty, for once we have events to talk about, we can say as much or as little as we please about them. Thus the troublesome sentence becomes (not in symbols, and not quite in English); 'There exists an event that is a stabbing of Caesar by Brutus event, it is an into the back of Caesar event, it took place in the Forum, and Brutus did it with a knife.' The wanted entailments now go through as a matter of form. Before we enthusiastically embrace an ontology ofevents we will want to think long and hard about the criteria for individuating them. I am myself inclined to think we can do as well for events generally as we can for physical objects generally (which is not very well), and can do much better for sorts of everus.Iike deaths and meetings, just as we can for sorts of physical objects, like tables and people. But all this must wair. 2 S Meanwhile the siruarion seems to the to be this: there is a lot of language we can make systematic sense of if we suppose events exist, and we know no promising alternative. The presumption lies with events. H. Reply to Cargile. I suggested that sentences about events and actions be construed as requiring an ontology of particular, unrepeacable, dated events. For example. I argued that a sentence like <Lucifer fell' has the logical form of an existential quantification of an open sentence true of falls of Lucifer, the open sentence in turn consisting of a two-place predicate true of ordered pairs of things and their falls, and the predicate places filled with a proper name ['Lucifer") and a free variable (bound by the quantifier]. [ did not explain in derail what I meant by logical form, though I did devote some paragraphs to the subject. I suppose I thought the problems set, the examples and counter­ examples offered, the arguments given and the answers entertained would, taken wich the tradition and my hints, make the idea clear enough. I was wrong; and in retrospect I sympathize with my misundersranders. I will try to do better. Logical form was invented to contrast with something else mar is held to be apparent but mere: the form we are led to assign to sentences by superficial analogy or traditional grammar. What meets the eye or ear in language has the l4 I am indebted to Daniel Bennerr for the example. Z) See Essay 4. 63 charm, complexity, convenience, and deceir of other conventions of the market place, but underlying it is the solid currency ofa plainer, duller structure, without wit but also without pretence. This true coin, the deep structure, need never feature directly in the transactions of real life. As long as we know how to redeem our paper we can enjoy the benefits of credit. The image may help explain why the distinction between logical form and surface grammar can flourish without anyone ever quite explaining it. But what can we say to Someone who wonders whether there is really any gold in the vaults! I think the concept oflogical form can be clarified and thus defended; bur the account I shall offer disclaims some of what is implied by the previous paragraph. wrhat do we mean when we ~ay that 'W'halcs arc mammals' is a quantified sentence? James Cargile suggests that the sentence is elliptical for 'All whales are mammals' (or 'Some whales are mammals') and once the ellipsis is mended we see that the sentence is quantified. Someone interested in logical form would, of course, go much further: he would maintain that 'All whales are mammals' is a universally quantified conditional whose antecedent is an open sentence true of whales and whose consequent is an open sentence true of mammals. The contrast with surface grammar is striking. The subject-predicate analysis goes by the board, 'all whales' is no longer neared as a unit, and the role of 'whales' and of 'mammals' is seen, or claimed. to he predicarive. What can justify this astonishing theory? Part of the answer-the part with which we are most familiar-is that inference is simplified and mechanized when We rewrite sentences in Some standardized notation. If we want to deduce 'Moby Dick is a mammal' from 'All whales are mammals' and 'Moby Dick lS a whale', we need ro connect the predicate 'is a whale' in some systematic way with a suitable feature of 'All whales are mammals'. The theory of the logical form of this sentence tells us how. Words for temporal precedence. like 'before' and 'after', provide anomer example. 'The inflation came after the war' is simple enough, at least if we accept events as entities, but how abouc 'Earwicker slept before Shem kicked Shaun'? Here (before' connects expressions with the gramrnarical form of sentences. How is this 'before' related to the one that stands between descriptions of events? Is it a sentential connective, like 'and'? 'Earwicker slept before Shem kicked Shaun' does entail both 'Earwicker slept' and 'Shem kicked Shaun'. Yet clearly 'before' is not truth-functional, since reversing the order of the sentences does not preserve truth. The solution proposed by Frege has been widely (if not universally) accepted; it is, as we all know, co think of our sentence as doubly quantified by existential quantifiers, to introduce extra places into the predicates to accommodate variables ranging Over rimes, and to interpret 'before' as a two-place predicate. The result, roughly, is: 'There exist two times, t and u, such that Earwicker slept at t, Shem kicked Shaun at u, and I was before' u.' This analysis relates the two uses ofbefore', and it explains why 'Earwicker slept before Shern kicked Shaun' entails 'Shern kicked Shaun'. It does this, however, only by attributing to 'Shem kicked Sbaun' the following form: 'There exists a tsuch that Shem kickedShaun ar t. 'According to Seen in this light, to call the paraphrase of a sentence inro some standard first­ order quanrificational form the logical form of the sentence seems arbitrary indeed. Quanrificacion theory has its celebrared merits, ro be sure: it is powerful, simple, consistent, and complete in its way. Not least, there are more or less standard techniques for paraphrasing many sentences of narural languages inro quanrihcational languages, which helps excuse nor making the relativity to a theory explicit. Still, the relariviry remains. Since there is no eliminating the relariviry of logical form ro a background theory, the only way to justify particular claims about logical form is by showing that they fir senrences inca a good theory, at least a theory better than known alternatives. In calling quanrificarional form logical form I was assuming, like many others before the, that quantification theory is a good theory. What's so good about it? Well, we should nor sneeze at the virtues mentioned above, its known consistency and completeness (in the sense that all quantihcational truths are provable). Cargile takes the ro rask for criricizing Reichenbach's analysis of senrences about events, which introduces an operaror that, when prefixed to a sentence, results in a singnlar rerm referring ro an event. I givc a standard argument to show that on this analysis, if one keeps suhstirutiviry of idenriry and a simple form of exrensionaliry, all events collapse inro one. r concluded, 'This demonstrates, I think, that Reichenbach's analysis is radically defective'. Cargile protescs that Reichenbach gets in no trouble if the assumption of exrensionaliry is abandoned; and the assumption is mine, nor Reichenbach's. Fair enough; I ought nor to have said the analysis was defective, bur rather that on a narnral assumption there was a calamitous consequence. Wirhour the assumption there is no such consequence; but also no theory. Standard quantification theory plus Reichenbach's theory of event sentences plus suhstitutiviry ofidenciry in the new contexts leads to collapse of all events inro one. Reichenbach indirectly commits himself to the principle of subsritutiviry, and Cargile goes along explicirly. So they are apparently committed co giving up srandard quanrificarion theory. Since neither offers a substitute, it is impossible to evaluate the posirion.sc Cargile has another idea, which is nor ro ramper with quantification theory, bur simply to add some exrra rules to it. If we give the quannficarional form of 'Jones buttered the toast in the bathroom as 'Bunered, (Jones, the roast, the bathroom)' and of <Jones buttered the roast' as 'Burrered- (Jones, the toast)' then the inference from the first to the second is no longer a matter of quanrificarional logic; bur why not inrerprcr this as showing that quanrificarional form isn't logical form, and quanrificationallogic isn't all of logic? Cargile suggesrs that we mighr be able ro give a purely formal (syntactical) rule that would sysrcmarize these inferences. I think Cargile underestimates the difficulties in doing this, 64 x Cargile. nor even Russell would have denied that kicked is a two-place relation form; but Russell had the same motive Frege did for holding chat 'kicked' has the logical form ofa three-place predicate. The logical form that the problem of 'before' prompts us to assign ro 'Shem kicked Shaun' and to its pam is the very form I suggested, though my reasons were somewhat different, and the oncology was different. So far as onrology is con­ cerned, [he two proposals may to advantage be merged, for we may chink of 'before' and 'after' as relating events as easily as rimes. For mosr purposes, if nor all. times are like lengchs-c-conveniem abstractions with which we can dispense in favour of the concrera that have them. A significant bonus from [his analysis of sentences of temporal priority is that singular causal senrences can then be nat­ urally related to them. According to Hume, if x caused j, then x preceded y. What are the entities these variables range over? Events, to be sure. But ifthis answer is to be taken seriously, then a sentence like 'Sandy's rocking the boat caused it co sink' must somehow refer to events. Ir does, if we analyse it along these lines: 'There exist two events, e andf, such that r is a rocking of the boat by SandY,fis a sinking of the boat, and e caused f' Ler us suppose, as Cargile seems willing to do, that I am right to this extent: by rewriting or rephrasing certain sentences inro sentences that explicitly refer to or quantify over events, we can conveniently represent the enrailmenr relations between the original sentences. The entailments we preanalytically recognize to hold between the original sentences become matters of quantificarional logic applied to their rephrasals. And now Cargile asks: how can this projecr. assuming it to be successfully carried out, justify the claim that the original senrences have the logical form of their rewrites? Why not admit that the rewrites show, in many cases, a different form? Here we have, I hope, the makings ofa reconciliation, for I am happy ro admit that much of the interest in logical form comes from an interest in logical geography: to give the logical form of a sentence is ro give its logical location in the roraliry of sentences, to describe it in a way that explicitly determines what sentences it entails and what sentences it is entailed by. The locarion must be given relative ro a specific deductive theory; so logical form itself is relarive ro a theory. The relatively does nor stop here, eicher, since even given a theory of deduction there may be more chan one total scheme for interprering the sen­ rences we are interested in and mar preserves che partern of entailments. The logical form of a particular sentence is, then, relative both ro a theory of deduction and to some prior determinations as ro how ro render sentences in the language of the theory. 65 l U; For a discussion of the difficultie! of combining subsriruciviry of idenriry and non­ exrensionalicy, see Dagfinn Fellesdal, 'Quine on Modality'. 66 67 The EssentialDavidson particularly if. as I have argued. such an approach forces US to adrnir predicates with indefinitely large numbers of predicate places. I also think he slights the difference, in his remark chat 'the standard symbolism of quantification theory is nOC good at keeping track of entailments between relational forms in English'. between simple axioms (which are all that are needed co keep track of the entailments between relational forms in. say. a theory of measurement] and new rules of inference (or axiom schemata). Bur harping on the difficulties, unless they can be proven to be impossibilities, is inconclusive. lt will be more instructive co assume chat we are presented with a satisfactory deductive system that adds to quantification theory rules adequate co implement the entailments between event sentences of the SOft under consideration. Whar could then be said in defence of my analysis? What can be said comes down ro this: it explains more, and it explains better. lr explains more in the obvious sense of bringing more clara under fewer rules. Given my account of the form of sentences about evenrs and actions, certain entailments are a matrer of quantificarionallogic: an accounr of the kind Cargile hopes ro give requires quanrificarionallogic, and then some. Bur there is a deeper difference. We catch sighr of the further difference if we ask ourselves why 'Jones buttered the roast in the bathroom' en rails 'Jones buttered the roast'. So far, Cargile's only answer is, because 'buttered' and some orher verbs (lisred or characterized somehow) work that way; and my only answer is, because (given my paraphrases) it follows from the rules of quantification theory. Bur now suppose we ask, why do the rules endorse this inference? Surely it has something to do with the facr mar "buttered' rums up in both sentences? There must be a common conceptual element represented by this repeated syntactic feature, we would have a clue co it, and hence a better understanding of the meaning of the two sentences, if we could say what common role 'buttered' has in the two sentences. Bur here it is evident mar Cargile's rules, if they were formulated, would be no help. These rules near the fact mar the word 'buttered' rurns up in both senrences as an accident: the rule would work as well if unrelated words were used for the two­ and for the three-place ptedicares. In the analysis I have proposed, the word 'buttered' is discovered. to have a common role in the two sentences: in both cases it ls a predicate satisfied by certain ordered triples of agents, things buttered, and events. So now we have the beginnings of a new sort of answer to the question why one of our sentences entails the other: it depends on the fact that the word 'burcered' is playing a certain common role in born sentences. By saying exactly what the role is, and whar the roles of the orner significanr fearures of the sentences are, we will have a deep explanation of why one senrence enrails the other, an explanarion mar draws on a systemaric accounr of how the meaning of each senrence is a hmcrion of irs srrucrure. To exhibir an enrailmenr as a marrer of quanrificational form is ro explain it bener because we do nor need (0 rake the rules of quanrificarLonallogic on faim; we can show that they are valid, i.e., truth-preserving, by giving an accounr of the conditions under which sentences in quantificationai form are true. From such an account (a theory of truth satisfying Tarski's criteria) it can be seen that if certain sentences are true, others must be. The rules of quantificational logic are justified when we demonstrate mar from truths they can lead only to truths. Plenry of inferences that some might call logical cannot be shown ro be valid in any interesting way by appeal to a theory of truth, for example the inference to 'a is larger than c ' from 'a is larger than band b is larger than c' or to 'Henry is nor a than' from 'Henry is a frog'. Clearly a recursive accounr of truth can ignore these entailments simply by ignoring the logical features of the particular pre­ dicares involved. Bur if I am right. it may nor be possible to give a coherent theory of truth mar applies to sentences abour events and that does nor validate the adverbial inferences we have been discussing. Ler the scare in more detail how I think our sample inference can be shown to be valid. On my view, a theory of truth would email that 'Jones buttered the roast in the bathroom' is true if and only if there exists an event satisfying these two condirions: it is a buttering of the roasr by Jones, and it occurred in the barh­ room. Bur if these conditions are satisfied, then there is an event that is a bur­ rering of the roast by Jones, and this is just what musr be the case, according to the theory, ifjones buttered the roast' is true. I pur the matter this way because it seems to the possible that Cargae may agree with what I say, then adding, 'Bur how does chis show that "Jones buttered the roasr'' is a three-place predicate?' If this is his response, our troubles are over, or anyway are merely verbal, for all I mean by saying that 'Jones buttered the toast' has the logical form of an existentially quantified senrence, and that 'buttered' is a three-piece predicate, is that a theory of truth meering Tarski's criteria would entail mar this senrence is rrue if and only if there exists ... etc. By my lighrs, we have given the logical form of a sentence when we have given the truth-conditions of the sentence in the context of a theory of truth mar applies to the language as a whole. Such a theory must identify some finite stock of truth-relevant elements, and explicitly account for the truth-conditions of each sentence by how these elements feature in it: so to give the logical form of a sentence is to describe it as composed of the elements the theory isolates. These remarks will help, I hope, to pur talk of'paraphrasing' or 'translating' in irs place. A theory of truth entails, for each sentence s of the object language, a theorem of the form 's is true if and only ifp '. Since the sentence that replaces 'p' must be true (in the metalanguage) if and only if sis true (in the object lauguagc), there is a sense in which the sentence that replaces 'p 'may be called a translation of s; and if the meralanguage contains the objecr language, it may be called a paraphrase. (These claims musr be modified in imporram ways in a meory of rrurh for a namral language.) Bur it should be emphasized that paraphrasis or translation serves no purpose here excepr that of giving a sysrematic aCCOUnr of trurh-condirons. There is no further claim co synonymy. nor inreresr in > 68 The Essential Davidson The Logica! Formof Action Sentences regimentation or improvement. A theory of [CUm gives a paine to such concepts as meaning, translation, and logical form; if does not depend on them.e? Ie should now be clear that my only reason for 'rendering' or 'paraphrasing' event sentences into quantihcational form was as a way of giving truth­ conditions for those sentences within a going theory of truth. We have a clear semantics for first-order quantificarionallanguages, and so if we CU1 see how to paraphrase senrences in a natural language into quanrificarional form, we see how to extend a theory of tturh co those sentences. Since the entailments that depend on quanrificarional form can be completely formalized, it is an easy test of our success in capruring logical form within a theory of [rum to see whether our paraphrases articulate the enrailrnenrs we independently recognize as due co form. To give the logical form of a sentence is, then, for the, co describe it in rerms that bring it within the scope of a semantic theory that meers clear requirements. Merely providing formal rules of inference, as Cargile suggests, thus fails co couch the question of logical form (except by generalizing some of the data a theory must explain); showing how co puc sentences into quanrificarional form, on the other hand, does place them in the context of a semantic theory. The contrast is stark, for it is the contrast between having a theory, and hence a hypothesis about logical form, and having no theory, and hence no way of making sense of claims about form. Bur of course this does nor show mac a theory based on first-order quanrificarional structure and irs semantics is all we need or can have. Many philosophers and logicians who have worked on the problem of event sentences (nor co mention modalities, sentences about propositional arrirudes, and so on) have come to the conclusion that a richer semantics is required, and can be provided. In Essay 2 above, I explicitly pur to one side several obvious problems ehar invite appeal to such richer schemes. For various reasons I thoughr, or hoped, mac the problem I isolared could be handled within a fairly ausrere scheme. But when other problems are also emphasized, it may well be mac my simple proposal loses irs initial appeal; at least the theory must be augmented, and perhaps it will have co be abandoned. Cargile thinks that instead ofsuggesting that 'Shem kicked Shaun' has a logical form that is made mote explicit by '(3x) (Kicked (Shern, Shaun, x»)' I ought (at most) to have said mac the CWo sentences are logically equivalent (bur have different logical forms). He makes an analogous point in defending Reichenbach against my strictures. I want co explain why I resist this adjustment. Of course it can happen that two sentences are logically equivalent, yec have different logical forms; for example a sentence with the logical form of a con­ junction is logically equivalent co the conjunction which rakes the conjuncts in reverse order. Here we assume the theory gives the truth-conditions of each sentence, and it will be possible co prove mac one sentence is true if and 0 nly if the other is. Bur the theory doesn't independently supply truth-conditions for 'Shem kicked Shaun' and its canonical counterpart; ramer the larrer gives (or, in the present discussion, is used ro suggest) the truth conditions of the former. If the theory were turned on itself as well it might be, the sentence used to give the truth-conditions of '(3x) (Kicked (Shern, Shaun, x»)' would have the same form as this sentence; under some natural conditions, it would be this sentence. So there is no way within the theory ofassigning different logical forms to 'Shem kicked Shaun' and its explicitly quanrificarional stand-in. Outside a theory, the notion of logical form has no clear application, as we have noted. That the two senrences have very different syntactical structures is evident; that is why the claim that the logical form is the same is interesting and, if correct, revealing. Suppose that a rule of inference is added to our logic, making each of the two sentences deducible from the other. (Reichenbach may have had this in mind: see Elements of57mbo!;c Logic, § 48.) Will this then make it possible to hold that the sentences have different logical forms? The answer is as before: rules of inference that are not backed by a semantic theory are irrelevant to logical form. I would like co mention very briefly anomer point on which Cargile may have misunderstood the. He says that, 'The idea that philosophical "analysis" consists in this revealing of logical form is a popular one ... ' and he may mink I share this notion. I don't, and I said that I didn't on the first page of the article he discusses. Even if philosophical analysis were concerned only with language (which I do not believe), revealing logical form would be only part of the enterprise. To know the logical form of a sentence is to know, in the Context of a comprehensive theory, the semantic roles of the significant features of the sentence. Aside from the logical constants, this knowledge leaves us ignorant of the relations between predicates, and of their logical properties. To know the logical form of 'The rain caused the flood' is to know whether 'caused' is a sentential connective or a two­ place predicate (or something else), but it hardly begins to be knowledge of an analysis of the concept of causaliry (or the word 'caused'). Or perhaps it is the beginning; bur mac is all. On the score of oncology, too, the study oflogical form can carry us onJy a certain distance. If I am right, we cannot give a satisfactory account of the semantics of certain sentences without recognizing that if any of those sentences are true. mere must exist such things as events and actions. Given this much, a study of event sentences will show a great deal about what we assume to be true concerning events. But deep metaphysical problems will remain as to the nature of these encities, their mode of individuation, their relarions to ocher categories. Perhaps we will find a way of reducing events to entities of other kinds, for example, sets of points in space-time, or ordered a-tuples of times, physical objects, and classes of ordered a-tuples of such. Successful reductions along these lines may, in an honoured tradition, be advertised as showing that there are no the 17 These claims and others made here art: expanded and defended in my'Tnuh and Meaning' (Essay 8, [his volume). • 69 such things as events. As long as the quantifiers and variables remain in the same places, however, the analysis oflogical form will stick. shown (by a sernanrical theory] to be valid without also proving the following to be true; 'The striking of the tude old than by Oedipus was identical with the striking of Oedipus's father by Oedipus'? Yet one of these actions was intentional and the other nor. I don't say no theory could be contrived to validate the wanted inferences while not endorsing the identity; but we don't now have such a theory. 70 I. &ply to Hedman. If we are committed to events, we are committed to making sense ofidenriry-senrences, like 'a = b', where the terms flanking the identity sign refer ro events. I think in fact we use sentences in this form constantly: 'The third round of the fight was (identical with) the one in which he took a dive'. 'Our worst accident was (identical with) the one where we hit four other cars', 'Falling off the tower was (identical with) the cause of his death'. The problem of individuation for events is the problem of giving criteria saying when such sentences arc true. Carl Hedman raises a tricky question about these criteria as applied co actions. In Essay 2 above, I asserted, as Hedman says, that 'intentional actions are not a class of actions'. I said this to protect my theory against an obvious objection. If 'intentional' modifies actions the way 'in the kitchen' does, then intentional actions are a class of actions. Does Oedipus's striking of the rude old than belong in this class or not? Oedipus struck the rude old than intentionally, but he did not strike his father intentionally. But on my theory, these srrikings were one, since the tude old than was Oedipus's father. The obvious solution, which I endorsed, is to take 'intentionally' as crearing a semantically opaque context in which one would expect substirutiviry of identity to seem to fail. I did not argue for this view in the article Hedman discusses; in the long passage he quotes I say only that it is 'the natural and, I think, correct answer'. In that passage I was surveying a number of topics, such as causaliry, theory of action, explanations, and the identity theory of mind, where philosophers tend to say things which rake for granted an ontology of events and actions. My point was that if they do make this assumption, they ought to come up with a serious theory about how reference to events occurs; my intention was to soften up potential opposition to the analysis which (I argued) is forced on us anyway when we try to give a systematic semantics for natural language. Elsewhere I have argued for the view that one and the same action may be correccly said to be intentional (when described in one way) and not intentional (when described in anomer). The position is hardly new with the; it was expounded at length by Anscombc.w and has been accepted by many other writers on action. It is harder 1O avoid taking this position than one might think. I suppose no one wants 1O deny that if the rude old than was Oedipus's father, then 'Oedipus struck the rude old than' and 'Oedipus struck his father' entail one another. If one accepts. as Hedman apparently does, an ontology of evenrs, one will also presumably want to infer 'The striking of the rude old than by Oedipus occurred at the crossroads' from 'The striking of Oedipus's father by Oedipus occurred at the crossroads' and vice versa. But how can these entailments be
C++
UTF-8
464
2.734375
3
[]
no_license
#include <iostream> #include <fstream> using namespace std; int main(int argc, char* argv[]) { char filename[] = "Balances.txt"; char buff[100]; ifstream infile(filename); infile.open(filename); if (infile.fail()) { cout << "Unable to open " << filename << endl; return 1; } while (!infile.eof()) { infile.getline(buff,100); cout << buff << endl; } infile.close(); return 0; }
Java
UTF-8
677
2.921875
3
[]
no_license
/** * */ package ds.movement; import java.awt.geom.Point2D; /** * @author f4 * */ public class HorizontalLine extends AntiGravityObject { /** * Constructeur * @param y * @param weight * @param gravityType */ public HorizontalLine( double y, double weight, double gravityType ) { super( 400, y, weight, gravityType ); } public Vector2D getForceVector(Point2D.Double referent) { double distance = Math.abs(referent.getY()-getPosition().getY()); Vector2D vect = new Vector2D(0, referent.getY()-getPosition().getY()); vect.multiply(100); double pow = Math.pow( distance, m_gravityType); vect.multiply(getWeight()/pow); return vect; } }
Python
UTF-8
759
2.734375
3
[]
no_license
# Scrapes result from http://result.vtu.ac.in using BeautifulSoup from bs4 import BeautifulSoup import requests u="1mv15cs" # beginning part of the USN. Without serial for i in range(1,135): # USN range for every branch if (i<10): pre='00' elif (i<100): pre='0' else: pre='' no=str(i) usn=u+pre+no # Concatenated USN url="http://result.vtu.ac.in/cbcs_results2016.aspx?usn="+usn+"&sem=2" reqfile = requests.get(url) soup = BeautifulSoup(reqfile.content,"html5lib") #print soup.prettify() #print soup.title.text if(soup.title.text=="cbcs_result"): continue print usn print soup.find(id="txtName")['value'],soup.find(id="lblSGPA").text # print USN, Name and GPA print ''
Python
UTF-8
847
4.40625
4
[]
no_license
""" 2. Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка элементов необходимо использовать функцию input(). """ my_list = [] #пусть будет 7 элементов for i in range(7): el = input(f'Введите элемент списка номер {i+1} (всего 7): ') my_list.append(el) print(my_list) # поменяем местами for i in range(1, len(my_list), 2): num = my_list.pop(i) my_list.insert(i-1, num) print(my_list)
JavaScript
UTF-8
21,860
2.515625
3
[ "MIT" ]
permissive
const scene = new THREE.Scene(); const renderer = new THREE.WebGLRenderer(); var allInterval = []; const audio1 = new Audio(), audio2 = new Audio(), audio3 = new Audio(); audio1.src = 'https://static.wikia.nocookie.net/minecraft_ru_gamepedia/images/a/aa/Grass_hit1.ogg'; audio2.src = 'https://static.wikia.nocookie.net/minecraft_ru_gamepedia/images/7/71/Grass_hit2.ogg'; audio3.src = 'https://static.wikia.nocookie.net/minecraft_ru_gamepedia/images/e/e0/Grass_hit3.ogg'; const allMusic = [audio1, audio2, audio3] const NewGame = () => { scene.background = new THREE.Color("#153b84"); var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 32); var raycaster = new THREE.Raycaster(); var mouse = new THREE.Vector2(); camera.rotation.order = 'YXZ'; renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); camera.position.z = 0; camera.position.y = 8; camera.position.x = 0; document.oncontextmenu = function () { return false }; var geometry = new THREE.BoxGeometry(1, 1, 1); var chanks = [], scope = 0, gameover = false; var oldMousePosition = { x: 0, y: 0 }; new Promise((resolve, reject) => { //loading texture// var canvas = document.createElement('canvas'), ctx = canvas.getContext("2d"), parts = [], img = new Image(); function split_4() { let w2 = img.width / 16, h2 = img.height / 16; for (let h = 0; h > -img.height; h -= 32) { for (let w = 0; w > -img.width; w -= 32) { canvas.width = w2; canvas.height = h2; ctx.drawImage(this, w, h, w2 * 16, h2 * 16); parts.push(canvas.toDataURL()); } } for (let i = 0; i < parts.length; i++) { var slicedImage = document.createElement("img"); slicedImage.id = `gameBlock_${i + 1}` slicedImage.src = parts[i]; var div = document.getElementById("test"); div.appendChild(slicedImage); } }; img.onload = split_4; img.src = document.getElementById("textureCode").getAttribute("src"); resolve("result") //loading texture// }).then(() => { let def = setInterval(() => { if (document.getElementById(`gameBlock_255`).getAttribute("src")) { clearInterval(def); let fly = false, space = false; //gravity player (() => { let gravity = new THREE.Raycaster() let gravitationInterval = setInterval(() => { if (!fly && !space) { gravity.set(camera.position, new THREE.Vector3(0, -1, 0)); try { let intersects = gravity.intersectObjects(scene.children, true); if (intersects[0]) { if (intersects[0].distance > 2) { camera.position.y -= 0.3 } } else { camera.position.y -= 0.3 } } catch{ } if (camera.position.y < -20) { document.getElementById("scope").innerHTML = scope; document.getElementsByClassName("gameover")[0].style.display = "block"; clearInterval(gravitationInterval); gameover = true; } } document.getElementById("position").innerHTML = `Position(x,y,z): ${Math.floor(camera.position.x)}/${Math.floor(camera.position.z)}/${Math.floor(camera.position.y)}`; }, 10) })(); //gravity player //background change// (() => { let backgroundColor = ["05132b", "081b3d", "0a214b", "0c2554", "0f2d65", "153b84", "153b84", "153b84", "0c2554", "0a214b", "081b3d", "05132b", "05132b"] let gameTime = { hour: 12, minute: 0 } let gameTimeInterval = setInterval(() => { if (gameTime.hour < 24) { if (gameTime.minute < 59) { gameTime.minute += 1 } else { gameTime.hour += 1; gameTime.minute = 0 } } else { gameTime.hour = 0; } try { scene.background = new THREE.Color('#' + backgroundColor[Math.floor(gameTime.hour / 2)]); } catch{ } document.getElementById("chunks").innerHTML = `ChunksLoad: ${chanks.length}`; document.getElementById("gametime").innerHTML = `GameTime: ${gameTime.hour}:${gameTime.minute < 10 ? '0' + gameTime.minute : gameTime.minute}`; }, 288); allInterval.push(gameTimeInterval) })(); //background change// //control keys// (() => { window.addEventListener('mousemove', (event) => { if (!gameover) { let movementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0; let movementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0; camera.rotation.x += -movementY * Math.PI / 180; camera.rotation.y -= movementX * Math.PI / 180 camera.rotation.x = Math.min(Math.max(camera.rotation.x, -1.0472), 1.0472); oldMousePosition.x = event.clientX; oldMousePosition.y = event.clientY; mouse.x = (event.clientX / window.innerWidth) * 2 - 1; mouse.y = - (event.clientY / window.innerHeight) * 2 + 1; raycaster.setFromCamera(mouse, camera); var intersects = raycaster.intersectObjects(scene.children, true); if (intersects[0]) { document.getElementById("selectBlock").innerHTML = `SelectBlock(x,y,z): ${Math.floor(intersects[0].object.position.x)}/` + `${Math.floor(intersects[0].object.position.z)}/` + `${Math.floor(intersects[0].object.position.y)}`; } else { document.getElementById("selectBlock").innerHTML = `SelectBlock(x,y,z): 0/0/0`; } } }, false); document.body.addEventListener("click", () => { raycaster.setFromCamera(mouse, camera); var intersects = raycaster.intersectObjects(scene.children); if (intersects[0]) { if (Math.abs(camera.position.x - intersects[0].point.x) < 9 && Math.abs(camera.position.z - intersects[0].point.z) < 9 && Math.abs(camera.position.y - intersects[0].point.y) < 9) { scene.remove(intersects[0].object); scope++; } } }); const randomAudio = () => { allMusic[Math.floor(Math.random() * Math.floor(3))].play() } (() => { let lastChar = undefined; let clearchar = undefined; document.body.onkeyup = (e) => { clearInterval(clearchar) if (e.keyCode == 32) { if (lastChar != 32) { space = true; camera.position.y += 2; setTimeout(() => { space = false; }, 200); } clearchar = setTimeout(() => { lastChar = undefined; }, 300); } if (lastChar == 32) { fly = !fly; document.getElementById("flystatus").innerHTML = `Fly Status: ${fly}`; lastChar = undefined; } else { lastChar = e.keyCode; } } document.body.onkeydown = (e) => { if (!gameover) { if (e.keyCode == 32) { if (fly) { camera.position.y += 0.5; } } if (e.keyCode == 16) { if (fly) { camera.position.y -= 0.5; } } let fixidY = camera.position.y; if (e.keyCode == 87) { camera.translateZ(-0.3); camera.position.y = fixidY; if (!fly) { randomAudio(); } } else if (e.keyCode == 65) { camera.translateX(-0.3); camera.position.y = fixidY; if (!fly) { randomAudio(); } } else if (e.keyCode == 68) { camera.translateX(0.3); camera.position.y = fixidY; if (!fly) { randomAudio(); } } else if (e.keyCode == 83) { camera.translateZ(0.3); camera.position.y = fixidY; if (!fly) { randomAudio(); } } } } })() var setblock = 1; (() => { let ignoreBlock = [ 6, 10, 11, 22, 27, 28, 31, 32, 39, 40, 41, 46, 48, 58, 59, 60, 63, 70, 71, 72, 76, 77, 82, 83, 84, 85, 86, 87, 89, 90, 91, 92, 93, 94, 95, 97, 98, 99, 100, 103, 109, 110, 111, 113, 119, 123, 124, 125, 128, 132, 135, 136, 137, 140, 141, 144, 148, 149, 150, 151, 152, 156, 157, 158, 160, 169, 170, 171, 173, 174, 175, 181, 182, 184, 186, 187, 188, 189, 190, 191, 192, 217, 218, 219, 220, 221, 222, 232, 233, 234, 235, 236, 237, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 42, 43, 153, 112, 79 ]; let storageRoot = document.getElementById("test"); for (let i = 1; i < storageRoot.childElementCount; i++) { if (!ignoreBlock.includes(i)) { let localElem = document.getElementById(`gameBlock_${i}`); if(localElem){ localElem.setAttribute("class", "allow_block"); } } } })(); const fixTextureFunction = (allowBlock) => { let arrayTexture = [ { allowBlock: 3, absoluteTexture: [4, 4, [41, "#bfb755"], 4, 4, 4] }, { allowBlock: 7, absoluteTexture: [9, 9, 10, 9, 9, 9] }, { allowBlock: 11, absoluteTexture: [208, 208, 208, 208, 208, 208] }, { allowBlock: 17, absoluteTexture: [21, 21, 22, 21, 21, 21] }, { allowBlock: 27, absoluteTexture: [36, 36, 5, 36, 36, 36] }, { allowBlock: 42, absoluteTexture: [60, 60, 44, 44, 61, 61] }, { allowBlock: 31, absoluteTexture: [45, 46, 63, 63, 46, 46] }, { allowBlock: 32, absoluteTexture: [47, 46, 63, 63, 46, 46] }, { allowBlock: 43, absoluteTexture: [62, 46, 63, 63, 46, 46] }, { allowBlock: 49, absoluteTexture: [69, 69, 67, 69, 69, 69] }, { allowBlock: 53, absoluteTexture: [78, 78, 79, 78, 78, 78] }, { allowBlock: 56, absoluteTexture: [3, 3, 88, 3, 3, 3] }, { allowBlock: 63, absoluteTexture: [109, 109, 107, 109, 109, 109] }, { allowBlock: 64, absoluteTexture: [109, 109, 108, 109, 109, 109] }, { allowBlock: 70, absoluteTexture: [120, 119, 103, 119, 119, 119] }, { allowBlock: 71, absoluteTexture: [121, 119, 103, 119, 119, 119] }, { allowBlock: 80, absoluteTexture: [137, 137, 138, 137, 137, 137] }, { allowBlock: 89, absoluteTexture: [160, 160, 159, 160, 160, 160] }, { allowBlock: 104, absoluteTexture: [183, 183, 167, 183, 183, 183] }, { allowBlock: 88, absoluteTexture: [155, 155, 156, 155, 155, 155] }, { allowBlock: 37, absoluteTexture: [[53, "#9E814D"], [53, "#9E814D"], [53, "#9E814D"], [53, "#9E814D"], [53, "#9E814D"], [53, "#9E814D"]] }, { allowBlock: 38, absoluteTexture: [[54, "#9E814D"], [54, "#9E814D"], [54, "#9E814D"], [54, "#9E814D"], [54, "#9E814D"], [54, "#9E814D"]] }, { allowBlock: 78, absoluteTexture: [[133, "#9E814D"], [133, "#9E814D"], [133, "#9E814D"], [133, "#9E814D"], [133, "#9E814D"], [133, "#9E814D"]] }, { allowBlock: 79, absoluteTexture: [[134, "#9E814D"], [134, "#9E814D"], [134, "#9E814D"], [134, "#9E814D"], [134, "#9E814D"], [134, "#9E814D"]] }, ] let search = arrayTexture.filter((e) => e.allowBlock == allowBlock)[0]; let t = search.absoluteTexture; let mat = [ new THREE.MeshBasicMaterial({ map: new THREE.TextureLoader().load(document.getElementById(`gameBlock_${t[0][0] ? t[0][0] : t[0]}`).getAttribute("src")), color: (t[0][0] ? t[0][1] : false), transparent: true }), new THREE.MeshBasicMaterial({ map: new THREE.TextureLoader().load(document.getElementById(`gameBlock_${t[1][0] ? t[1][0] : t[1]}`).getAttribute("src")), color: (t[1][0] ? t[1][1] : false), transparent: true }), new THREE.MeshBasicMaterial({ map: new THREE.TextureLoader().load(document.getElementById(`gameBlock_${t[2][0] ? t[2][0] : t[2]}`).getAttribute("src")), color: (t[2][0] ? t[2][1] : false), transparent: true }), new THREE.MeshBasicMaterial({ map: new THREE.TextureLoader().load(document.getElementById(`gameBlock_${t[3][0] ? t[3][0] : t[3]}`).getAttribute("src")), color: (t[3][0] ? t[3][1] : false), transparent: true }), new THREE.MeshBasicMaterial({ map: new THREE.TextureLoader().load(document.getElementById(`gameBlock_${t[4][0] ? t[4][0] : t[4]}`).getAttribute("src")), color: (t[4][0] ? t[4][1] : false), transparent: true }), new THREE.MeshBasicMaterial({ map: new THREE.TextureLoader().load(document.getElementById(`gameBlock_${t[5][0] ? t[5][0] : t[5]}`).getAttribute("src")), color: (t[5][0] ? t[5][1] : false), transparent: true }) ]; return mat; } document.body.addEventListener("mousedown", (e) => { if (e.which == 3) { raycaster.setFromCamera(mouse, camera); var intersects = raycaster.intersectObjects(scene.children); if (intersects[0]) { if (Math.abs(camera.position.x - intersects[0].point.x) < 9 && Math.abs(camera.position.z - intersects[0].point.z) < 9 && Math.abs(camera.position.y - intersects[0].point.y) < 9) { let crossObject = [8, 9, 10, 12, 22, 23, 40, 41, 44, 51, 54, 55, 67, 57, 114, 115, 116, 117, 118, 134, 135, 136]; let fixTexture = [3, 7, 11, 17, 27, 31, 32, 37, 38, 42, 43, 49, 53, 56, 63, 64, 70, 71, 78, 79, 80, 88, 89, 104]; let x = ((Math.abs(intersects[0].point.x) % 1 == 0.5) ? ((Math.abs(camera.position.x) > Math.abs(intersects[0].point.x)) ? (Math.ceil(Math.abs(intersects[0].point.x)) * Math.sign(intersects[0].point.x)) : (Math.floor(Math.abs(intersects[0].point.x)) * Math.sign(intersects[0].point.x))) : Math.round(intersects[0].point.x)); let y = ((Math.abs(intersects[0].point.y) % 1 == 0.5) ? ((Math.abs(camera.position.y) > Math.abs(intersects[0].point.y)) ? (Math.ceil(Math.abs(intersects[0].point.y)) * Math.sign(intersects[0].point.y)) : (Math.floor(Math.abs(intersects[0].point.y)) * Math.sign(intersects[0].point.y))) : Math.round(intersects[0].point.y)); let z = ((Math.abs(intersects[0].point.z) % 1 == 0.5) ? ((Math.abs(camera.position.z) > Math.abs(intersects[0].point.z)) ? (Math.ceil(Math.abs(intersects[0].point.z)) * Math.sign(intersects[0].point.z)) : (Math.floor(Math.abs(intersects[0].point.z)) * Math.sign(intersects[0].point.z))) : Math.round(intersects[0].point.z)); let texture = new THREE.TextureLoader().load(document.getElementsByClassName(`allow_block`)[setblock].getAttribute("src")); let block = undefined, material = new THREE.MeshBasicMaterial({ map: texture, transparent: true }); if (fixTexture.includes(setblock)) { material = fixTextureFunction(setblock) } if (crossObject.includes(setblock)) { var materials = new THREE.MeshBasicMaterial({ map: texture, side: THREE.DoubleSide, transparent: true }); block = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ transparent: true, wireframe: true, color: "#bfb755" })); scene.add(block); localGeometry = new THREE.PlaneBufferGeometry(1, 1, 1, 1); mesh1 = new THREE.Mesh(localGeometry, materials); mesh1.rotation.y = THREE.Math.degToRad(45) block.add(mesh1); mesh2 = new THREE.Mesh(localGeometry, materials); mesh1.rotation.y = THREE.Math.degToRad(90) block.add(mesh2); if (intersects[0].object.position.x != x || intersects[0].object.position.y != y || intersects[0].object.position.z != z) { block.position.x = x; block.position.y = y; block.position.z = z; scope++; } } else { block = new THREE.Mesh(geometry, material); if (intersects[0].object.position.x != x || intersects[0].object.position.y != y || intersects[0].object.position.z != z) { block.position.x = x; block.position.y = y; block.position.z = z; scene.add(block); scope++; } } } } } }, true); (() => { let updateInvent = (sign = undefined) => { for (i = 1; i < 10; i++) { if (setblock + i - 1 < 139) { document.getElementById(`slot${i}`).setAttribute("src", document.getElementsByClassName(`allow_block`)[setblock + i - 1].getAttribute("src")); } else { document.getElementById(`slot${i}`).setAttribute("src", ""); } } } document.addEventListener("wheel", (e) => { let sign = Math.sign(e.deltaY || e.detail || e.wheelDelta); if (setblock + sign > 0 && setblock + sign < 139) { setblock += sign; updateInvent(sign) } }); updateInvent() })() })(); //control keys// //chunk generator function generatorChunk(x1 = null, y1 = null, x2 = null, y2 = null, height = null, typeblock = null) { let localSaveChank = { x1, y1, x2, y2, height, blocks: [] } if (!isNaN(x1) && !isNaN(y1) && !isNaN(x2) && !isNaN(y2)) { for (let i = 0; i < height; i++) { let text = new THREE.TextureLoader().load( document.getElementById(`gameBlock_18`).getAttribute("src") ); if (i == 1 || i == 2) { text = new THREE.TextureLoader().load( document.getElementById(`gameBlock_2`).getAttribute("src") ); } if (i == 3) { text = new THREE.TextureLoader().load( document.getElementById(`gameBlock_3`).getAttribute("src") ); } let mat = new THREE.MeshBasicMaterial({ map: text, transparent: true }); if (i == 4) { mat = [ new THREE.MeshBasicMaterial({ map: new THREE.TextureLoader().load(document.getElementById(`gameBlock_4`).getAttribute("src")) }), new THREE.MeshBasicMaterial({ map: new THREE.TextureLoader().load(document.getElementById(`gameBlock_4`).getAttribute("src")) }), new THREE.MeshBasicMaterial({ map: new THREE.TextureLoader().load(document.getElementById(`gameBlock_41`).getAttribute("src")), color: "#bfb755" }), new THREE.MeshBasicMaterial({ map: new THREE.TextureLoader().load(document.getElementById(`gameBlock_4`).getAttribute("src")) }), new THREE.MeshBasicMaterial({ map: new THREE.TextureLoader().load(document.getElementById(`gameBlock_4`).getAttribute("src")) }), new THREE.MeshBasicMaterial({ map: new THREE.TextureLoader().load(document.getElementById(`gameBlock_4`).getAttribute("src")) }) ]; } for (let x = x1; x < x2 + 1; x++) { for (let y = y1; y < y2 + 1; y++) { let block = new THREE.Mesh(geometry, mat) block.position.x = x block.position.z = y block.position.y = i localSaveChank.blocks.push(block) scene.add(block); } } } } chanks.push(localSaveChank) } //chunk generator //default chuncks (() => { generatorChunk(-16, -16, 0, 0, 5, undefined); generatorChunk(-16, 1, 0, 16, 5, undefined); generatorChunk(0, -16, 16, 0, 5, undefined); generatorChunk(0, 0, 16, 16, 5, undefined); })() //default chuncks //animate function// var animate = function () { requestAnimationFrame(animate); renderer.render(scene, camera); }; animate() //animate function// } }, 500); }); } const restartGame = () => { document.getElementsByClassName("gameover")[0].style.display = "none"; document.getElementById("flystatus").innerHTML = `Fly Status: false`; for (elem in allInterval) { clearInterval(allInterval[elem]); } allInterval = [] while (scene.children.length > 0) { scene.remove(scene.children[0]); } NewGame(); } NewGame();
Java
UTF-8
2,971
3.140625
3
[]
no_license
package ir.parsdeveloper.commons.tags.utils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.UnhandledException; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; /** * @author hadi tayebi */ public class MultipleHtmlAttribute implements Cloneable { /** * Sets containing splitted attribute values. */ private Set<String> attributeSet; /** * Constructor for MultipleHtmlAttribute. * * @param attributeValue String */ public MultipleHtmlAttribute(String attributeValue) { this.attributeSet = new LinkedHashSet<String>(); addAllAttributesFromArray(StringUtils.split(attributeValue)); } /** * Adds attributes from an array. * * @param attributes Object[] Array containing attributes */ private void addAllAttributesFromArray(String[] attributes) { if (attributes == null) { return; } // number of attributes to add int length = attributes.length; // add all the splitted attributes for (String attribute : attributes) { // don't add if empty if (!StringUtils.isEmpty(attribute)) { this.attributeSet.add(attribute); } } } /** * Returns the list of attributes separated by a space. * * @return String */ public String toString() { StringBuffer buffer = new StringBuffer(); Iterator iterator = this.attributeSet.iterator(); while (iterator.hasNext()) { // apend next value buffer.append(iterator.next()); if (iterator.hasNext()) { // append a space if there are more buffer.append(' '); } } return buffer.toString(); } /** * Adds a value to the attribute. * * @param attributeValue value to add to the attribute */ public void addAttributeValue(String attributeValue) { // don't add if empty if (!StringUtils.isEmpty(attributeValue)) { this.attributeSet.add(attributeValue); } } /** * Return true if this MultipleHtmlValue doesn't store any value. * * @return <code>true</code> if this MultipleHtmlValue doesn't store any value */ public boolean isEmpty() { return attributeSet.isEmpty(); } /** * @see java.lang.Object#clone() */ protected Object clone() throws CloneNotSupportedException { MultipleHtmlAttribute clone; try { clone = (MultipleHtmlAttribute) super.clone(); } catch (CloneNotSupportedException e) { // should never happen throw new UnhandledException(e); } // copy attributes clone.addAllAttributesFromArray(this.attributeSet.toArray(new String[this.attributeSet.size()])); return clone; } }
Markdown
UTF-8
2,226
3.0625
3
[ "0BSD" ]
permissive
# About the "NetworkTime" sample The "NetworkTime" sample extension is a server extension that can query an NTP server. It uses the "RequestListener" interface to provide a single function symbol called "Now" that fetches the current timestamp from the NTP server and returns it. The NTP server URL is stored in the extension configuration at path `NetworkTime.Config::ntpServer`. **First steps:** - [Working with server extensions](../../README/WorkingWithServerExtensions.md) - [Interacting with a server extension](../../README/InteractingWithServerExtensions.md) ## Example requests 1. Get the current time from the configured NTP server. **Request:** ```json { "requestType": "ReadWrite", "commands": [ { "symbol": "NetworkTime.Now", "commandOptions": [ "SendErrorMessage" ] } ] } ``` **Response:** ```json { "commands": [ { "symbol": "NetworkTime.Now", "readValue": "2020-12-28T06:41:54.587Z" } ] } ``` 1. Get the configured NTP server URL. **Request:** ```json { "requestType": "ReadWrite", "commands": [ { "symbol": "NetworkTime.Config::ntpServer", "commandOptions": [ "SendErrorMessage" ] } ] } ``` **Response:** ```json { "commands": [ { "symbol": "NetworkTime.Config::ntpServer", "readValue": "ntp.beckhoff-cloud.com" } ] } ``` 1. Change the configured NTP server URL. **Request:** ```json { "requestType": "ReadWrite", "commands": [ { "symbol": "NetworkTime.Config::ntpServer", "writeValue": "time.windows.com", "commandOptions": [ "SendErrorMessage", "SendWriteValue" ] } ] } ``` **Response:** ```json { "commands": [ { "symbol": "NetworkTime.Config::ntpServer", "readValue": "time.windows.com" } ] } ```
Rust
UTF-8
2,996
2.8125
3
[ "MIT", "Apache-2.0" ]
permissive
// https://github.com/rvagg/ghauth/blob/master/ghauth.js extern crate dialoguer; extern crate directories; extern crate failure; extern crate mkdirp; extern crate reqwest; extern crate serde; extern crate serde_json; use self::dialoguer::{Input, PasswordInput}; use self::directories::ProjectDirs; use self::failure::Error; use self::mkdirp::mkdirp; use self::reqwest::{ Client, header::{ Headers, UserAgent, ContentType } }; use std::collections::HashMap; const GITHUB_URL: &'static str = "https://api.github.com/authorizations"; /// Configuration passed to create a new GitHub auth instance. #[derive(Debug, Default)] pub struct Config { /// GitHub auth scopes. E.g. `['user']`. // FIXME: convert scopes into a Vector of an Enum. Implement serializability // on it too. pub scopes: Option<Vec<String>>, /// Saved with the token on GitHub. Allows you to identify the purpose of this /// token from the GitHub UI. pub note: String, /// User agent used to make a request. pub user_agent: Option<String>, } /// A GitHub auth instance. #[derive(Debug)] pub struct Authenticator { name: String, config: Config, } /// An authentication returned by a GitHub auth instance. #[derive(Debug)] pub struct Authentication { /// The User's username. user: String, /// The token for the User. token: String, } impl Authenticator { /// Create a new instance. pub fn new(name: String, config: Config) -> Self { Authenticator { name, config } } /// Authenticate with GitHub. pub fn auth(&self) -> Result<Authentication, Error> { // Get CLI input. let username = Input::new("GitHub username").interact()?; let password = PasswordInput::new("GitHub password").interact()?; let otp = Input::new("GitHub OTP (optional)").interact()?; // Perform HTTP request. let client = Client::new(); let mut headers = Headers::new(); headers.set_raw("X-GitHub-OTP", otp); headers.set(UserAgent::new("Rust GH Auth client")); headers.set(ContentType::json()); let mut body = HashMap::new(); // if let Some(scopes) = self.config.scopes { // body.insert("scopes", *scopes); // } body.insert("note", &self.config.note); let mut res = client .post(GITHUB_URL) .json(&body) .headers(headers) .basic_auth(username, Some(password)) .send()?; // Parse request output. let status = res.status(); ensure!( status.is_success(), format!( "{:?} {:?}", res.text().unwrap(), status.canonical_reason().unwrap() ) ); let dirs = ProjectDirs::from("com", "GitHub Auth", &self.name); let dir = dirs.data_dir(); mkdirp(&dir)?; unimplemented!(); } } impl Default for Authenticator { /// Create a new instance of fn default() -> Self { let mut config = Config::default(); config.note = String::from("An unidentified token."); Authenticator { name: String::from("GitHub Auth"), config, } } }
Ruby
UTF-8
540
2.6875
3
[ "MIT" ]
permissive
module NewExcel module BuiltInFunctions module DateTime def date(strs) if strs.is_a?(Array) each_list(strs) do |list| list.map do |str| date(str) end end else Date.parse(strs) end end def time(*strs) each_item(strs) do |str| Time.parse(str) end end def hour(*list) each_item(list) do |time| primitive_method_call(time, :hour) end end end end end
Java
UTF-8
3,490
2.65625
3
[]
no_license
package ru.ifmo.ctd.ngp.demo.paramchooser.experiments; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.LineNumberReader; import java.nio.file.Path; import java.nio.file.Paths; /** * @author Arkadii Rost */ public class Extractor { private static final String DIST = "dist_base"; private static final String SIMPLE_Q = "simple_single"; private static final String KARAFOTIAS = "simple"; private static final String EARPC = "earpc_single"; private static final String UEARPC = "earpc"; private enum Problems { DIST("dist", "dist_base"), SIMPLE_Q("q-learn","simple_single"), GECCO("gecco", "simple"), EARPC("earpc", "earpc_single"), UEARPC("uearpc", "earpc") ; final String name; final String folder; Problems(String name, String folder) { this.name = name; this.folder = folder; } public String getName() { return name; } public String getFolder() { return folder; } } public static int countLines(File file) { try (LineNumberReader reader = new LineNumberReader(new FileReader(file))) { //noinspection StatementWithEmptyBody while (reader.readLine() != null) {} return reader.getLineNumber(); } catch (IOException e) { throw new RuntimeException(e); } } private static int getAverageLength(Problems problem, Path problemPath, int k, int mu, int lambda) { Path resPath = problemPath.resolve(String.format("%d_%d/%s_%d/", mu, lambda, problem.getFolder(), k)); File[] results = resPath.toFile().listFiles(); if (results == null) return 0; long sum = 0; for (File r : results) sum += countLines(r); return (int)(sum / results.length); } public static void main(String[] args) { int[] ranges = {1, 2, 3}; int[] mus = {1, 5, 10}; int[] lambdas = {1, 3, 7}; Problems[] problems; switch (args[0]) { case "dist": problems = new Problems[]{Problems.DIST}; break; case "simple": problems = new Problems[] {Problems.SIMPLE_Q, Problems.GECCO}; break; case "earpc": problems = new Problems[] {Problems.EARPC, Problems.UEARPC}; break; default: throw new IllegalArgumentException("Unknown value for args[0]: " + args[0]); } int size = problems.length * mus.length; Path problemDir = Paths.get(args[1]); System.out.println(String.format("\\begin{tabular}{|*%d{c|}}", size + 1)); for (int k : ranges) { System.out.println("\\hline"); System.out.println(String.format("\\multicolumn{%d}{|l|}{k = %d} \\\\", size + 1, k)); System.out.println("\\hline"); String diagBox = "\\diagbox{$\\mu$}{$\\lambda$}"; System.out.print(problems.length > 1 ? String.format("\\multirow{2}{*}{%s}", diagBox) : diagBox); for (int lambda : lambdas) System.out.print(String.format(" & \\multicolumn{%d}{c|}{%d}", problems.length, lambda)); System.out.println(" \\\\"); if (problems.length > 1) { System.out.println(String.format("\\cline{2-%d}", size + 1)); for (int ignored : lambdas) { for (Problems problem : problems) System.out.print(String.format(" & %s", problem.getName())); } System.out.println(" \\\\"); } for (int mu : mus) { System.out.println("\\hline"); System.out.print(mu); for (int lambda : lambdas) { for (Problems problem : problems) System.out.print(String.format(" & %d", getAverageLength(problem, problemDir, k, mu, lambda))); } System.out.println(" \\\\"); } } System.out.println("\\hline"); System.out.println("\\end{tabular}"); } }
JavaScript
UTF-8
668
4.59375
5
[]
no_license
// # // 16. 두 정수 사이의 합 // adder함수는 정수 x, y를 매개변수로 입력받는다. // 두 수와 두 수 사이에 있는 모든 정수를 더해서 리턴하도록 함수를 완성하라. // x와 y가 같은 경우는 둘 중 아무 수나 리턴한다. // x, y는 음수나 0, 양수일 수 있으며 둘의 대소 관계도 정해져 있지 않다. // 예를들어 x가 3, y가 5 이면 12 를 리턴한다. function adder(x, y) { res = 0; big_number = x > y ? x : y; small_number = x > y ? y : x; for (i = small_number; i <= big_number; i++) { res += i; } return res; } console.log(adder(3, 5)); // 12 console.log(adder(3, 3));
SQL
UTF-8
1,160
3.203125
3
[]
no_license
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `minhabase` -- -- -------------------------------------------------------- -- -- Estrutura da tabela `empregados` -- CREATE TABLE IF NOT EXISTS `empregados` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nome` varchar(100) NOT NULL, `endereco` varchar(255) NOT NULL, `salario` int(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ; -- -- Adicionando dados na tabela `empregados` -- INSERT INTO `empregados` (`id`, `nome`, `endereco`, `salario`) VALUES (1, 'Carlos Silva', 'Rua da Subida, 67, Brasil', 5000), (2, 'Victoria Moreira', 'Rua Tiradentes, 44, Brasil', 6500), (3, 'Livia Bastos', '25, Rue Lauriston, Paris', 8000); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Markdown
UTF-8
1,962
2.625
3
[]
no_license
# Roadmap | Product | Description | Recommended Start Time | Recommended Publish | | :--- | :--- | :--- | :--- | | Initial Website Release | Updating website for new conference information. | ~ Late April | ~ Early September | | Registration Open | Opens registration online, through whatever means. | As set by SGs. | As set by SGs. | | Social Media Push - Registration Open | Social media information on registration being open. | As set by SGs. | As set by SGs. | | Background Guides | Background Guides for each committee. | As set by SGs. | ~ Early February | | Rules of Procedure | Rules of Procedure, placed online, and printed out for special delegates. | ~ Late January | ~ Early February | | Delegate Package | Package given to every delegate, includes schedule, committee information, staff list, etc. Requires lots of information - please see page. | ~ Mid February | Last Week March | | Delegate Folders | Folders that encompass the delegate package, if needed. | ~ Mid February | Last Week February | | Registration Closes | Closing registration, which in turn allows all conference data to be generated and used. | ~ Mid to Late March | ~ Mid to Late March | | Nametags | Nametags for delegates, staff, and advisors. Requires registration to be closed. | ~ Mid March | Last Week March | | Placards | Placards for delegates. Requires registration to be closed, and finalized rules of procedure. | ~ Mid March | Last Week March | | Room Signs | Room Signs for each committee. Requires room positions to be finished. | ~ Mid March | Last Week March | | Notepads | Notepads for each delegate and staff, and extras. Requires number of delegates. | ~ Mid March | Last Week March | | Schedule Posters | Posters put around the school displaying scheduling. | Last Week March | Day of Conference | | Delegate Rubric | Rubric for delegate evaluation, goes into each delegate package. Requires number of delegates. | Last Week March | Day of Conference |
Java
UTF-8
2,786
2.09375
2
[]
no_license
import com.sun.deploy.net.HttpRequest; import org.jnetpcap.packet.PcapPacket; import org.jnetpcap.packet.structure.JField; import org.jnetpcap.protocol.application.Html; import org.jnetpcap.protocol.application.HtmlParser; import org.jnetpcap.protocol.network.Ip4; import org.jnetpcap.protocol.tcpip.Http; import org.jnetpcap.protocol.tcpip.Tcp; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; public class Session implements Runnable { private String sessionID; private Http http = new Http(); private boolean state; private UserEntry ue = new UserEntry(); private Tcp tcp; private PcapPacket pcap; private Ip4 ip = new Ip4(); public Session(PcapPacket packet) { tcp = packet.getHeader(new Tcp()); pcap = packet; http = packet.getHeader(new Http()); ip = packet.getHeader(new Ip4()); if(http != null) state = urlScriptTag(); } public void run() { if(state) { byte[] sIP = new byte[4]; sIP = ip.source(); System.out.println("XSS Cross site scripting detected"); ue.setSrcPort(Integer.toString(tcp.source())); ue.setDstPort(Integer.toString(tcp.destination())); ue.setAttacker(org.jnetpcap.packet.format.FormatUtils.ip(sIP)); ue.setProtocol("HTTP"); ue.setAttackType("XSS-Cross-site-scripting"); ue.setAttackInfo("Reflected-XSS"); ue.setAttackDescription("Attacker injected a HTML tag during a request"); ue.setHexDump(pcap.toHexdump()); Handler.sendMessage(TCP.sc, "XSS-Cross site scripting"); try { new Alert().insertDB(ue); } catch (Exception e) { e.printStackTrace(); } } //Alert/NotifyGUI/Store to database } public boolean urlScriptTag() { String request = http.fieldValue(Http.Request.RequestMethod); String url = http.fieldValue(Http.Request.RequestUrl); if(request != null) { //System.out.println(http.toHexdump()); if (request.equals("GET") || request.equals("POST")) { //System.out.println(http); return url.toLowerCase().contains("script") || url.toLowerCase().contains("cookie"); } } return false; } void htmlInjection() throws IOException { String request = http.fieldValue(Http.Request.RequestUrl); if(request != null) { if (request.contains("script")) { System.out.println("Alert Script url injection"); } } } }
Java
UTF-8
3,345
2.375
2
[]
no_license
package br.com.samir.baas.repository; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.bson.BsonInvalidOperationException; import org.bson.Document; import org.bson.conversions.Bson; import org.bson.types.ObjectId; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import br.com.samir.baas.database.Database; import br.com.samir.baas.exception.InvalidJsonObjectException; import br.com.samir.baas.exception.NonUniqueResultException; import br.com.samir.baas.exception.NotFoundException; @Repository public class BaasRepository { @Autowired private Database database; public String insert(String tableName, String jsonObject) throws InvalidJsonObjectException { MongoCollection<Document> collection = database.getDatabase().getCollection(tableName); Document document = parseJsonToDocument(jsonObject); collection.insertOne(document); return document.toJson(); } public void update(String tableName, String jsonObject, String id) throws InvalidJsonObjectException, NotFoundException { MongoCollection<Document> collection = database.getDatabase().getCollection(tableName); Document newDocument = parseJsonToDocument(jsonObject); newDocument.append("_id", new ObjectId(id)); Bson objectId = createBsonObjectWithId(id); Long modifiedCount = collection.replaceOne(objectId, newDocument).getModifiedCount(); if(modifiedCount == 0) { throw new NotFoundException(); } } public String findById(String tableName, String id) throws NotFoundException { Bson objectId = createBsonObjectWithId(id); MongoCursor<Document> iterator = database.getDatabase().getCollection(tableName).find(objectId).iterator(); return createSingleJsonElement(iterator); } public void remove(String tableName, String id) throws NotFoundException { Bson objectId = createBsonObjectWithId(id); Long deletedCount = database.getDatabase().getCollection(tableName) .deleteOne(objectId).getDeletedCount(); if(deletedCount == 0) { throw new NotFoundException(); } } public List<String> list(String tableName) { MongoCursor<Document> iterator = database.getDatabase().getCollection(tableName).find().iterator(); return createListjsonObjects(iterator); } private Bson createBsonObjectWithId(String id) throws NotFoundException { if(StringUtils.isBlank(id)) { throw new NotFoundException(); } return new Document().append("_id", new ObjectId(id)); } private Document parseJsonToDocument(String jsonObject) throws InvalidJsonObjectException { try { return Document.parse(jsonObject); } catch (BsonInvalidOperationException e) { throw new InvalidJsonObjectException(); } } private List<String> createListjsonObjects(MongoCursor<Document> iterator) { List<String> jsonObjects = new ArrayList<>(); while (iterator.hasNext()) { jsonObjects.add(iterator.next().toJson()); } return jsonObjects; } private String createSingleJsonElement(MongoCursor<Document> iterator) { List<String> jsonObjects = createListjsonObjects(iterator); if (jsonObjects.size() > 1) { throw new NonUniqueResultException(); } return jsonObjects.isEmpty() ? null : jsonObjects.get(0); } }
SQL
UTF-8
15,783
3.453125
3
[]
no_license
DROP DATABASE IF EXISTS DBMS; CREATE DATABASE DBMS; USE DBMS; DROP TABLE IF EXISTS Manuscript; DROP TABLE IF EXISTS Author; DROP TABLE IF EXISTS Issue; DROP TABLE IF EXISTS AcceptedManuscript; DROP TABLE IF EXISTS Feedback; DROP TABLE IF EXISTS BeingReviewed; DROP TABLE IF EXISTS ReviewerInterest; DROP TABLE IF EXISTS AreaOfInterest; DROP TABLE IF EXISTS Submission; DROP TABLE IF EXISTS Typeset; DROP TABLE IF EXISTS Returned; DROP TABLE IF EXISTS ManuHistory; DROP TABLE IF EXISTS Manu_Returned; DROP TABLE IF EXISTS RejectedManuscript; DROP TABLE IF EXISTS ReviewerAssignment; CREATE TABLE Manuscript ( Manuscript_Number varchar(3) primary key, Title varchar(15), Author_ID varchar(15), Manuscript_Type varchar(30), foreign key (Author_ID) references Submission (Author_ID) ); CREATE TABLE Author( Author_ID varchar(15) primary key, Author_Name varchar(15), Mail_Address varchar(30), Email_Address varchar(20), Affiliation varchar(25) ); CREATE TABLE Reviewer ( Reviewer_ID varchar(3) primary key, Reviewer_Name varchar(15), Reviewer_Affiliation varchar(25), Interest_ID varchar(6), Reviewer_Email varchar(25) ); CREATE TABLE AreaOfInterest ( Interest_ID varchar(6) primary key, Description varchar(20) ); CREATE TABLE Feedback ( Reviewer_ID varchar(3), Manuscript_ID varchar(3), Rating int, Recommendation varchar(10), dateReceieved date, primary key (Reviewer_ID, Manuscript_ID), foreign key (Reviewer_ID) references Reviewer (Reviewer_ID), foreign key (Manuscript_Number) references Manuscript (Manuscript_ID) ); CREATE TABLE AcceptedManuscript ( Manuscript_ID varchar(3) primary key, Issue_ID varchar(3), orderWithinIssue varchar(15), beginningPageNumber int, numberofPages int, AcceptedDate date, foreign key (Manuscript_ID) references Manuscript (Manuscript_ID), foreign key (Issue_ID) references Issue (Issue_ID) ); CREATE TABLE RejectedManuscript ( Manuscript_ID varchar(3) primary key, foreign key (Manuscript_ID) references Manuscript (Manuscript_ID), RejectedDate date ); CREATE TABLE Issue ( Issue_ID varchar(3) primary key, publicationPeriod varchar(10), publicationYear varchar(4), volume varchar(2), Issue_number varchar(3), printDate date ); CREATE TABLE ReviewerInterest ( Reviewer_ID varchar(3), Interest_ID varchar(6), primary key (Reviewer_ID, Interest_ID), foreign key (Reviewer_ID) references Reveiwer (Reviewer_ID), foreign key (Interest_ID) references AreaOfInterest (Interest_ID) ); CREATE TABLE Submission ( Manuscript_ID varchar(3), Author_ID varchar(15), submitDate date, AuthorOrder varchar(2), Manu_Status varchar(20), primary key (Manuscript_ID, Author_ID), foreign key (Manuscript_ID) references Manuscript (Manuscript_ID), foreign key (Author_ID) references Author (Author_ID) ); CREATE TABLE Being_Reviewed ( Manuscript_ID varchar(3) primary key, foreign key (Manuscript_ID) references Manuscript (Manuscript_ID) ); CREATE TABLE ReviewerAssignment ( Manuscript_ID varchar(3), Reviewer_ID varchar(3), dateSentToReviewer date, primary key (Manuscript_ID, Reviewer_ID), foreign key (Manuscript_ID) references Manuscript (Manuscript_ID), foreign key (Reviewer_ID) references ReviewerAssignment (Reviewer_ID) ); CREATE TABLE Typeset ( Manuscript_ID varchar(3), Issue_ID varchar(3), Font varchar(10), Font_Size int, Line_Spacing varchar(10), Justification varchar(20), primary key (Manuscript_ID, Issue_ID), foreign key (Manuscript_ID) references AcceptedManuscript (Manuscript_ID), foreign key (Issue_ID) references Issue (Issue_ID) ); CREATE TABLE Manu_Returned ( Manuscript_ID varchar(3) primary key, Return_Status varchar(10), Return_Date date ); CREATE TABLE Manuscript_History ( Manuscript_ID varchar(3), Manuscript_Hist_Status varchar(15), ManuHisDate date, primary key (Manuscript_ID), foreign key (Manuscript_ID) references Manuscript (Manuscript_ID) ); #Manuscript INSERT INTO Manuscript VALUES ('001', 'History', 'Published', 'Case Studies'); INSERT INTO Manuscript VALUES ('002', 'Computers', 'Rejected', 'Original Research'); INSERT INTO Manuscript VALUES ('003', 'Computers2', 'Accepted', 'Original Research'); INSERT INTO Manuscript VALUES ('004', 'Math', 'Under Review', 'Original Research'); INSERT INTO Manuscript VALUES ('005', 'Science', 'Published', 'Communication'); INSERT INTO Manuscript VALUES ('006', 'Biology', 'Scheduled', 'Communication'); INSERT INTO Manuscript VALUES ('007', 'Calculus', 'Returned', 'Original Research'); INSERT INTO Manuscript VALUES ('008', 'Phys Ed.', 'Returned', 'Original Research'); INSERT INTO Manuscript VALUES ('009', 'Chemistry', 'Rejected', 'Case Study'); #Authors INSERT INTO Author VALUES ('111', 'John Mayer', '123 Harper St.', 'JMayer@gmail.com', 'High School'); INSERT INTO Author VALUES ('112', 'Alice Light', '156 Wallace Ave', 'ALight@yahoo.com', 'Comp Tech'); INSERT INTO Author VALUES ('113', 'Robert Lander', '535 Lamper St.', 'RLander@aol.com', 'Math Club'); INSERT INTO Author VALUES ('114', 'Forest Law', '004 Tecken St.', 'ForLaw3@hotmail.com', 'Hospital'); INSERT INTO Author VALUES ('115', 'Jessica Quest', '229 Alexandra Blvd', 'JQuest56@msn.com', 'Medical Center'); #Submission INSERT INTO Submission Values ('001', '111', '2018/03/01', '01'); INSERT INTO Submission Values ('001', '112', '2018/03/01', '02'); INSERT INTO Submission Values ('001', '113', '2018/03/01', '03'); INSERT INTO Submission Values ('002', '112', '2018/03/01', '01'); INSERT INTO Submission Values ('002', '113', '2018/03/01', '02'); INSERT INTO Submission Values ('002', '114', '2018/03/01', '03'); INSERT INTO Submission Values ('003', '112', '2018/03/04','01'); INSERT INTO Submission Values ('003', '113', '2018/03/04','02'); INSERT INTO Submission Values ('004', '113', '2018/03/04', '01'); INSERT INTO Submission Values ('004', '114', '2018/03/04', '02'); INSERT INTO Submission Values ('004', '115', '2018/03/04', '03'); INSERT INTO Submission Values ('005', '114', '2018/03/07', '01'); INSERT INTO Submission Values ('005', '115', '2018/03/07', '02'); INSERT INTO Submission Values ('005', '111', '2018/03/07', '03'); INSERT INTO Submission Values ('006', '114', '2018/03/07', '01'); INSERT INTO Submission Values ('007', '113', '2018/03/09', '01'); INSERT INTO Submission Values ('007', '114', '2018/03/09', '02'); INSERT INTO Submission Values ('008', '115', '2018/03/09', '01'); INSERT INTO Submission Values ('009', '112', '2018/03/10', '01'); INSERT INTO Submission Values ('009', '113', '2018/03/10', '02'); #Manu_Returned INSERT INTO Manu_Returned VALUES ('007', 'Returned', '2018/03/10'); INSERT INTO Manu_Returned VALUES ('008', 'Returned', '2018/03/11'); #Reviewer INSERT INTO Reviewer VALUES('123', 'Lenny Jenkins', 'High School', '900', 'LenJen@gmail.com'); INSERT INTO Reviewer VALUES('124', 'Wallace Menk', 'Medical Center', '901', 'WallyMenk@yahoo.com'); INSERT INTO Reviewer VALUES('125', 'Jennifer Pret', 'Hospital', '901', 'JPret@aol.com'); INSERT INTO Reviewer VALUES('126', 'Raul Ortiz', 'Music Club', '903', 'ROrtiz@aol.com'); INSERT INTO Reviewer VALUES('127', 'Jacob Key', 'Math Club', '904', 'JKey@hotmail.com'); INSERT INTO Reviewer VALUES('128', 'Emma Poppie', 'Medical Center', '901', 'EmmiePop@gmail.com'); INSERT INTO Reviewer VALUES('129', 'Julia Makoto', 'Comp Tech', '906', 'JMakoto@msn.com'); INSERT INTO Reviewer VALUES('130', 'Taylor Font', 'Biology Club', '901', 'FontTay@msn.com'); INSERT INTO Reviewer VALUES('131', 'Robert Zen', 'High School', '900', 'RZen@hotmail.com'); #ReviewerAssignment INSERT INTO ReviewerAssignment VALUES ('001', '123', '2018/03/04'); INSERT INTO ReviewerAssignment VALUES ('001', '124', '2018/03/04'); INSERT INTO ReviewerAssignment VALUES ('001', '126', '2018/03/04'); INSERT INTO ReviewerAssignment VALUES ('001', '131', '2018/03/05'); INSERT INTO ReviewerAssignment VALUES ('002', '123', '2018/03/06'); INSERT INTO ReviewerAssignment VALUES ('002', '125', '2018/03/06'); INSERT INTO ReviewerAssignment VALUES ('002', '130', '2018/03/06'); INSERT INTO ReviewerAssignment VALUES ('003', '127', '2018/03/05'); INSERT INTO ReviewerAssignment VALUES ('003', '129', '2018/03/05'); INSERT INTO ReviewerAssignment VALUES ('003', '123', '2018/03/05'); INSERT INTO ReviewerAssignment VALUES ('003', '124', '2018/03/08'); INSERT INTO ReviewerAssignment VALUES ('004', '127', '2018/03/06'); INSERT INTO ReviewerAssignment VALUES ('004', '129', '2018/03/06'); INSERT INTO ReviewerAssignment VALUES ('004', '131', '2018/03/07'); INSERT INTO ReviewerAssignment VALUES ('004', '128', '2018/03/07'); INSERT INTO ReviewerAssignment VALUES ('005', '123', '2018/03/08'); INSERT INTO ReviewerAssignment VALUES ('005', '129', '2018/03/08'); INSERT INTO ReviewerAssignment VALUES ('005', '127', '2018/03/09'); INSERT INTO ReviewerAssignment VALUES ('005', '128', '2018/03/09'); INSERT INTO ReviewerAssignment VALUES ('005', '125', '2018/03/09'); INSERT INTO ReviewerAssignment VALUES ('006', '126', '2018/03/10'); INSERT INTO ReviewerAssignment VALUES ('006', '130', '2018/03/10'); INSERT INTO ReviewerAssignment VALUES ('006', '131', '2018/03/11'); INSERT INTO ReviewerAssignment VALUES ('006', '129', '2018/03/11'); INSERT INTO ReviewerAssignment VALUES ('009', '124', '2018/03/10'); INSERT INTO ReviewerAssignment VALUES ('009', '130', '2018/03/10'); INSERT INTO ReviewerAssignment VALUES ('009', '125', '2018/03/12'); INSERT INTO ReviewerAssignment VALUES ('009', '128', '2018/03/12'); #BeingReviewed INSERT INTO BeingReviewed VALUES ('001'); INSERT INTO BeingReviewed VALUES ('002'); INSERT INTO BeingReviewed VALUES ('003'); INSERT INTO BeingReviewed VALUES ('004'); INSERT INTO BeingReviewed VALUES ('005'); INSERT INTO BeingReviewed VALUES ('006'); INSERT INTO BeingReviewed VALUES ('009'); #ReviewerInterest INSERT INTO ReviewerInterest VALUES ('123', '900'); INSERT INTO ReviewerInterest VALUES ('124', '901'); INSERT INTO ReviewerInterest VALUES ('125', '901'); INSERT INTO ReviewerInterest VALUES ('126', '903'); INSERT INTO ReviewerInterest VALUES ('127', '904'); INSERT INTO ReviewerInterest VALUES ('128', '901'); INSERT INTO ReviewerInterest VALUES ('129', '906'); INSERT INTO ReviewerInterest VALUES ('130', '901'); INSERT INTO ReviewerInterest VALUES ('131', '900'); #AreaOfInterest INSERT INTO AreaOfInterest VALUES ('900', 'School Basics'); INSERT INTO AreaOfInterest VALUES ('901', 'Medical Information'); INSERT INTO AreaOfInterest VALUES ('903', 'Musical Theory'); INSERT INTO AreaOfInterest VALUES ('904', 'Mathematics'); INSERT INTO AreaOfInterest VALUES ('906', 'Computer Technology'); #ManuscriptHistory INSERT INTO ManuscriptHistory VALUES ('001', 'Submitted', '2018/03/01'); INSERT INTO ManuscriptHistory VALUES ('001', 'Under Review', '2018/03/04'); INSERT INTO ManuscriptHistory VALUES ('001', 'Accepted', '2018/03/15'); INSERT INTO ManuscriptHistory VALUES ('001', 'Scheduled', '2018/04/03'); INSERT INTO ManuscriptHistory VALUES ('001', 'Published', '2018/05/19'); INSERT INTO ManuscriptHistory VALUES ('002', 'Submitted', '2018/03/01'); INSERT INTO ManuscriptHistory VALUES ('002', 'Under Review', '2018/03/06'); INSERT INTO ManuscriptHistory VALUES ('002', 'Rejected', '2018/03/10'); INSERT INTO ManuscriptHistory VALUES ('003', 'Submitted', '2018/03/04'); INSERT INTO ManuscriptHistory VALUES ('003', 'Under Review', '2018/03/05'); INSERT INTO ManuscriptHistory VALUES ('004', 'Submitted', '2018/03/04'); INSERT INTO ManuscriptHistory VALUES ('004', 'Under Review', '2018/03/06'); INSERT INTO ManuscriptHistory VALUES ('004', 'Accepted', '2018/03/16'); INSERT INTO ManuscriptHistory VALUES ('005', 'Submitted', '2018/03/07'); INSERT INTO ManuscriptHistory VALUES ('005', 'Under Review', '2018/03/08'); INSERT INTO ManuscriptHistory VALUES ('005', 'Accepted', '2018/03/15'); INSERT INTO ManuscriptHistory VALUES ('005', 'Scheduled', '2018/04/15'); INSERT INTO ManuscriptHistory VALUES ('005', 'Published', '2018/08/19'); INSERT INTO ManuscriptHistory VALUES ('006', 'Submitted', '2018/03/07'); INSERT INTO ManuscriptHistory VALUES ('006', 'Under Review', '2018/03/10'); INSERT INTO ManuscriptHistory VALUES ('006', 'Accepted', '2018/03/15'); INSERT INTO ManuscriptHistory VALUES ('007', 'Submitted', '2018/03/09'); INSERT INTO ManuscriptHistory VALUES ('007', 'Returned', '2018/03/10'); INSERT INTO ManuscriptHistory VALUES ('008', 'Submitted', '2018/03/09'); INSERT INTO ManuscriptHistory VALUES ('008', 'Returned', '2018/03/12'); INSERT INTO ManuscriptHistory VALUES ('009', 'Submitted', '2018/03/10'); INSERT INTO ManuscriptHistory VALUES ('009', 'Under Review', '2018/03/12'); INSERT INTO ManuscriptHistory VALUES ('009', 'Rejected', '2018/03/20'); #RejectedManuscript INSERT INTO RejectedManuscript VALUES ('002', '2018/03/10'); INSERT INTO RejectedManuscript VALUES ('009', '2018/03/20'); #AcceptedManuscript INSERT INTO AcceptedManuscript VALUES ('001', '010', 'Middle' , 35, 11, '2018/03/22'); INSERT INTO AcceptedManuscript VALUES ('004', '011', 'Beginning', 05, 12, '2018/03/23'); INSERT INTO AcceptedManuscript VALUES ('005', '012', 'End', 53, 10, '2018/03/27'); INSERT INTO AcceptedManuscript VALUES ('006', '014', 'Middle', 31, 10, '2018/03/29'); INSERT INTO AcceptedManuscript VALUES ('007', '015', 'Beginning', 10, 06, '2018/03/39'); #Issue INSERT INTO Issue VALUES ('010', 'Summer', '2018', 05, '07', '2018/05/25'); INSERT INTO Issue VALUES ('011', 'Autumn', '2018', 03, '10', '2018/09/03'); INSERT INTO Issue VALUES ('012', 'Winter', '2018', 10, '15', '2018/12/05'); INSERT INTO Issue VALUES ('013', 'Winter', '2019', 07, '16', '2019/01/09'); INSERT INTO Issue VALUES ('014', 'Spring', '2019', 12, '18', '2019/03/22'); INSERT INTO Issue VALUES ('015', 'Spring', '2019', 02, '20', '2019/04/15'); #Typeset INSERT INTO Typeset VALUES ('001', '010', 'Arial', 14, 'Double', 'Research'); INSERT INTO Typeset VALUES ('004', '011', 'Cursive', 12, 'Single', 'Problem Solving'); INSERT INTO Typeset VALUES ('005', '012', 'Cursive', 12, 'Single', 'Research'); INSERT INTO Typeset VALUES ('006', '014', 'Calibri', 10, 'Double', 'Teaching'); #Feedback INSERT INTO Feedback VALUES ('001', '123', 08, 'Yes', '2018/03/05'); INSERT INTO Feedback VALUES ('001', '124', 08, 'Yes', '2018/03/05'); INSERT INTO Feedback VALUES ('001', '126', 07, 'Yes', '2018/03/08'); INSERT INTO Feedback VALUES ('001', '131', 08, 'Yes', '2018/03/13'); INSERT INTO Feedback VALUES ('002', '123', 03, 'No', '2018/03/08'); INSERT INTO Feedback VALUES ('002', '125', 04, 'No', '2018/03/09'); INSERT INTO Feedback VALUES ('002', '130', 06, 'Yes', '2018/03/11'); INSERT INTO Feedback VALUES ('003', '127', 07, 'Yes', '2018/03/08'); INSERT INTO Feedback VALUES ('003', '129', 05, 'No', '2018/03/09'); INSERT INTO Feedback VALUES ('003', '123', 08, 'Yes', '2018/03/10'); INSERT INTO Feedback VALUES ('003', '124', 07, 'Yes', '2018/03/11'); INSERT INTO Feedback VALUES ('004', '127', 10, 'Yes', '2018/03/09'); INSERT INTO Feedback VALUES ('004', '129', 08, 'Yes', '2018/03/10'); INSERT INTO Feedback VALUES ('004', '131', 09, 'Yes', '2018/03/10'); INSERT INTO Feedback VALUES ('004', '128', 09, 'Yes', '2018/03/12'); INSERT INTO Feedback VALUES ('005', '123', 08, 'Yes', '2018/03/10'); INSERT INTO Feedback VALUES ('005', '129', 09, 'Yes', '2018/03/12'); INSERT INTO Feedback VALUES ('005', '127', 08, 'Yes', '2018/03/12'); INSERT INTO Feedback VALUES ('005', '128', 08, 'Yes', '2018/03/14'); INSERT INTO Feedback VALUES ('005', '125', 07, 'Yes', '2018/03/15'); INSERT INTO Feedback VALUES ('006', '126', 07, 'Yes', '2018/03/13'); INSERT INTO Feedback VALUES ('006', '130', 06, 'No', '2018/03/15'); INSERT INTO Feedback VALUES ('006', '131', 08, 'Yes', '2018/03/15'); INSERT INTO Feedback VALUES ('006', '129', 08, 'Yes', '2018/03/17'); INSERT INTO Feedback VALUES ('009', '124', 04, 'No', '2018/03/16'); INSERT INTO Feedback VALUES ('009', '130', 05, 'Yes', '2018/03/16'); INSERT INTO Feedback VALUES ('009','125', 03, 'No', '2018/03/17'); INSERT INTO Feedback VALUES ('009','128', 04, 'No', '2018/03/20');
JavaScript
UTF-8
9,963
2.84375
3
[ "MIT" ]
permissive
import Mario from '../prefabs/mario' import Clouds from '../prefabs/clouds' import Hills from '../prefabs/hills' import Bushes from '../prefabs/bushes' import Ground from '../prefabs/ground' import Dialog from '../prefabs/dialog' import Score from '../prefabs/score' import PowerUpFactory from '../prefabs/powerups/powerupfactory' import EnemyFactory from '../prefabs/enemies/enemyfactory' import config from '../config' class Game extends Phaser.State { /* set ready to false, since we don't want the game to start straight away. * tap count allows us to prevent mario from jumping on first tap. * create a sounds array, we use this in create to load various sounds. */ constructor() { super(); this.ready = false; this.tapCount = 0; this.sounds = []; } /* * here we set up physics, set the world bounds and create the scenery * we display a dialog to create a narrative, when the player taps on it the * game will begin. */ create() { this.game.physics.startSystem(Phaser.Physics.ARCADE); this.game.physics.arcade.gravity.y = config.GRAVITY; this.game.world.setBounds(0, 0, this.game.width, this.game.height); this.clouds = new Clouds(this.game); this.hills = new Hills(this.game); this.bushes = new Bushes(this.game); this.ground = new Ground(this.game); this.dialog = new Dialog(this.game); this.dialog.events.onInputDown.add(this.hideDialog, this); // music this.overworld = this.game.add.audio('overworld', config.VOLUME, true); // sounds ['pipe', 'coin'].forEach(el => this.sounds[el] = this.game.add.audio(`${el}`, config.VOLUME)); // add score this.score = new Score(this.game); // drop mario into the game this.mario = new Mario(this.game, 128, -200); // play the pipe sound this.sounds['pipe'].play(); // fade in dialog this.game.add.tween(this.dialog).to({alpha: 1}, 0, Phaser.Easing.Linear.None, true, 500); // tap listener this.game.input.onDown.add(this.onTap, this); // create a power ups group this.powerUps = this.game.add.group(); // create an enemies group this.enemies = this.game.add.group(); // set up the objects that collide with ground this.collisionGroup = [this.mario, this.powerUps, this.enemies]; // variables to keep track of spawning power ups and enemies this.lastSpawnTime = 0; this.spawnInterval = Math.random() * config.SPAWNINTERVAL.MAX + config.SPAWNINTERVAL.MIN; } /* * this is the main game loop, it is responsible for keeping enemies, power ups and mario * on the ground. we create a collision handler so we can decide what happens when * mario collides with a power up or enemy */ update() { if (!this.mario.alive) { // very important! keeps mario from getting stuck during death animation delete this.collisionGroup[0] } // keeps marios, enemies and power ups on ground this.game.physics.arcade.collide(this.collisionGroup, this.ground); // collision handler for mario, enemies and power ups this.game.physics.arcade.overlap(this.mario, [this.enemies, this.powerUps], this.onOverlap, null, this); // do this while game is ready and mario is alive if (this.ready && this.mario.alive) { this.ground.move(this.mario.speed); this.clouds.move(); this.hills.move(); this.bushes.move(); // run as long as mario is touching the ground if (this.mario.body.touching.down) { this.mario.run(); } // loop over each power up this.powerUps.forEach(powerUp => { // match marios speed powerUp.x -= this.mario.speed; }); // loop over each enemy this.enemies.forEach(enemy => { // use enemies speed if defined or match marios speed typeof enemy.speed !== 'undefined' ? enemy.x -= this.mario.speed + enemy.speed : enemy.x -= this.mario.speed; // reward points if mario is has jumped over enemy and enemy is alive if (this.mario.x > (enemy.x + enemy.width) && this.mario.y < enemy.y && enemy.alive === true) { this.rewardPoints(enemy); } }); // call spawn timer function this.spawnTimer(); } } /* * this function adds a floating score animation on mario it is called when he collides * with a power up or when he has successfully jumped over an enemy. * it takes an object as a parameter, which may be an enemy or power up from this we can determine * how many points to give the player */ rewardPoints(object) { // creates a floating score animation on mario let reward = this.game.add.bitmapText(this.mario.x, this.mario.y, 'press_start_2p', `${object.points}`, 24); reward.anchor.setTo(0.5); this.game.add.tween(reward).to({ y: this.mario.y - 50, alpha: 0 }, 1000, Phaser.Easing.Linear.None, true); // increment score according to the objects points this.score.setScore(object.points); this.sounds['coin'].play(); // kill the object so player can't be awarded any more points object.kill(); } /* * make sure we dont consume too much resources by destroying * enemies and power ups which drift of the screen to the left */ outOfBounds(object) { object.destroy(); } /* * this timer is responsible for deciding when to spawn new enemies and power ups * SPAWNINTERVAL.MAX and SPAWNINTERVAL.MIN may be changed in the config file to make the * game easier or more challenging */ spawnTimer() { let currentTime = this.game.time.time; // if current time - last spawn time is greater than spawn interval if (currentTime - this.lastSpawnTime > this.spawnInterval) { // set new random spawn interval between given range this.spawnInterval = Math.floor(Math.random() * config.SPAWNINTERVAL.MAX + config.SPAWNINTERVAL.MIN); // set last spawn time to now this.lastSpawnTime = currentTime; // call spawn random function this.spawnRandom(); } } /* * spawns a power up if three conditions are true, 1. 50/50 chance Math.floor(Math.random() * 2) === 0 * 2. mario must be small and 3. there must be no other power ups on the screen, else spawn an enemy. */ spawnRandom() { if (Math.floor(Math.random() * 2) === 0 && this.mario.size === 'small' && this.powerUps.children.length === 0) { // uses PowerUpFactory to get a random instance of a power up let PowerUp = PowerUpFactory(); this.powerUp = new PowerUp(this.game); // do this when power up goes off screen this.powerUp.events.onOutOfBounds.add(this.outOfBounds, this); // add to power up group so we can keep track of it this.powerUps.add(this.powerUp); } else { // uses EnemyFactory to get a random instance of an enemy let Enemy = EnemyFactory(); this.enemy = new Enemy(this.game); // do this when enemy goes off screen this.enemy.events.onOutOfBounds.add(this.outOfBounds, this); // add to enemy group so we can keep track of it this.enemies.add(this.enemy); } } /* * main logic for checking collisions between mario and other objects. */ onOverlap(mario, object) { // check if object belongs to power up group if (this.powerUps.children.indexOf(object) > -1) { // was mario small and on the ground ? if (this.mario.size === 'small' && this.mario.body.touching.down) { // triggers the reward points animation and increments score // and make mario grow this.rewardPoints(object); this.mario.grow(object.health); object.destroy(); } // check if object belongs to enemy group, mario is alive and not invulnerable and object is alive } else if (this.enemies.children.indexOf(object) > -1 && this.mario.alive && !this.mario.invulnerable && object.alive) { // mario was hit! if (this.mario.health <= 50) { // trigger mario death sequence this.marioDeath(); } else { // inflict damage on mario and shrink him this.mario.shrink(object.damage); // kill the object so it can't damage the player again object.kill(); } } } /* * stops the update loop and triggers marios death sequence * loads the game over state in 3 seconds passing in the player's score */ marioDeath() { this.ready = false; this.overworld.stop(); this.mario.kill(); this.game.time.events.add(3000, () => this.game.state.start('gameover', true, false, this.score.score), this); } /* * hides the opening dialog and kicks off the gameplay */ hideDialog() { if (this.dialog.alpha === 1) { this.dialog.alpha = 0; this.overworld.play(); this.ready = true; } this.tapCount++; } /* * function for making mario jump, game must be ready and mario must be touching down */ onTap() { if (this.ready && this.mario.body.touching.down && this.tapCount >= 1) { this.mario.jump(); } } } export default Game
JavaScript
UTF-8
3,363
4.125
4
[]
no_license
/* Задание "Шифр цезаря": https://uk.wikipedia.org/wiki/%D0%A8%D0%B8%D1%84%D1%80_%D0%A6%D0%B5%D0%B7%D0%B0%D1%80%D1%8F Написать функцию, которая будет принимать в себя слово и количество симовлов на которые нужно сделать сдвиг внутри. Написать функцию дешефратор которая вернет слово в изначальный вид. Сделать статичные функции используя bind и метод частичного вызова функции (каррирования), которая будет создавать и дешефровать слова с статично забитым шагом от одного до 5. const isMobile = document.innerWidth < 768; Например: encryptCesar( 3, 'Word'); encryptCesar1(...) ... encryptCesar5(...) decryptCesar1(3, 'Sdwq'); decryptCesar1(...) ... decryptCesar5(...) "а".charCodeAt(); // 1072 String.fromCharCode(189, 43, 190, 61) // ½+¾ */ let alfabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]; function encryptCesar(index, word){ let newWord = []; let toArray = word.split(""); let positionNumber = 0; let alfabetLength = alfabet.length-1; for(let i = 0; i < toArray.length; i++ ){ for(let j = 0; j < alfabet.length; j++ ){ if(toArray[i] == alfabet[j]){ positionNumber = j + index; if(positionNumber > alfabetLength){ positionNumber = positionNumber - alfabet.length; newWord.push(alfabet[positionNumber]); }else { newWord.push(alfabet[positionNumber]); } } } } return newWord.join(''); } let test = encryptCesar(3, "xena"); console.log(test); function decryptCesar(index, word){ let Word = []; let toArray = word.split(""); let positionNumber = 0; for(let i = 0; i < toArray.length; i++ ){ for(let j = 0; j < alfabet.length; j++ ){ if(toArray[i] == alfabet[j]){ positionNumber = j - index; if(positionNumber < 0){ positionNumber = positionNumber * (-1); positionNumber = alfabet.length - positionNumber; Word.push(alfabet[positionNumber]); }else { Word.push(alfabet[positionNumber]); } } } } return Word.join(''); } let test2 = decryptCesar(3, test); console.log(test2); // Сделать статичные функции используя bind и метод частичного // вызова функции (каррирования), которая будет создавать и дешефровать // слова с статично забитым шагом от одного до 5. // function encryptCesar5(){ // let index = Math.floor(Math.random()*(5-1)+1); // // } // let encryptCesarStatic = encryptCesar.bind( encryptCesar5,3, "wood" ); // encryptCesarStatic(); // console.log(encryptCesarStatic());
Python
UTF-8
904
2.671875
3
[]
no_license
import os import json dir = "annotations" files = sorted(os.listdir(dir)) words = [] for file in files: words_cur = [] with open(dir + "/" + file) as f: json_content = json.load(f) for box in json_content["form"]: words_cur.extend(box["text"].split()) words.append(words_cur) # print(words_cur) dir_outputs = "doc-kraken-outputs" output_files = sorted(os.listdir(dir_outputs)) for i in range(len(output_files)): output = [] with open(dir_outputs + "/" + output_files[i]) as f: for line in f: output.extend(line.strip().split()) count = 0 for word in output: if word in words[i]: count += 1 accuracy = count / len(words[i]) print(output) print(words[i]) print(accuracy) print("") with open("kraken_docs_accuracy.txt", "a") as f: f.write(str(accuracy) + "\n")
Python
UTF-8
336
2.765625
3
[]
no_license
import unittest from datetime import datetime, timedelta from project import get_last_value_date today = datetime.now() yesterday = (today - timedelta(1)).strftime('%Y-%m-%d') class LastValueDateTestCase(unittest.TestCase): def test_value(self): result = get_last_value_date() self.assertEqual(yesterday, result)
C++
UTF-8
1,867
3.140625
3
[]
no_license
/* * ===================================================================================== * Filename : TheGreatGame.cpp * Description : So Funny * Version : 0.1 * Created : 04/29/14 07:58 * Author : Liu Xue Yang (LXY), liuxueyang457@163.com * Motto : How about today? * ===================================================================================== */ #include <cstdlib> #include <cstdio> #include <cstring> using namespace std; /* * === FUNCTION ====================================================================== * Name: judge * Description: who win? * ===================================================================================== */ int judge ( char a, char b ) { if ( a=='[' ) { if ( b=='[' ) { return 0; } else if ( b=='(' ) { return 1; } else { return -1; } } if ( a=='(' ) { if ( b=='[' ) { return -1; } else if ( b=='(' ) { return 0; } else { return 1; } } if ( a=='8' ) { if ( b=='[' ) { return 1; } else if ( b=='(' ) { return -1; } else { return 0; } } return 0; } /* ----- end of function judge ----- */ /* * === FUNCTION ====================================================================== * Name: main * ===================================================================================== */ int main ( int argc, char *argv[] ) { char a[21], b[21]; scanf ( "%s%s", a, b ); int len = strlen(a), wina = 0, winb = 0; for ( int i = 0; i < len; i+=2 ) { int tmp = judge(a[i], b[i]); if ( tmp > 0 ) { ++wina; } else if ( tmp < 0 ) { ++winb; } } if ( wina > winb ) { printf ( "TEAM 1 WINS\n" ); } else if ( wina < winb ) { printf ( "TEAM 2 WINS\n" ); } else { printf ( "TIE\n" ); } return EXIT_SUCCESS; } /* ---------- end of function main ---------- */
Swift
UTF-8
1,235
2.71875
3
[]
no_license
// // ViewController_Player.swift // LTM-interface // // Created by Louis Lenief on 09/05/2018. // Copyright © 2018 Louis Lenief. All rights reserved. // import Foundation import AVKit extension ViewController { func playSelectedVideo() { if let video = getSelectedVideo() { player?.replaceCurrentItem(with: AVPlayerItem(url: video.url)) player?.play() } } func goToFrame(frame: Int) { if let video = getSelectedVideo() { let s = Double(frame)/video.framerate player?.seek(to: CMTime(seconds: s, preferredTimescale: 60), toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero) } } /* menu action handlers */ @IBAction func menuTogglePlay(_ sender: Any) { if let p = player { if p.rate != 0.0 { p.pause() } else { p.play() } } } @IBAction func menuRestart(_ sender: Any) { playSelectedVideo() } @IBAction func menuSetRate(_ sender: Any) { if let menuItem = sender as? NSMenuItem { let newRate = Float(menuItem.title) player?.rate = newRate! } } }
JavaScript
UTF-8
1,280
3.484375
3
[]
no_license
function KilometerToMeter(distance) { var convert=distance*1000; return convert; } var result=KilometerToMeter(50); console.log(result); //budgetCalculator// function budgetCalculator(watch,phone,laptop) { var watchQuantity=watch*50; var phoneQuantity=phone*100; var laptopQuantity=laptop*500; return watchQuantity ,phoneQuantity, laptopQuantity;; } var total=budgetCalculator(5,10,15); console.log(total); //hotelCost// function hotelCost(days){ var cost=0; if(days<=10) { cost=days*100; } else if(days<=20){ var firstTen=10*100; var remaining=days-10; var secondTen=remaining*80; cost=firstTen+secondTen; } else{ firstTen=10*100; secondTen=10*80; remaining=days-20; var thirdPortion=remaining*50; cost=firstTen+secondTen+thirdPortion; } return cost; } var total=hotelCost(18); console.log(total); function megaFriend(names){ var max=[0]; for(var i=0;i<names.length;i++){ var string=names[i]; if(string.length>max.length){ max=string; } } return max; } var names=['salam','doly','jui','farhana','shumi','asadnurjaved']; var biggest=megaFriend(names); console.log(biggest);
Markdown
UTF-8
476
2.5625
3
[]
no_license
# Directory Contents List of directory contents using PHP Easy to list of localhost directory project folder especially document of sites or www or htdocs. # Setup Put folder in your directory Example: ```php /var/www /Library/WebServer/Documents /Xampp/htdocs ``` ## Set path Please change path in class.index.php in line 18 ```php $this->dir = "Your_Folder_Path"; ``` ![directory](https://raw.githubusercontent.com/mzm-dev/directory_contents/master/img/photo.png)
C#
UTF-8
928
2.625
3
[ "MIT" ]
permissive
using System.Collections; using System.Collections.Generic; using UnityEngine; public abstract class mono : MonoBehaviour { public float[] fill = new float[1024]; private bool[] doneBox = { false }; protected int length; public mono[] monoInputs = new mono[0]; public Knob[] knobInputs = new Knob[0]; public float[] gibSignal(List<bool[]> doneBoxes) { if (!doneBox[0]) { doneBox[0] = true; doneBoxes.Add(doneBox); getSignal(doneBoxes); } return fill; } /// <summary> /// build "fill" to length /// </summary> /// <param name="length"></param> /// <returns>A float array </returns> abstract protected void getSignal(List<bool[]> doneBoxes);//nobody else should ever call this public virtual void setLength(int length) { fill = new float[length]; this.length = length; } public int getNumMonos() { return monoInputs.Length; } public int getNumKnobs() { return knobInputs.Length; ; } }
Ruby
UTF-8
1,240
2.640625
3
[]
no_license
# frozen_string_literal: true # 1/5/2018: specs complete, help complete. require 'shellwords' class Pomodoro::Commands::Commit < Pomodoro::Commands::Command self.help = <<-EOF.gsub(/^\s*/, '') now <magenta>commit</magenta> <bright_black># #{self.description}</bright_black> now <magenta>commit</magenta> -a|-v now <magenta>commit</magenta> spec For this to work you have to be in the right directory. If the current task has a numeric tag (i. e. <bright_black>#112</bright_black>), then it will be closed using the <bright_black>Closes #num</bright_black> syntax. EOF def run ensure_today if with_active_task(self.config) do |active_task| tag = active_task.tags.find { |tag| tag.match(/^\d+$/) } body = [active_task.body, tag && "Closes ##{tag}"].compact.join(' ') # TODO: closes vs. mention only? Shall we use commit -v? commit_message = Shellwords.escape(body) arguments = [*@args, '-m', commit_message].join(' ') puts("#{t(:log_command, commit_message: commit_message)}\n\n") command("git commit #{arguments}") end else abort t(:no_task_in_progress) # TODO: raise NoTaskInProgress. end end end
Java
UTF-8
8,176
2.140625
2
[]
no_license
package com.eshokin.socs.screens.main; import com.arellomobile.mvp.InjectViewState; import com.eshokin.socs.R; import com.eshokin.socs.api.ApiService; import com.eshokin.socs.api.enumerations.Interval; import com.eshokin.socs.api.schemas.Point; import com.eshokin.socs.api.schemas.requests.GetStatisticsMethodRequest; import com.eshokin.socs.api.schemas.responses.GetStatisticsMethodResponse; import com.eshokin.socs.calculating.Calculating.MinMax; import com.eshokin.socs.jobs.CalculateAverageJob; import com.eshokin.socs.jobs.CalculateInterquartileRangeJob; import com.eshokin.socs.jobs.CalculateMedianJob; import com.eshokin.socs.jobs.CalculateMinMaxJob; import com.eshokin.socs.screens.base.BasePresenter; import com.eshokin.socs.screens.main.di.MainComponent; import com.eshokin.socs.utils.Rx; import com.path.android.jobqueue.JobManager; import java.util.Calendar; import java.util.Date; import java.util.List; import javax.inject.Inject; import io.reactivex.Observable; import io.reactivex.disposables.Disposable; import io.reactivex.subjects.PublishSubject; @InjectViewState public class MainPresenter extends BasePresenter<MainView> { private Date mStartDate; private Date mEndDate; private PublishSubject<MinMax> mMinMaxSubject = PublishSubject.create(); private PublishSubject<Double> mAverageSubject = PublishSubject.create(); private PublishSubject<Double> mMedianSubject = PublishSubject.create(); private PublishSubject<Double> mInterquartileRangeSubject = PublishSubject.create(); @Inject ApiService mApiService; @Inject JobManager mJobManager; @Inject Rx mRx; public void ingest(MainComponent component) { component.inject(this); } @Override protected void onFirstViewAttach() { super.onFirstViewAttach(); initSubjects(); } public void hideAlertDialog() { getViewState().hideAlertDialog(); } public void hideDateDialog() { getViewState().hideDateDialog(); } public void hideTimeDialog() { getViewState().hideTimeDialog(); } public void setStartDate(Date startDate) { if (startDate != null) { if (mEndDate != null) { if (startDate.getTime() < mEndDate.getTime()) { mStartDate = startDate; } else { getViewState().showAlertDialog(R.string.activity_main_start_date_error); } } else { mStartDate = startDate; } getViewState().setStartDate(mStartDate); } } public void setEndDate(Date endDate) { if (endDate != null) { if (mStartDate != null) { if (endDate.getTime() > mStartDate.getTime()) { mEndDate = endDate; } else { getViewState().showAlertDialog(R.string.activity_main_end_date_error); } } else { mEndDate = endDate; } getViewState().setEndDate(mEndDate); } } public void showStartDateDialog() { Calendar calendar = Calendar.getInstance(); if (mStartDate != null) { calendar.setTime(mStartDate); } getViewState().showStartDateDialog(calendar.getTime()); } public void showStartTimeDialog(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); getViewState().showStartTimeDialog(calendar.getTime()); } public void showEndTimeDialog(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); getViewState().showEndTimeDialog(calendar.getTime()); } public void showEndDialog() { Calendar calendar = Calendar.getInstance(); if (mEndDate != null) { calendar.setTime(mEndDate); } getViewState().showEndDateDialog(calendar.getTime()); } public void loadStatistics(Interval interval) { if (mStartDate == null) { getViewState().emptyStartDate(); return; } if (mEndDate == null) { getViewState().emptyEndDate(); return; } getViewState().showLoading(true); GetStatisticsMethodRequest request = new GetStatisticsMethodRequest(); request.setStartDate(mStartDate); request.setEndDate(mEndDate); request.setInterval(interval); final Observable<GetStatisticsMethodResponse> observable = mApiService.getStatisticsMethod(request); Disposable disposable = observable .compose(mRx.applySchedulers()) .subscribe(response -> { getViewState().showLoading(false); if (response != null && response.getStatus() != null && response.getStatus().isOk() && response.getResult().getPoints() != null) { List<Point> points = response.getResult().getPoints(); if (points.size() > 0) { getViewState().showPoints(points); calculateMinMax(points); calculateAverage(points); calculateMedian(points); calculateInterquartileRange(points); } else { getViewState().showAlertDialog(R.string.could_not_retrieve_data); } } else { getViewState().showAlertDialog(R.string.server_internal_error); } }, error -> { getViewState().showLoading(false); getViewState().showAlertDialog(R.string.server_not_responding); }); unSubscribeOnDestroy(disposable); } private void calculateMinMax(List<Point> points) { getViewState().showCalculatingMinMaxValue(true); mJobManager.addJob(new CalculateMinMaxJob(points, mMinMaxSubject)); } private void calculateAverage(List<Point> points) { getViewState().showCalculatingAverageValue(true); mJobManager.addJob(new CalculateAverageJob(points, mAverageSubject)); } private void calculateMedian(List<Point> points) { getViewState().showCalculatingMedianValue(true); mJobManager.addJob(new CalculateMedianJob(points, mMedianSubject)); } private void calculateInterquartileRange(List<Point> points) { getViewState().showCalculatingInterquartileRangeValue(true); mJobManager.addJob(new CalculateInterquartileRangeJob(points, mInterquartileRangeSubject)); } private void initSubjects() { Disposable minMaxDisposable = mMinMaxSubject .compose(mRx.applySchedulers()) .subscribe(minMax -> { getViewState().showCalculatingMinMaxValue(false); getViewState().showMinMaxValue(minMax.getMin(), minMax.getMax()); }); unSubscribeOnDestroy(minMaxDisposable); Disposable averageDisposable = mAverageSubject.compose(mRx.applySchedulers()) .subscribe(average -> { getViewState().showCalculatingAverageValue(false); getViewState().showAverageValue(average); }); unSubscribeOnDestroy(averageDisposable); Disposable medianDisposable = mMedianSubject.compose(mRx.applySchedulers()) .subscribe(median -> { getViewState().showCalculatingMedianValue(false); getViewState().showMedianValue(median); }); unSubscribeOnDestroy(medianDisposable); Disposable interquartileRangeDisposable = mInterquartileRangeSubject.compose(mRx.applySchedulers()) .subscribe(interquartileRange -> { getViewState().showCalculatingInterquartileRangeValue(false); getViewState().showInterquartileRangeValue(interquartileRange); }); unSubscribeOnDestroy(interquartileRangeDisposable); } }
Markdown
UTF-8
6,209
2.859375
3
[]
no_license
# Sweater Weather [In Express] #### [Refactor in progress] ###### Check me out here https://polar-island-07844.herokuapp.com/ This is an API built with the Express Framework! A user will be able to pass an API key to retreive weather details from a desired city, using the Darksky API using the Google Geocoding Api. Users have the ability to store their favorite locations, retrieve a list of those locations and forecast data for all of those favorites in one request! Details on installation and endpoints are below. ## Endpoints ### GET /api/v1/forecast?location=denver,co #### Example Response ``` { "location": "Denver, C0", "currently": { "summary": "Overcast", "icon": "cloudy", "precipIntensity": 0, "precipProbability": 0, "temperature": 54.91, "humidity": 0.65, "pressure": 1020.51, "windSpeed": 11.91, "windGust": 23.39, "windBearing": 294, "cloudCover": 1, "visibility": 9.12, }, "hourly": { "summary": "Partly cloudy throughout the day and breezy this evening.", "icon": "wind", "data": [ { "time": 1555016400, "summary": "Overcast", "icon": "cloudy", "precipIntensity": 0, "precipProbability": 0, "temperature": 54.9, "humidity": 0.65, "pressure": 1020.8, "windSpeed": 11.3, "windGust": 22.64, "windBearing": 293, "cloudCover": 1, "visibility": 9.02, }, ] }, "daily": { "summary": "No precipitation throughout the week, with high temperatures bottoming out at 58°F on Monday.", "icon": "clear-day", "data": [ { "time": 1554966000, "summary": "Partly cloudy throughout the day and breezy in the evening.", "icon": "wind", "sunriseTime": 1554990063, "sunsetTime": 1555036947, "precipIntensity": 0.0001, "precipIntensityMax": 0.0011, "precipIntensityMaxTime": 1555045200, "precipProbability": 0.11, "precipType": "rain", "temperatureHigh": 57.07, "temperatureLow": 51.47, "humidity": 0.66, "pressure": 1020.5, "windSpeed": 10.94, "windGust": 33.93, "cloudCover": 0.38, "visibility": 9.51, "temperatureMin": 53.49, "temperatureMax": 58.44, }, ] } } ``` ### POST /api/v1/favorites #### Example Response `status: 200 body: { "message": "Denver, CO has been added to your favorites", } ` ### GET /api/v1/favorites #### Example Response ``` status: 200 body: [ { "location": "Denver, CO", "current_weather": { "summary": "Overcast", "icon": "cloudy", "precipIntensity": 0, "precipProbability": 0, "temperature": 54.91, "humidity": 0.65, "pressure": 1020.51, "windSpeed": 11.91, "windGust": 23.39, "windBearing": 294, "cloudCover": 1, "visibility": 9.12, }, "location": "Golden, CO", "current_weather": { "summary": "Sunny", "icon": "sunny", "precipIntensity": 0, "precipProbability": 0, "temperature": 71.00, "humidity": 0.50, "pressure": 1015.10, "windSpeed": 10.16, "windGust": 13.40, "windBearing": 200, "cloudCover": 0, "visibility": 8.11, } } ] ``` ### DELETE /api/v1/favorites #### Example Response ` status: 204 ` #### Installing necessary dependencies The easiest way to get started is to run the following command. This will pull down any necessary dependencies that your app will require. You can think of this command as something incredibly similar to `bundle install` in Rails. `npm install` #### Set up your local database You’ll need to figure out a name for your database. We suggest calling it something like `sweater_weather_dev`. To get things set up, you’ll need to access your Postgres instance by typing in `psql` into your terminal. Once there, you can create your database by running the comment `CREATE DATABASE PUT_DATABASE_NAME_HERE_dev;`. Now you have a database for your new project. #### Migrations Once you have your database setup, you’ll need to run some migrations (if you have any). You can do this by running the following command: `knex migrate:latest` Instructions to create database, run migrations, and seed: ``` psql CREATE DATABASE DATABASE_NAME_dev; \q knex migrate:latest knex seed:run ``` #### Set up your test database Most of the setup is going to be same as the one you did before. You’ll notice one small difference with setting the environment flag to `test`. ``` psql CREATE DATABASE DATABASE_NAME_test; \q knex migrate:latest --env test ``` ## Running your tests Running tests are simple and require you to run the following command below: `npm test` When the tests have completed, you’ll get a read out of how things panned out. The tests will be a bit more noisy than what you’re used to, so be prepared. ## Setting up your production environment This repo comes with a lot of things prepared for you. This includes production ready configuration. To get started, you’ll need to do a few things. - Start a brand new app on the Heroku dashboard - Add a Postgres instance to your new Heroku app - Find the URL of that same Postgres instance and copy it. It should look like a long url. It may look something like like `postgres://sdflkjsdflksdf:9d3367042c8739f3...`. - Update your `knexfile.js` file to use your Heroku database instance. You’ll see a key of `connection` with a value of an empty string. This is where you’ll paste your new Postgres instance URL. Once you’ve set all of that up, you’ll need to `add the remote` to your new app. This should work no differently than how you’ve done it with any Rails project. Adding this remote will allow you to run `git push heroku master`. Once you’ve done that, you’ll need to `bash` into your Heroku instance and get some things set up. - Run the following commands to get started: ``` heroku run bash npm install nom install -g knex knex migrate:latest ``` This will install any dependencies, install Knex, and migrate any changes that you’ve made to the database.
TypeScript
UTF-8
2,613
2.8125
3
[]
no_license
import { RequestHandler } from 'express'; import { Training, validateTraining } from '../models/training'; import { notFoundTrainingResponse } from '../utils/trainings'; import { badRequest } from '../utils/common'; const TRAININGS: Training[] = []; export const createTraining: RequestHandler = (req, res, next) => { const { distanceInKM, date, workoutType, comment } = req.body as Partial<Training>; // Validate an incoming request data for training const { error } = validateTraining({ distanceInKM, date, workoutType, comment }); if (error) { return badRequest(res, error.details[0].message); } // Create a new training const newTraining = new Training(Date.now(), distanceInKM!, date!, workoutType!, comment); // Add created training to the DB emulator TRAININGS.push(newTraining); res.send(newTraining); }; export const getTrainings: RequestHandler = (req, res, next) => { res.send(TRAININGS); }; export const getTraining: RequestHandler<{ id: number | string }> = (req, res, next) => { const trainingId = Number(req.params.id); const training = TRAININGS.find(training => training.id === trainingId); // Response for not existing training if (!training) { return notFoundTrainingResponse(res); } res.send(training); }; export const updateTraining: RequestHandler<{ id: number | string }> = (req, res, next) => { const trainingId = Number(req.params.id); const { distanceInKM, date, workoutType, comment } = req.body as Partial<Training>; const training = TRAININGS.find(training => training.id === trainingId); // Response for not existing training if (!training) { return notFoundTrainingResponse(res); } // Validate new data for a training const { error } = validateTraining({ distanceInKM, date, workoutType, comment }); if (error) { return badRequest(res, error.details[0].message); } // Update training data training.distanceInKM = distanceInKM!; training.date = date!; training.workoutType = workoutType!; training.comment = comment; res.send(training); }; export const deleteTraining: RequestHandler<{ id: number | string }> = (req, res, next) => { const trainingId = Number(req.params.id); const trainingIndex = TRAININGS.findIndex(training => training.id === trainingId); // Response for not existing training if (trainingIndex === -1) { return notFoundTrainingResponse(res); } // Delete a specified training TRAININGS.splice(trainingIndex, 1); res.send({id: trainingId}); };
Shell
UTF-8
2,748
3.265625
3
[]
no_license
#!/bin/bash -l #### grep read sequences from fastq lanes, compare them between mates, then truncate both accordingly, so they match. #### checking specifically, og176_2, og179_2, and og275_2 ######## #SBATCH -D /home/sbhadral/Projects/Rice_project/fixed_fastqs #SBATCH -J fastq_check #SBATCH -p serial #SBATCH -o /home/sbhadral/Projects/Rice_project/outs/og176_grep_trunc_%A_%a.out #SBATCH -e /home/sbhadral/Projects/Rice_project/errors/og176_grep_trunc_%A_%a.err #SBATCH -c 8 ##SBATCH --mail-type=FAIL ##SBATCH --mail-type=END ##SBATCH --mail-user=sbhadralobo@ucdavis.edu ##SBATCH --array=1-4 #SBATCH --array=2 set -e set -u ### Missing read runs. # 15998464 EJF-001B_index2_CGATGT_L001_R2_003.fastq og275 # 15999487 EJF_002C_GCCAAT_L007_R2_002.fastq og176 # 15998456 EJF_003B_ACTTGA_L008_R2_005.fastq og179 # 15997944 EJF_003B_ACTTGA_L008_R2_004.fastq og179 FILE=$( sed -n "$SLURM_ARRAY_TASK_ID"p grep_trunc_list.txt ) # list like above, but of R1 lanes. for file in "$FILE"; do short=$( echo "$file" | sed -e 's/EJF//g' | sed -e 's/_L//g' | sed -e 's/.fastq//g' | sed -e 's/_//g' | sed -e 's/00//g' | sed -e 's/-//g' | sed -e 's/index2//g' ) mate2=$( echo "$file" | sed -e 's/R1/R2/g' ) # replace R1 with R2 to specify mate2. echo "$file" echo "$mate2" echo "$short" grep -n "^@HS" "$file" > headers."$short"_1; # grep every header and it's line number as lines = {1, 5, 9, ... 4n+1}, save to file. grep -n "^@HS" "$mate2" > headers."$short"_2; # same as above, but for mate2 echo grep1 finished cut -s -d ':' -f 1 headers."$short"_1 > nums."$short"_1 # cut out line numbers, delimited by colon. (part of grep -n output e.g 2:<for line 2> ) cut -s -d ':' -f 1 headers."$short"_2 > nums."$short"_2 echo cut1 finished; diff --suppress-common-lines nums."$short"_1 nums."$short"_2 | # output only line numbers that differ cut -s -d '<' -f 2 - > new.delete."$short"; echo delete lines are ready. # #cp "$file" temp_delete_lines/ # delete_list=$( less delete."$short" ) # # array=( "$delete_list" ) # # cd temp_delete_lines/ # # #for nums in "$delete_list"; # for nums in "${array[@]}"; # # do # # #sed '/"${array[@]}"/,+3d' "$file" > new."$file"; # # #sed 's/.*/&+3d/' delete."$short" | sed -i -f - "$file"; # # sed '/"${nums}"/,+3d' "$file" > new."$file"; # # done; done; ## Next delete those lines in the mate 2 runs? Can't be sure if the missing header also means the following 3 lines of ( seq\n +\n seq\n ) are also missing? ## Fastq lines # @HS1:192:d143cacxx:8:2304:14253:160681 2:N:0:GATCAG # CTAGCAGTAACTGGTAAGTATGATGTGAAAAGAAAGCTCAATGACTGGACAATTTGTTCCGTTATGCTTATTCCTTGCCATTTTATTTAAAGTTTTCCCA # + # CCCFFFFFHHHHHJGHIJIJIJJJJHHJJJJIJJJJJJJIJJJJJIJJIJIIJJJJIJJJJHJJJJJJJJIIJJIJJJHHHHHHGFFFFFFFCEEEEEC>
PHP
UTF-8
680
2.671875
3
[]
no_license
<?php namespace PawsPlus\Doorknob; class Autoloader { private static $namespace = __NAMESPACE__; public static function register() { spl_autoload_register( array( __CLASS__, 'autoload' ) ); } public static function autoload( $class ) { $class = ltrim( $class, '\\' ); if ( 0 !== strpos( $class, self::$namespace ) ) return; $class = str_replace( self::$namespace, '', $class ); $class = preg_replace( '/([a-zA-Z])(?=[A-Z])/', '$1_', $class ); $file = dirname( __FILE__ ) . strtolower( str_replace( '\\', DIRECTORY_SEPARATOR, $class ) ) . '.php'; if ( is_file( $file ) ) { require_once( $file ); return $file; } else { return false; } } }
Markdown
UTF-8
1,638
2.828125
3
[]
no_license
--- title: 'Quick Tip: Remove Paypal logo from Catalog pages in Magento' author: Ash Smith layout: post share: true permalink: /2011/07/quick-tip-remove-paypal-logo-from-catalog-pages-in-magento/ categories: - magento1 --- When setting your store up one of the first things you&#8217;ll come across is on the catalog pages of your store you&#8217;ll see down the right hand side in the 2columns-right.phtml file is the paypal logo saying you accept paypal. If you are new to Magento this can prove to be rather difficult. Anyway, there are two options to getting rid of the Paypal logo. ## Option One: Disable Paypal So, if you have no intention of using paypal as a payment method you can disable paypal from your store completely, this is simple to do go to: system > confiuration > advanced > advanced  then from the list of modules disable both paypal and paypaluk. Refresh your cache and the logo has gone from your right hand sidebar. ## Option Two: Remove the logo yourself To remove the logo from the right hand sidebar all you need to do is go into your file system and navigate to: app/design/frontend/base/default/layout/ and open up paypal.xml. copy this file to your theme&#8217;s layout directory (app/design/frontend/package/yourtheme/layout/) once you&#8217;ve done this open up paypal.xml and remove the following lines from the file: 98-100, 106 112, 118. Once you&#8217;ve completed this simply refresh your cache and you&#8217;re done! Thanks for reading this quick tip on removing the paypal logo from catalog page inside of your Magento store. For more quick tips stay tuned and subscribe to our RSS feed.
Python
UTF-8
1,722
3.046875
3
[]
no_license
class Human(object): # def __init__(self,h=0,w=0): # self.height=h # self.weight=w # def BMI(self): # return self.weight / ((self.height/100)**2) # def __add__(self,other): # return self.height + other.height # def __iadd__(self,other): # self.height += other.height # self.weight += other.weight # return self def __init__(self,h=0,w=0): self._height=h self._weight=w def _BMI(self): return self._weight / ((self._height/100)**2) class Bird: def __init__(self): print("init") #先執行new 再執行init def fly(self): print("fly") def __new__(self): print("new") return object.__new__(self) #如果沒有return,這個物件並沒有建立成功 b=Bird() b.fly() class FirstClass: """My first class in python.""" str1 = "Apple" str2 = "IBM" def __init__(self, str1="參數1", str2="參數2"): self.str1 = str1 self.str2 = str2 def fun(self): return "Hello world." my_obj = FirstClass() print(my_obj.str1) print(my_obj.str2) print("===分隔線===") my_obj2 = FirstClass("我是參數1") print(my_obj2.str1) print(my_obj2.str2) print("===分隔線===") my_obj3 = FirstClass("我是參數1", "我是參數2") print(my_obj3.str1) print(my_obj3.str2) class ManagementUtility: """ Encapsulate the logic of the django-admin and manage.py utilities. """ def __init__(self, argv=None): self.argv = argv or sys.argv[:] self.prog_name = os.path.basename(self.argv[0]) if self.prog_name == '__main__.py': self.prog_name = 'python -m django' self.settings_exception = None
Markdown
UTF-8
1,911
3.578125
4
[ "MIT" ]
permissive
Linear Regression: Check Your Understanding =========================================== Before going on to the lab, here are some additional practice questions that you can use to check your understanding of linear regression. ### Question 1 of 4 Which of the following statements about linear regression are **incorrect**? (Select all that apply.) - [x] A general equation like y = mx + b is a model - [x] Simple linear regression uses a _plane_ to describe relationships between variables - [ ] Multiple linear regression involves more than one input variable - [ ] Linear regression assumes that the input variables and output variable follow a linear relationship > A general equation like y = mx + b is not a model. To train a model, we need to learn the specific values for m and b. Submit ### Question 2 of 4 One of the things that can be difficult when looking at a machine learning algorithm is that different terms and symbols are often used to refer to the same (or very closely related) things. With that in mind, can you match the following terms? coefficient: slope bias: intercept cost function: RMSE ### Question 3 of 4 Which of the following about training a linear regression model is correct? (Select all that apply.) - [x] The training process is a process of _minimizing the error_ - [x] A _cost function_ is used to calculate the error of a model - [ ] A linear regression model will not change much if outliers are removed - [ ] It is not necessary to remove highly correlated input variables when training a model - [x] It is always a good idea to rescale data ### Question 4 of 4 Which one of the following is not necessary when preparing data for a linear regression model? - [ ] Remove noise - [ ] Make sure the input variable(s) and output variable follow a linear relationship - [ ] Remove collinearity - [x] Make sure the error is minimized.
C
UTF-8
374
3.5
4
[]
no_license
#include<stdio.h> int main() { int numero, temp, dig1, dig2, dig3; printf("Numero de 3 digitos: "); scanf("%d",&numero); temp = numero; dig1 = temp % 10; temp = temp / 10; dig2 = temp % 10; temp = temp / 10; dig3 = temp % 10; printf("%d = %d x 1 + %d x 10 + %d x 100.\n",numero,dig1,dig2,dig3); return 0; }
Markdown
UTF-8
643
2.8125
3
[]
no_license
# useMemo 1. useMemo invokes a function to calculate a memoized value. In computer science in general, memoization is a technique that’s used to improve performance. In a memoized function, the result of a function call is saved and cached. Then, when the function is called again with the same inputs, the cached value is returned. In React, useMemo allows us to compare the cached value against itself to see if it has actually changed. 2. The way useMemo works is that we pass it a function that’s used to calculate and create a memoized value. useMemo will only recalculate that value when one of the dependencies has changed.
C++
UTF-8
962
3.21875
3
[]
no_license
#include "SimpleFileFactory.h" #include "SimpleFileSystem.h" // studio 18 - simple file factory definitions AbstractFile* SimpleFileFactory::createFile(string fileName) { bool isSuffix = false;//bool detrmining if the file that is to be created has a suffix (ex: .txt) string suffix = "";//string that stores the suffix for (char c : fileName) {//iterate thru the file name if (c == '.') {//find the . isSuffix = true;//if it has a . then it has a suffix } else if (isSuffix) {//if it has a suffix start storing the extensino suffix += c; } } if (suffix == "txt") {//if its a text file create a new textfile and return its pointer TextFile* tf = new TextFile(fileName); return tf; } if (suffix == "img") {//if its a img file create a new imagefile and return its pointer ImageFile* imgf = new ImageFile(fileName); return imgf; } return nullptr;//if its not a txt or img file return nullptr }
C++
UTF-8
621
2.515625
3
[]
no_license
class Solution { public: vector<int> executeInstructions(int n, vector<int>& startPos, string s) { int m = s.size(); vector<int> ret(m); for(auto i = 0; i < m; ++i) { int y = startPos[0], x = startPos[1]; for(auto j = i; j < m; ++j) { if(s[j] == 'R') ++x; else if(s[j] == 'L') --x; else if(s[j] == 'U') --y; else ++y; if(y < 0 || y >= n || x < 0 || x >= n) break; ++ret[i]; } } return ret; } };
Java
UTF-8
523
1.773438
2
[]
no_license
package crawler.documents; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import java.util.Date; @Document @Data public class InstagramFeed { @Id private String id; private String code; private int commentCount; private int likeCount; private int viewCount; private String content; private String thumbnailUrl; private String instagramUserId; private Date takenAt; private Date createdDate; }
C#
UTF-8
2,914
3.203125
3
[]
no_license
using System; using System.Timers; namespace YoutubeExplodeConsole { class Progress : IProgress<double>, IDisposable { private readonly string title; private readonly string filePath; private double percent; private readonly long size; private double bytesCount; private bool first; private readonly Timer timer; private int messageLength; public delegate void MessageHandler(string message); public event MessageHandler Message; public Progress(string title, string filePath, long size) { percent = 0; bytesCount = 0; messageLength = 0; first = true; this.title = title; this.filePath = filePath; this.size = size; timer = new Timer(1000); timer.Elapsed += Timer_Elapsed; timer.Start(); } private void Timer_Elapsed(object sender, ElapsedEventArgs e) { if (!first) { double bytesCount = percent * size; double speed = bytesCount - this.bytesCount; this.bytesCount = bytesCount; string message = string.Format("\rПрогресс загрузки: {0:P2}. Скорость: {1}.", percent, SpeedToString(speed)); SendMessage(message); messageLength = message.Length; } } private void SendMessage(string message) { if (messageLength == 0 || messageLength <= message.Length) { Message(message); } else { Message(string.Format("{0, -" + messageLength + "}", message)); } } public void Dispose() { timer.Stop(); string message = string.Format("\rВидео загружено в {0}.\n", filePath); SendMessage(message); messageLength = 0; } public void Report(double value) { if (first) { Message(string.Format("Загрузка видео {0}.\n", title)); first = false; } percent = value; } private string SpeedToString(double speed) { string si; if (speed >= 1073741824) { speed /= 1073741824; si = "ГБ"; } else if (speed >= 1048576) { speed /= 1048576; si = "МБ"; } else if (speed >= 1024) { speed /= 1024; si = "КБ"; } else { si = "Б"; } return string.Format("{0:f1} {1}/c", speed, si); } } }
Java
UTF-8
624
2
2
[]
no_license
package com.spring.transformer.service.impl; import org.springframework.stereotype.Service; import com.spring.transformer.dto.InternalUserSearchDTO; import com.spring.transformer.service.CustomUserService; @Service("internalCustomUserService") public class InternalCustomUserServiceImpl implements CustomUserService<InternalUserSearchDTO> { @Override public InternalUserSearchDTO searchUser(Long userId) { InternalUserSearchDTO internalUserSearchDTO = new InternalUserSearchDTO(2L, "Internal User", "Password", true, 0, "Admin"); return internalUserSearchDTO; } }
TypeScript
UTF-8
8,123
2.671875
3
[]
no_license
import { Clock } from '../clock.js'; import { DeepReadonlyObject } from '../deep_readonly.js'; import { integrateWithConstantAcceleration } from '../math.js'; import { Battery, PoweredSystem, PowerSource, Ship, System } from '../model/ship.js'; import { ShipComputer } from '../ship_computer.js'; import { SnapshotManager } from '../snapshot_manager.js'; import { Ships } from './ships.js'; const EPSILON = 0.016667; // Approximately one frame. const POWER_TOLERANCE = 0.00001; interface DistributedEnergy { availableEnergyFromReactor: number; availableEnergyFromBattery: number; suppliedEnergyBySystem: Map<PoweredSystem, number>; totalEnergyDrawnFromReactor: number; totalEnergyDrawnFromBattery: number; } export class PowerDistribution { public static lastCharge: number = 0; public static lastStep: number = 0; public static update( ship: DeepReadonlyObject<Ship>, clock: Readonly<Clock>, snapshots: SnapshotManager, computer: ShipComputer): void { if (!ship.systems.reactor.enabled) { return; } // TODO: Move this to reactors.ts? const powerOutput = ship.systems.reactor.powerOutput; const powerOutputDelta = ship.systems.reactor.powerOutputDelta; if (powerOutput <= 0 && powerOutputDelta < 0) { const newShip = Ships.clone(ship); newShip.systems.reactor.powerOutput = 0; newShip.systems.reactor.powerOutputDelta = 0; snapshots.addSnapshotForShip(newShip, clock); } if (powerOutput >= ship.systems.reactor.maxPowerOutput && powerOutputDelta > 0) { const newShip = Ships.clone(ship); newShip.systems.reactor.powerOutput = ship.systems.reactor.maxPowerOutput; newShip.systems.reactor.powerOutputDelta = 0; snapshots.addSnapshotForShip(newShip, clock); } // TODO: move this to batteries.ts? const powerInput = ship.systems.battery.powerInput; if (powerInput >= ship.systems.battery.maxPowerInput + POWER_TOLERANCE) { const newShip = Ships.clone(ship); newShip.systems.battery.powerInput = ship.systems.battery.maxPowerInput; snapshots.addSnapshotForShip(newShip, clock); } } public static simulate(oldShip: DeepReadonlyObject<Ship>, ship: Ship, step: number): void { const oldDistributedEnergy = this.getDistributedEnergy(oldShip, ship, step - EPSILON); const newDistributedEnergy = this.getDistributedEnergy(oldShip, ship, step); for (const system of newDistributedEnergy.suppliedEnergyBySystem.keys()) { const oldEnergy = oldDistributedEnergy.suppliedEnergyBySystem.get(system) || 0; const newEnergy = newDistributedEnergy.suppliedEnergyBySystem.get(system) || 0; system.powerInput = (newEnergy - oldEnergy) / EPSILON; } // Deduct any energy we took from the battery from its charge. const oldCharge = this.calculateBatteryCharge(oldDistributedEnergy, oldShip, step - EPSILON); const newCharge = this.calculateBatteryCharge(newDistributedEnergy, oldShip, step); ship.systems.battery.charge = newCharge; ship.systems.battery.powerInput = (newCharge - oldCharge) / EPSILON; } private static calculateBatteryCharge( distributedEnergy: DistributedEnergy, ship: DeepReadonlyObject<Ship>, step: number): number { if (distributedEnergy.totalEnergyDrawnFromBattery > 0) { return ship.systems.battery.charge - distributedEnergy.totalEnergyDrawnFromBattery; } else if (distributedEnergy.totalEnergyDrawnFromReactor < distributedEnergy.availableEnergyFromReactor) { // If we have not used up all the reactor energy, we need to divert as much of what's left // over as we can to the battery. // Calculate the maximum amount of energy that can be diverted to the battery during the time // step. This is the amount we are allowed to use to charge the battery; anything more than // this will have to be dissipated as heat. const maxEnergyToBattery = Math.min(ship.systems.battery.capacity - ship.systems.battery.charge, ship.systems.battery.maxPowerInput * step); const desiredEnergyToBattery = distributedEnergy.availableEnergyFromReactor - distributedEnergy.totalEnergyDrawnFromReactor; if (desiredEnergyToBattery < maxEnergyToBattery) { return ship.systems.battery.charge + desiredEnergyToBattery; } else { return ship.systems.battery.charge + maxEnergyToBattery; // TODO: dissipate desiredEnergyToBattery - maxEnergyToBattery into the hull as heat. } } else { return ship.systems.battery.charge; } } private static getDistributedEnergy( ship: DeepReadonlyObject<Ship>, newShip: Ship, step: number): DistributedEnergy { const powerSources: Array<DeepReadonlyObject<PowerSource>> = []; const poweredSystems: PoweredSystem[] = []; for (const value of Object.values(ship.systems)) { const system = value as DeepReadonlyObject<System>; if (this.isPowerSource(system, ship.systems.battery)) { powerSources.push(system); } } // Need to use the new ship here so the systems will be identity-equal to the ones we intend to // update later on. for (const value of Object.values(newShip.systems)) { const system = value as System; if (this.isPoweredSystem(system, ship.systems.battery)) { poweredSystems.push(system); } } poweredSystems.sort((a, b) => a.powerPriority - b.powerPriority); const result: DistributedEnergy = { availableEnergyFromReactor: 0, availableEnergyFromBattery: 0, suppliedEnergyBySystem: new Map(), totalEnergyDrawnFromReactor: 0, totalEnergyDrawnFromBattery: 0, }; // Calculate the total amount of energy that has been generated by all power sources since the // last snapshot. result.availableEnergyFromReactor = powerSources.reduce<number>( (accum, source) => accum + integrateWithConstantAcceleration( 0, source.powerOutput, source.powerOutputDelta, step), 0); // Calculate the maximum amount of energy that can be drawn from the battery during the time // step. This is the amount we have available to draw from if the reactor isn't enough. result.availableEnergyFromBattery = Math.min( ship.systems.battery.charge, ship.systems.battery.maxPowerOutput * step); for (const system of poweredSystems) { const requestedEnergy = system.requestedPowerInput * step; let providedEnergyFromReactor = 0; let providedEnergyFromBattery = 0; if (requestedEnergy < result.availableEnergyFromReactor - result.totalEnergyDrawnFromReactor) { // All the energy will come from the reactor. providedEnergyFromReactor = requestedEnergy; } else { // Take all the remaining energy from the reactor, and make up the rest from the battery. providedEnergyFromReactor = result.availableEnergyFromReactor - result.totalEnergyDrawnFromReactor; // The amount from the battery is either all the remaining energy we need, or all the energy // we have left in the battery, whichever is less. providedEnergyFromBattery = Math.min( requestedEnergy - providedEnergyFromReactor, result.availableEnergyFromBattery - result.totalEnergyDrawnFromBattery); } result.suppliedEnergyBySystem.set( system, providedEnergyFromReactor + providedEnergyFromBattery); // Deduct the energy we've taken from the reactor and battery pools, since it is no longer // available to the next system. result.totalEnergyDrawnFromReactor += providedEnergyFromReactor; result.totalEnergyDrawnFromBattery += providedEnergyFromBattery; } return result; } private static isPowerSource(system: System, battery: Battery): system is PowerSource { return (system as PowerSource).powerOutput !== undefined && system !== battery; } private static isPoweredSystem(system: System, battery: Battery): system is PoweredSystem { return (system as PoweredSystem).requestedPowerInput !== undefined && system !== battery; } }
Python
UTF-8
1,148
2.796875
3
[]
no_license
import re import cv2 import os #import crop function to this file #from cropfunction.py import crop def crop(path_img, path_save, path_detection): # parse txt file myfile=open(path_detection,'r') lines=myfile.readlines() pattern= "Cat" for line in lines: if re.search(pattern,line): Cord_Raw=line Cord=Cord_Raw.split("(")[1].split(")")[0].split(" ") # calculate coordinates x_min=int(Cord[1]) x_max=x_min + int(Cord[5]) y_min=int(Cord[3]) y_max=y_min+ int(Cord[7]) #crop image img = cv2.imread(path_img) cv2.imshow('whatever the hell i want', img) cv2.waitKey(0) cv2.destroyAllWindows() # crop_img = img[y_min:y_max, x_min:x_max] # img_name = 'whatever the hell I want.jpg' # os.chdir(path_save) # cv2.imwrite(img_name, crop_img) #define variables to feed to function pimg = r'C:\Users\shore\GitHub\RutYOLO\RutYOLO\image\cat' psave = r'C:\Users\shore\GitHub\RutYOLO\RutYOLO\crop' presult = r'C:\Users\shore\GitHub\RutYOLO\RutYOLO\result.txt' crop(pimg,psave,presult)