language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 1,887 | 3.046875 | 3 |
[] |
no_license
|
package be.mdelbar.geneticcells;
import be.mdelbar.geneticcells.ability.Ability;
import be.mdelbar.geneticcells.ability.AbilityPoints;
import be.mdelbar.geneticcells.config.ConfigFactory;
import java.awt.Color;
/**
*
* @author Matthias Delbar
*/
public class Cell {
private static final int BASE_RESISTANCE_COLD = ConfigFactory.getInstance().getCellBaseResistanceCold();
private static final int BASE_ENERGY_PRODUCTION = ConfigFactory.getInstance().getCellBaseEnergyProduction();
private static final int BASE_ENERGY_CONSUMPTION = ConfigFactory.getInstance().getCellBaseEnergyConsumption();
private AbilityPoints ap;
// Empty constructor
public Cell() {
this.ap = new AbilityPoints();
}
// Copy constructor
public Cell(Cell old) {
this.ap = new AbilityPoints(old.ap);
}
public Color toColor() {
return new Color(calculateResistanceCold(), calculateEnergyProduction(), calculateEnergyConsumption());
}
// Percentage scale, +10% resistance for every AP added
public int calculateResistanceCold() {
return BASE_RESISTANCE_COLD + 10*ap.getAP(Ability.RESISTANCE_COLD);
}
// Flat bonus to production
public int calculateEnergyProduction() {
return BASE_ENERGY_PRODUCTION + ap.getAP(Ability.ENERGY_PRODUCTION);
}
// Possible for a cell to have more than the "useful amount" of AP in energy consumption, but consumption is always at least 1
public int calculateEnergyConsumption() {
return Math.max(1, BASE_ENERGY_CONSUMPTION - ap.getAP(Ability.ENERGY_CONSUMPTION));
}
public AbilityPoints getAp() {
return ap;
}
@Override
public String toString() {
return String.format("(%d, %d, %d)", calculateEnergyProduction(), calculateEnergyConsumption(), calculateResistanceCold());
}
}
|
C#
|
UTF-8
| 878 | 3.140625 | 3 |
[] |
no_license
|
using HanoiEntity;
using System.Collections.Generic;
using System.Linq;
using System;
namespace HanoiRepository
{
public class EntityRepository<T> : IEntityRepository<T> where T : BaseEntity
{
private static List<T> _repo = new List<T>();
public void Add(T entity)
{
entity.Id = _repo.Count + 1;
_repo.Add(entity);
}
public T Get(int id)
{
return _repo.Find(x => x.Id == id);
}
public void Delete(int id)
{
_repo.Remove(Get(id));
}
public int Count()
{
return _repo.Count + 1;
}
public IEnumerable<T> Get(Func<T, bool> filter)
{
return _repo.Where(filter);
}
public IEnumerable<T> GetAll()
{
return _repo.ToList();
}
}
}
|
Java
|
UTF-8
| 760 | 3.59375 | 4 |
[] |
no_license
|
/*
Receba os valores do comprimento, largura e altura de um paralelepípedo. Calcule e mostre seu volume.
*/
import javax.swing.JOptionPane;
public class Paralelepipedo
{
public static void main(String args[])
{
Double comp, larg, alt, paralelepipedo;
comp = Double.parseDouble(JOptionPane.showInputDialog("Digite o comprimento do paralelepípedo"));
larg = Double.parseDouble(JOptionPane.showInputDialog("Digite a largura do paralelepípedo"));
alt = Double.parseDouble(JOptionPane.showInputDialog("Digite a altura do paralelepípedo"));
paralelepipedo = comp * larg * alt;
JOptionPane.showMessageDialog(null, "O volume do paralelepipedo é de: " + paralelepipedo);
}
}
|
JavaScript
|
UTF-8
| 1,843 | 2.890625 | 3 |
[] |
no_license
|
/**
* It's possible to some extent but won't be really accurate, the idea is load image with a known file size then in its onload event measure how much time passed until that event was triggered, and divide this time in the image file size.
Important things to keep in mind:
1. The image being used should be properly optimized and compressed. If it isn't, then default compression on connections by the web server might show speed bigger than it actually is. Another option is using uncompressible file format, e.g. jpg. (thanks Rauli Rajande for pointing this out and Fluxine for reminding me).
2. The cache buster mechanism described above might not work with some CDN servers, which can be configured to ignore query string parameters, hence better setting cache control headers on the image itself.
*/
function measureConnectionSpeed(options){
var imageURL = options.imageURL || "http://www.kenrockwell.com/contax/images/g2/examples/31120037-5mb.jpg",
downloadSize = options.downloadSize || 4995374, //bytes
retry = options.retry || 3,
load = options.load || function(){};
function _measure(){
var download = new Image(),
startTime,
endTime,
duration,
bitsLoaded,
speedBps; //bit pro second
download.onload = function () {
endTime = (new Date()).getTime();
duration = (endTime - startTime) / 1000;
bitsLoaded = downloadSize * 8;
speedBps = (bitsLoaded / duration).toFixed(2);
load && load(speedBps);
retry = 0;
download.onload = null;
}
download.onerror = function (err, msg) {
if(--retry){
_measure();
}
download.onerror = null;
}
startTime = (new Date()).getTime();
download.src = imageURL + "?t=" + startTime;
}
_measure();
}
|
C#
|
UTF-8
| 2,237 | 2.609375 | 3 |
[] |
no_license
|
namespace GitHubTracker.Core
{
using System;
using GitHubTracker.Contracts;
using GitHubTracker.GitHubViews;
using GitHubTracker.Models;
public class Dispatcher : IDispatcher
{
private IIssueTracker tracker;
public Dispatcher()
: this(new Views())
{
}
internal Dispatcher(IIssueTracker tracker)
{
this.tracker = tracker;
}
public string DispatchAction(ICommand command)
{
switch (command.CommandName)
{
case "RegisterUser":
return this.tracker.RegisterUser(
command.Parameters["username"],
command.Parameters["password"],
command.Parameters["confirmPassword"]);
case "LoginUser":
return this.tracker.LoginUser(command.Parameters["username"], command.Parameters["password"]);
case "LogoutUser":
return this.tracker.LogoutUser();
case "CreateIssue":
return this.tracker.CreateIssue(
command.Parameters["title"],
command.Parameters["description"],
(IssuePriority)Enum.Parse(typeof(IssuePriority), command.Parameters["priority"], true),
command.Parameters["tags"].Split( new char[] { '/', '|' }, StringSplitOptions.RemoveEmptyEntries));
case "RemoveIssue":
return this.tracker.RemoveIssue(int.Parse(command.Parameters["id"]));
case "AddComment":
return this.tracker.AddComment(int.Parse(command.Parameters["id"]), command.Parameters["text"]);
case "MyIssues":
return this.tracker.GetMyIssues();
case "MyComments":
return this.tracker.GetMyComments();
case "Search":
return this.tracker.SearchForIssues(command.Parameters["tags"].Split('|'));
default:
return string.Format("Invalid action: {0}", command.CommandName);
}
}
}
}
|
Markdown
|
UTF-8
| 5,395 | 2.890625 | 3 |
[
"CC0-1.0"
] |
permissive
|
# Archivo .gitignore
En esta actividad empezaremos a trabajar con algo más real. Por ejemplo, una sencilla aplicación de Java. Esta actividad también es práctica.
Vamos a seguir utilizando el repositorio que estabamos usando en las actividades anteriores.
**`git log --oneline --all`**

## 1. Creamos una aplicación HolaMundo en Java con Gradle.
```
gradle init --type java-application
```

Vemos que nos ha creado un proyecto de gradle con varios archivos.
> NOTA: El archivo `README.md` no es creado por gradle. Ya existía previamente en la carpeta.
Para probar la ejecución hacemos:
```
gradle run
```

Si ahora volvemos a hacer un listado, veremos que nos ha creado una nueva carpeta llamada build con el bytecode resultante de la compilación.
```
ls -a
tree build
```

## 2. Añadiendo archivos al repositorio local
Como vimos en la actividad anterior, si ahora ejecutamos **git diff HEAD**, esperariamos ver los cambios de nuestro directorio de trabajo respecto al último commit.
Sin embargo esto no es lo que ocurre. NO SE MUESTRA NADA. ¿Por qué es esto?
Esto es porque git diff HEAD funciona siempre teniendo en cuenta los archivos que ya habían sido añadidos previamente al repositorio. Es decir sólo tiene en cuenta los archivos con seguimiento.
**Los archivos nuevos son archivos sin seguimiento**. En este caso debemos usar **git status** para ver esta circunstancia.

Ahora debemos añadir todos estos archivos al área de preparación (Staging Area) y luego realizar un commit.
PERO ESPERA UN MOMENTO. Voy a explicarte algo.
**Cuando se trabaja con proyectos de código fuente existen algunos archivos que no interesa añadir al repositorio, puesto que no aportan nada**. En el repositorio, como norma general, no debe haber archivos ejecutables, ni bytecode, ni código objeto, y muchas veces tampoco .zip, .rar, .jar, .war, etc. Estos archivos inflan el repositorio y, cuando llevamos muchos commits, hacen crecer demasiado el repositorio y además pueden ralentizar el trabajo de descarga y subida.
Para cada lenguaje y para cada entorno de desarrollo se recomienda no incluir ciertos tipos de archivos. Son los **archivos a ignorar**. Cada programador puede añadir o eliminar de la lista los que considere adecuados. Los archivos y carpetas a ignorar deben indicarse en el archivo **`.gitignore`**. En cada línea se pone un archivo, una carpeta o una expresión regular indicando varios tipos de archivos o carpetas.
En el repositorio https://github.com/github/gitignore tienes muchos ejemplos para distintos lenguajes, herramientas de construcción y entornos.
Para el lenguaje Java: https://github.com/github/gitignore/blob/master/Java.gitignore
Para la herramienta Gradle: https://github.com/github/gitignore/blob/master/Gradle.gitignore
Para el entorno Netbeans: https://github.com/github/gitignore/blob/master/Global/NetBeans.gitignore
Simplificando, nosotros vamos a ignorar las carpetas `build` y `.gradle`. Entonces, el archivo **`.gitignore`** debe tener el siguiente contenido:
```
build/
.gradle/
```
La barra final es opcional, pero a mí me gusta ponerla cuando me refiero a carpetas, para así saber cuando se trata de un archivo y cuando de una carpeta.
Crea el archivo .gitignore con dicho contenido y haz una captura de pantalla.
Ahora si hacemos
**`git status`**
veremos que no nos aparecen las carpetas `build` ni `.gradle`. Y nos aparece un archivo nuevo .gitignore.

Ahora ya podemos ejecutar
```
git add .
git commit -m "Código fuente inicial"
```
Fíjate que he escrito `git add .`. El punto indica el directorio actual, y es una forma de indicar que incluya en el área de preparación todos los archivos del directorio en el que me encuentro (salvo los archivos y carpetas indicados en `.gitignore`) Se utiliza bastante esta forma de git add cuando no queremos añadir los archivos uno a uno.
## 3. Subir cambios de repositorio local a repositorio remoto
Ya sólo nos queda subir los cambios realizados al repositorio remoto con **git push**

Para hacer algo más interesante este apartado, vamos a crear una etiqueta en el commit actual y subirla a github para que éste cree una nueva *release*.
```
git tag v3
git push --tags
```

Bueno, las etiquetas v1 y v2 no se suben porque ya la habíamos subido previamente.
En este caso, podríamos también haber ejecutado
**`git push origin v3`**
Y la historia de nuestro repositorio local nos quedaría así de bonita

Accede a tu repositorio en GitHub y haz una captura de pantalla de las *releases*.
Haz otra captura de los archivos y carpetas de código subidas a GitHub. No deberían aparecer ni la carpeta build ni la carpeta .gradle. Y sí debería aparecer el archivo .gitignore.
> NOTA: La carpeta `.git` nunca se muestra en GitHub.
> *NOTA: No borrar los repositorio local ni repositorio remoto. Los volveremos a utilizar en la siguiente actividad.*
**Subir a plataforma Moodle un documento PDF con las capturas de pantalla y explicaciones pertinentes.**
|
Markdown
|
UTF-8
| 16,137 | 3.265625 | 3 |
[
"MIT"
] |
permissive
|
- [Data Import and Transformation](#data-import-and-transformation)
- [Data wrangling](#data-wrangling)
- [Managing data in Azure](#managing-data-in-azure)
- [Datastore](#datastore)
- [Dataset](#dataset)
- [Data versioning](#data-versioning)
- [Working with features](#working-with-features)
- [Feature engineering](#feature-engineering)
- [Feature selection](#feature-selection)
- [Data drift](#data-drift)
- [Training model](#training-model)
- [Parameters vs. Hyperparameters](#parameters-vs-hyperparameters)
- [Splitting data](#splitting-data)
- [Training Classifiers](#training-classifiers)
- [Training Regressors](#training-regressors)
- [Evaluating performance](#evaluating-performance)
- [Evaluation mertics for classification](#evaluation-mertics-for-classification)
- [Confusion matrices](#confusion-matrices)
- [Evaluation metrics for regression](#evaluation-metrics-for-regression)
- [Training multiple models](#training-multiple-models)
- [ensemble training](#ensemble-training)
- [Automated training on Azure Ml](#automated-training-on-azure-ml)
- [Resources](#resources)
# Data Import and Transformation
Most algorythm are secitive to the quality of data they are learning from. That's why data transformation is a *crucial* step in getting a high quality model.
Problems in data: noise, wrong values (outliers), missing values.
## Data wrangling
Data wrangling is the process of *cleaning and transforming* data to make it more appropriate for data analysis. The main steps:
* Understand the data: explore the raw data and check the general quality of the dataset.
* Transform the raw data: restructuring, normalizing, cleaning. For example, this could involve handling *missing values* and *detecting errors*.
* Make the data available: Validate and publish the data.
## Managing data in Azure

The steps of the data access workflow:
1. Create a Datastore so that you can access storage services in Azure.
2. Create a Dataset, which you will subsequently use for model training in your machine learning experiment.
3. Create a dataset Monitor to detect *issues* in the data, such as data drift.
Data drift - the data which changes/evolves overtime which makes models trained on initial data less performant.
### Datastore
Datastore is a *layer of abstraction* over the supported Azure storage services.
* connection information is hidden which provides a layer of security
* answers to the question: "How do a I securely connect to my data in my Azure Storage?".
* compute location independence
* every ML service comes with pre-configured default Datastore
* Azure Blob container and blob data store are configured to serve as default Datastores
### Dataset
Dataset is a resource: a set of concrete files for exploring, transforming, testing, validating, etc. data.
* reference that points to the data in your Datastore, thus a dataset can be *shared* across other experiments without copying the data.
* answers to the questions:
* "How do a I get specific data files in my Datastore?".
* "How do I get naccess to specific data files?".
* can be created from local files, public URLs, Azure Open Datasets, and files uploaded to the datastores.
* used to interact with your data in the datastore and to package data into consumable objects.
* can be versioned
Datasets allow:
* Have a single copy of some data in your storage, but reference it multiple times—so that you don't need to create multiple copies each time you need that data available.
* Access data during model training without specifying connection strings or data paths.
* More easily share data and collaborate with other users, use the data for different experiments.
* Bookmark the state of your data by using *dataset versioning*.
Dataset types supported in Azure ML Workspace:
* The *Tabular Dataset*, which represents data in a tabular format created by parsing the provided file or list of files.
* The *Web URL* (File Dataset), which references single or multiple files in datastores or from public URLs.
#### Data versioning
Versionning gives access to traceability.
When to do versioning:
* New data is available for retraining.
* When you are applying different approaches to data preparation or feature engineering.
# Working with features
## Feature engineering
Sometimes existing features are not enough to create high quality models.
In this case we can create new features, which are derived from the original data:
* mathematically (using SQL, programming)
* by applying a ML algorithm
Classical ML algorithms depend much more on feature engineering than deep learning ones.
Feature engineering tasks on numerical data:
* aggregation (sum, count, mean, ..)
* part of (part of the date: time, year, ..)
* binning ( group data items in bins and apply aggregation on each of these beans)
* flagging - deriving boolean values
* frequency based - calculate frequency
* embedding (feature learning)
* derive by example - lean new features using examples of existing features
Text data must be first translated into numeric form.
Text embedding (transformation into numeric form) approaches:
* text frequency
* inverse document frequency
* word embedding
Image data is also translated into numeric form. And the form of the representation (matrix of RGB tuples) can be different: array of w*h*3 length, or 3D array,..
## Feature selection
Feature selection - selecting the features that are most important or most relevant for a given model.
Even if there is no feature engineering involved, the original data set can have a huge amount of feature.
Reasons for feature selection:
* eliminate irrelevant, redundant or highly correlated features.
* reduce dimensionality
The *curse of dimensionality* - many machine learning algorithms cannot accommodate a large number of features, so it is often necessary to do dimensionality reduction to decrease the number of features.
Algorythms to reduce dimensionality:
* [PCA](https://en.wikipedia.org/wiki/Principal_component_analysis) - mathematical approach based mostly on exact mathematical calculations
* [t-SNE (t-Distributed Stochastic Neighboring Entities)](https://en.wikipedia.org/wiki/T-distributed_stochastic_neighbor_embedding) - probabilistic approach; useful for the visualization of multidimensional data.
* Feature embedding - encodes a larger number of features into a smaller number of "super-features."
Azure ML prebuilt modules for feature selection:
* Filter-based feature selection: identify columns in the input dataset that have the greatest predictive power
* Permutation feature importance: determine the best features to use by computing the feature importance scores
## Data drift
Data drift - change in data which leads to model's performance degradation, the top reason for model degradation.
Most common causes:
* changes in upstream process (A sensor is replaced, causing the units of measurement to change)
* data quality issues (a sensor outage)
* data natural evolution (for example customer behavior changes over times)
* change in feature correlation
Data drift must be monitored and detected as early as possible to retrain the model.
The process of monitoring for data drift involves:
* Specifying a baseline dataset – usually the training dataset
* Specifying a target dataset – usually the input data for the model
* Comparing these two datasets over time, to monitor for differences
Scenarios for setting up for data monitoring:
1. detecting data drift - detect difference between the model input vs. training data
2. detecting data drift in timeseries dataset - detecting season data drift : current input data set vs. previous period input data set
3. performing analysis on past data
Understanding data drift results in Azure:
* data drift magnitude - the percentage of data similarity: 0% - identical, 100% - completely different data set
* drift contribution by feature - the contribution of each feature in a drift, helps to identify drifting features
# Training model
## Parameters vs. Hyperparameters
A major goal of model training is to learn the values of the *model parameters*.
In contrast, some model parameters are not learned from the data. These are called *hyperparameters* and their values are set before training. When choosing hyperparameters values, we make the *best guess*, and then we *adjust them* based on the model's performance.
Examples of hyperparameters:
* The number of layers in a deep neural network;
* The number of clusters (such as in a k-means clustering algorithm);
* The learning rate of the model.
## Splitting data
Splitting the Data
Datasets:
1. Training data - to learn the values for the *parameters*
2. Validation data - to check the model's performance and to tune the *hyperparameters*(run on training data) until the model performs well with the validation data
3. Test data - to do a final check of model's performance
## Training Classifiers
In a classification problem, the outputs are *categorical* or *discrete*.
Three main types of classification problem:
* binary classification (classify medical test results as "positive" or "negative", fraud detection) - the most difficult problem are often in this category,
* multi-class single-label classification (classify an image as one (and only one) of five possible fruits, recognition of numbers)
* multi-class multi-label classification (text tagging, classify music as belonging to multiple groups (e.g., "upbeat", "jazzy", "pop").)
## Training Regressors
In a regression problem, the output is *numerical* or *continuous*.
Two main types of regression problems:
* regression to arbitrary values - no boundary defined (price of houses based on different inputs)
* regression to values between 0 and 1 (the probability of a certain transaction to be fraudulent)
Examples og algorithms:
* linear regressor
* decision forest regressor
## Evaluating performance
Performance is evaluated on the test data. The test dataset is a portion of labeled data that is split off and reserved for model evaluation.
When splitting the available data, it is important to preserve the *statistical properties* of that data. This means that the data in the training, validation, and test datasets need to have *similar statistical properties* as the original data to prevent bias in the trained model.
Metrics used for evaluation depend on the problem we need to solve.
Establishing a set of criterias for evaluation is important:
* what is the primary metric used for evaluation?
* what us the threshold of that metric that we want to meet or to exceed to have "a good enough" model
### Evaluation mertics for classification
#### Confusion matrices
|| Actual Class X | Actual Class Y|
|:-|:-|:-|
|Predicted class X positive| correct X - True Positive (TP)| wrong X - False positive (FP) |
|Predicted class Y negative| incorrect y - False Negavites (FN)| correct Y - True Negative (TN)|
Evaluation metrics:
* accuracy - the proportion of correct predictions:
> (TP + TN) / (TP + FP + FN + TN)
* precision / - proportion of positive cases that were correctly identified; **; How many selected items are relevant?
> TP / (TP + FP)
* recall / *sensitivity* - proportion af actual positive cases that were identified; *true positive rate*; How many relevant items are selected?
> TP / (TP + FN)
* false positive rate (close to type I error)
> FP / (FP + TN)
* *specitivity* - How many negative selected elements are trully negative.
* F1 - mesures the balance between precision and recalls
> 2∗Precision∗Recall / (Precision+Recall)
To fully evaluate the effectiveness of a model, one must examine both precision and recall. Since precision and recall are often in tension: improving precision typically reduces recall and vice versa.
F1 is a measure of a test's accuracy. It takes into consideration both the precision and recall. F1 reaches its best value at 1, which means that precision and recall have perfect values (perfect balance between precision and recall).
Precision = What proportion of positive identifications was actually correct? = TP / (TP + FP)
Recall = What proportion of actual positives was identified correctly? = TP / (TP + FN)
Precision = What proportion of positive identifications was actually correct? = TP / (TP + FP)
Recall = What proportion of actual positives was identified correctly? = TP / (TP + FN)
Charts:
* Receiver Operating Characteristics (ROC) chart - the chart of *false positive rate* against the rate of FP
* Area Under the Curve (AUC)
* for random classifier the value is 0.5 (diagonal)
* for perfect classifier (100% TP) the area is 1
* Gain and lift chart - measure how much better one can expect to do with the predictive model comparing without a model
### Evaluation metrics for regression
Metrics:
* Root Mean Squared Error (RMSE) - the square root of the average of the squared differences between the predictions and the true values.
* Mean Absolute Error (MAE) - Average of the absolute difference between each prediction and the true value.
* R-squared metrics (in statistics - the coefficient of determination) - How close the regression line is to the true values.
* Spearman rank correlation - technique to measure the strength and the direction of the correlation between predicted values and the true values
Charts:
* Predicted vs true chart
* ideal regressor
* average predicted values
* histogram of distribution of true values in predicted result (should have bell-shape)
* Histogram of residuals (true value - predicted value) - must be normally distributes (bell shape)
## Training multiple models
Strength in numbers principle - to reduce the error of an individual trined ML model, we can train several models and combine their resuts.
### ensemble training
Ensemble learning - a technique to combine multiple machine learning models to produce one predictive model.
Individual algorithm trains several models as its internal training process.
Types of ensemble algorithms:
* Bagging/bootstrap aggregation
* uses *randomly selected subsets* of data to train several homogeneous models (bag of models)
* the final prediction is an equally weighted average prediction from individual models
* helps to reduce *overfitting* models that tend to have high variance (such as decision trees)
* Boosting
* uses the *same input data* to train multiple models using *different hyperparameters*.
* sequential training, with each new model correcting errors from previous models
* the final predictions are a weighted average from the individual models
* helps reduce *bias* for models.
* Stacking
* trains a large number of completely different (heterogeneous) models
* combines the outputs of the individual models into a meta-model that yields more accurate predictions
### Automated training on Azure Ml
We want to scale up the process of training the models. We have many models trained separately and we combine their results to get better outputs. Automated training is a way to get a baseline to create a model with a decent performance.
Automated machine learning automates many of the iterative, time-consuming, tasks involved in model development: selecting the best features, scaling features optimally, choosing the best algorithms, tuning hyperparameters.
Inputs to Automated training in Azure:
* dataset
* compute resources setup
* select a type of task to perform (classification, regression, forecasting)
* select primary evaluation metric
* critaria for finishing the process/ level of a quality for the model
# Resources
* [Secure data access in Azure Machine Learning](https://docs.microsoft.com/en-us/azure/machine-learning/concept-data)
* [What is an Azure Machine Learning workspace?](https://docs.microsoft.com/en-us/azure/machine-learning/concept-workspace)
* https://www.listendata.com/2014/08/excel-template-gain-and-lift-charts.html
|
Python
|
UTF-8
| 1,832 | 3.078125 | 3 |
[] |
no_license
|
import time
import calendar
from tkinter import *
from tkinter import ttk
from tkinter import font
import winsound
h=0
m=0
s=0
t="am"
def get_alarm(*args):
global h
h=input("What Hour")
global m
m=input("What Minute")
global s
s=input("What Second")
global t
t=input("Am or Pm"),upper()
def current_time():
totalSeconds= calendar.timegm(time.gmtime())
currentSeconds= totalSeconds%60
if currentSeconds < 10:
currentSeconds = "0"+str(currentSeconds)
totalMin= totalSeconds//60
currentMin=totalMin%60
if currentMin < 10:
currentMin = "0"+str(currentMin)
totalHours=totalMin//60
currentHour= totalHours%24-6
am_pm = ""
if currentHour> 12:
am_pm= "PM"
if currentHour==0:
currentHour=currentHour=12
else:
am_pm="AM"
if currentHour==0:
currentHour=currentHour=12
a=str(h)+":"+str(m)+":"+str(s)+t
timex=str(currentHour)+":"+str(currentMin)+":"+str(currentSeconds)+" "+am_pm
if timex == a:
beep()
return timex
def quit(*args):
root.destroy()
def beep():
winsound.Beep(2000, 5000)
def show_Time():
global h
global m
global s
global t
time=current_time(h,m,s,t)
txt.set(time)
root.after(1000, show_Time)
root=Tk()
#Set Window Size
root.geometry("500x200")
root.configure(background='teal')
fnt=font.Font(family='Merriweather', size=60, weight='bold')
txt = StringVar()
#Display Title and setup the color
root.after(1000, show_Time)
lbl=ttk.Label(root, textvariable=txt, font=fnt, foreground="Gold", background="teal")
#Center of screeb
lbl.place(relx=0.5, rely=0.5, anchor= CENTER)
#StartLoop
root.mainloop()
|
Python
|
UTF-8
| 1,297 | 2.546875 | 3 |
[] |
no_license
|
from models.siswa import Siswa
class SiswaController(db_controller):
def __init__(self , db_construct):
self.db = db_construct
def get_all_siswa(self):
siswa_list = []
siswa_data = self.db.session.query(Siswa).all()
for result in siswa_data:
siswa_list.append({"id":result.id , "nama":result.nama , "umur":result.umur , "kelamin":result.kelamin , "agama":result.agama , "alamat":result.alamat , "email":result.email , "kelas":result.kelas , "nilai":result.nilai , "lulus":result.lulus})
return siswa_list
def save_siswa_new(self, **data):
sis = Siswa()
for key , value in data.items:
setattr(sis , key , value)
self.db.session.add(sis)
self.db.session.commit()
def get_siswa_edit(self):
siswa_data = self.db.session.query(Sisa).filter(Siswa.id == id).first()
return siswa_data
def update_siswa(self):
siswa_data = self.db.session.query(Siswa).filter(Siswa.id == id).first()
for key , val in data.items():
setattr(siswa_data , key , val)
self.db.session.commit()
def delete_siswa(self):
siswa_data = self.db.session.query(Siswa).get(id)
self.db.session.delete(siswa_data)
self.db.session.commit()
|
Swift
|
UTF-8
| 1,347 | 2.578125 | 3 |
[] |
no_license
|
//
// MLTextRecongnizeViewController.swift
// MachineLearningBasedSystem
//
// Created by mabaoyan on 2021/5/31.
//
import UIKit
import Vision
@available(iOS 13.0, *)
class MLTextRecongnizeViewController: MLBasedSystemViewController, CaptureImageDelegate {
var date:NSDate?
override func viewDidLoad() {
super.viewDidLoad()
capture.delegate = self
}
override func createRequest() -> VNRequest? {
date = NSDate()
let request = VNRecognizeTextRequest.init()
// if #available(iOS 14.0, *) {
// let arr = try? VNRecognizeTextRequest.supportedRecognitionLanguages(for: .accurate, revision: VNRecognizeTextRequestRevision2)
// print(arr as Any)
// } else {
// // Fallback on earlier versions
// }
request.usesLanguageCorrection = true
request.recognitionLevel = .accurate
return request
}
override func processResults(result: [VNObservation]?) {
guard let rets : [ VNRecognizedTextObservation ] = result as? [ VNRecognizedTextObservation ] else {
return
}
guard let texts = rets.first?.topCandidates(2) else {
return
}
for object in texts {
print( object.string, object.confidence )
}
}
}
|
PHP
|
UTF-8
| 983 | 2.53125 | 3 |
[] |
no_license
|
<?php
session_start();
if(isset($_SESSION['clearence'])){
if($_SESSION['clearence']>1){
//after clearence check, start checkout table process
require_once("../includes/inc.header.php");
require_once("../includes/inc.db.php");
$con = connect();
try {
//get change book to checked in
$sql = $con->prepare("UPDATE litlookup SET checkedOut=false where id = :id");
$sql->bindParam(':id', $_GET['id']);
$sql->execute();
//update for checkin date
$sql = $con->prepare("UPDATE customerborrows SET checkinDATE = '" . date("Y/m/d") . "' where custID = :custid AND litlookupID = :litid");
$sql->bindParam(':custid', $_GET['customerid']);
$sql->bindParam(':litid', $_GET['id']);
$sql->execute();
echo '
<h2>Book checked back in!</h2>
';
}catch(PDOException $e){
echo $e->getMessage();
}
}
else{
//protection against session not being the right clearence
echo '<h1>ACCESS DENIED</h1>';
}
}
else{
echo '<h1>ACCESS DENIED</h1>';
}
?>
|
JavaScript
|
UTF-8
| 1,003 | 2.875 | 3 |
[] |
no_license
|
const axios = require("axios");
module.exports = {
myFunction: function() {
console.log("Custom function called...123");
},
sendSMS: async function(mobile, msg) {
msg = encodeURI(msg);
axios
.get(
process.env.SMS_PATH +
"&to=" +
mobile +
"&sender=ROSEAT&message=" +
msg +
"&format=json"
)
.then(function(response) {
console.log(response);
console.log("Mobile is : ");
console.log(mobile);
})
.catch(function(error) {
//console.log(error);
});
},
validateEmail: function(mail) {
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(mail)) {
return true;
}
return false;
},
mobileNumber: function(mobile) {
var phoneno = /^\d{10}$/;
if (mobile.match(phoneno)) {
return true;
} else {
return false;
}
},
randomSixDigit: function() {
return Math.floor(100000 + Math.random() * 900000);
}
};
|
C++
|
UTF-8
| 4,359 | 3.109375 | 3 |
[
"MIT"
] |
permissive
|
#include "OPERADORA_FRAC.h"
#include <iostream>
int OperaTADFRAC::numerador()const {
return numerator;
}
void OperaTADFRAC::numerador(int n){
numerator = n;
}
double OperaTADFRAC::resultado()const{
return result;
}
void OperaTADFRAC::resultado(double r){
result = r;
}
int OperaTADFRAC::denominador() const{
return denominator;
}
void OperaTADFRAC::denominador(int d){
denominator = d;
}
OperaTADFRAC::OperaTADFRAC(){
numerador(0);
denominador(1);
resultado((0/(double)1));
}
OperaTADFRAC::OperaTADFRAC(int n, int d){
simplifies(n,d);
resultado((n/(double)d));
}
OperaTADFRAC::OperaTADFRAC(const OperaTADFRAC &o){
numerador(o.numerador());
denominador(o.denominador());
resultado((o.numerador()/(double)o.denominador()));
}
int OperaTADFRAC::mdc(int n,int d){
int mdc;
int j;
j = d;
if(n > d){
j = n;
}
for(int i = 1; i < j;i++){
if(n%i == 0 && d%i == 0){
mdc = i;
}
}
return mdc;
}
int OperaTADFRAC::mmc(int d1,int d2){
int mdc;
int j;
if(d1 == d2)
return d1;
if(d1 > d2){
j = d1;
}else{
j = d2;
}
for(int i = 1; i < j;i++){
if(d1%i == 0 && d2%i == 0){
mdc = i;
}
}
//DEF:sejam a e b dois naturais validos, temos que MMC(a,b) = (a.b)/MDC
return (d1*d2)/mdc;
}
void OperaTADFRAC::simplifies(int n,int d){
if ((n%d) == 0){
numerador(n/d);
denominador(1);
}else{
if ((d%n) == 0){
denominador(d/n);
numerador(1);
}else{
numerador(n/mdc(n,d));
denominador(d/mdc(n,d));
}
}
}
OperaTADFRAC OperaTADFRAC::operator +(const OperaTADFRAC &f){
OperaTADFRAC fra;
if(f.denominador() == denominador()){
fra.denominador(f.denominador());
fra.numerador((f.numerador() + numerador()));
}else{
fra.denominador(mmc(f.denominador(),denominador()));
fra.numerador(f.numerador() + numerador());
}
return fra;
}
OperaTADFRAC OperaTADFRAC::operator -(const OperaTADFRAC &f){
OperaTADFRAC fra;
if(f.denominador() == denominador()){
fra.denominador(f.denominador());
fra.numerador((numerador() - f.numerador()));
}else{
fra.denominador(mmc(f.denominador(),denominador()));
fra.numerador(numerador() - f.numerador());
}
return fra;
}
OperaTADFRAC OperaTADFRAC::operator *(const OperaTADFRAC &f){
OperaTADFRAC fra;
fra.numerador(numerador()*f.numerador());
fra.denominador(denominador()*f.denominador());
return fra;
}
OperaTADFRAC OperaTADFRAC::operator /(const OperaTADFRAC &f){
OperaTADFRAC fra;
fra.numerador(numerador()*f.denominador());
fra.denominador(denominador()*f.numerador());
return fra;
}
OperaTADFRAC OperaTADFRAC::operator =(const OperaTADFRAC &o){
OperaTADFRAC aux(o);
numerador(o.numerador());
denominador(o.denominador());
return aux;
}
bool OperaTADFRAC::operator ==(const OperaTADFRAC &o){
return (numerador() == o.numerador() && denominador() == o.denominador());
}
bool OperaTADFRAC::operator <(const OperaTADFRAC &o){
return (resultado() < o.resultado());
}
bool OperaTADFRAC::operator >(const OperaTADFRAC &o){
return (resultado() > o.resultado());
}
ostream& operator <<(ostream& saida,OperaTADFRAC &o){
cout << "Fracao: " << o.numerador() << "/" << o.denominador() << " Resultado: " << o.resultado() ;
return saida;
}
bool OperaTADFRAC::operator<=(const OperaTADFRAC &o){
return (resultado()< o.resultado() || numerador()== o.numerador() && denominador() == o.denominador());
}
bool OperaTADFRAC ::operator>=(const OperaTADFRAC &o){
return (resultado() > o.resultado() || o.numerador() && denominador() == o.denominador());
}
string OperaTADFRAC::toString(){
int numAux = numerador();
int denAux = denominador();
double resulAux = resultado();
string nume = string(reinterpret_cast<char*>(&numAux), sizeof(int));
string deno = string(reinterpret_cast<char*>(&denAux), sizeof(int));
string resu = string(reinterpret_cast<char*>(&resulAux), sizeof(double));
string palavra = (nume + deno + resu);
return palavra;
}
void OperaTADFRAC::fromString(string repr){
char numAux[sizeof(int)];
repr.copy(numAux,sizeof(int),0);
char denAux[sizeof(int)];
repr.copy(denAux,sizeof(int),4);
char resulAux[sizeof(double)];
repr.copy(resulAux,sizeof(double),8);
numerator = *reinterpret_cast<int*>(&numAux);
denominator = *reinterpret_cast<int*>(&denAux);
result = *reinterpret_cast<double*>(&resulAux);
}
|
Markdown
|
UTF-8
| 4,396 | 3.015625 | 3 |
[] |
no_license
|
### Content
* [Consistency of Plug-in Confidence Sets for Classification in Semi-supervised Learning](#CPCSCSL)
<h2 id="#CPCSCSL">
### [Consistency of Plug-in Confidence Sets for Classification in Semi-supervised Learning](https://arxiv.org/pdf/1507.07235.pdf)
<p align="right"> Jan. 4, 2020 </p>
Not assigining labels for instances is better than giving non-confident predictions when wrong classifications may lead to a huge cost. Therefore, this paper proposed a method, level-$\varepsilon$-confidence sets, to give confident predictions in the binary classification cases. Many works are related to this method, like Conformal Prediction (CP) and Classification with Reject Option (CRO), even if they have different focuses.
The most difference from others is that level-$\varepsilon$-confidence sets control the proportion ($\varepsilon$) of classifying or the probability ($1-\varepsilon$) of reject option. Generally, the smaller $\varepsilon$, the more accurate prediction. However, CP does not take into account the reject option, although it guarantees the coverage probability. Similarly, CRO, though, considers the reject option, devotes to minimize a risk given a preset torelance (d) of reject option and do not care how much the rejection probability is (it does not control any part in a risk function). Both two methods can compromise the rejection probability to improve the missclassification. Therefore, it is much easier when comparing two classifiers given the controled probability of classifying if we utilize the proposed one in this paper.
This method takes estimation of $\eta^\ast(X)$ and unlabeled data to produce level-$\varepsilon$-confidence sets. Explicitly, we use labeled $D_n$ to obtain an estimation $\hat \eta(X)$ of $\eta^\ast(X)$ if we do not know the distribution of data (most time we do not know) and take $\hat f(X)=\max\\{\hat \eta(X), 1- \hat \eta(X)\\}$ as our score. Secondly, we use another (un)labled $D_N$ to estimate the distribution of $\hat f$, say $\hat F_{\hat f}$ and get the quantile threshold $\alpha_\varepsilon$. Given an upcoming instance $x$, we assigin a label for it based on $\hat \eta(x)$ if $\hat f(x)\geq \alpha_\varepsilon$, otherwise it falls into reject option. In contrast, for CRO, $\alpha_\varepsilon=1-d$ is a constant and hence we do not need one more dataset to find a threshold. However, it is this that we cannot guarantee the classifying probability.
Based on above procedure, if the estimation $\hat \eta$ is consistent ($\hat \eta \rightarrow \eta^\ast$ with probability 1 as $n\rightarrow \infty$), then asymtocically the plug-in $\varepsilon$-confidence set performs as well as the $\varepsilon$-confidence set (which is obtained by knew distribution and no estimation in any steps). However, the key this method relies on continuous cdfs of score functions $f^\ast$ and $\hat f$, which transduces to the continuity of $\eta^\ast$ and $\hat \eta$.
In numerical studyies, for data generated based on continuous $\eta^\ast$, it uses randomforest, logistic regression as well as kernel estimation to get $\hat\eta$. From the results, these three plug-in $\varepsilon$-confidence sets match the theories, although randomforest is outperformed by the others. Moreover, increasing the sample size $n$ on estimation of $\eta^\ast$ can improve the convergence rate. However, if $\eta^\ast$ is continouse but we use CART to estimate it (now $\hat\eta$ is not continuous), we cannot control the classifying probability and the risk also converges slowly. For the case data generated by discrete $\eta^\ast$ but estimated by kernel method ($\hat\eta$ is continuous), it is irrelavant to compare the performance of $\varepsilon$-confidence sets and its plug-in counterpart, although the results match the theoretical study.
In conclusion, this method outputs an optimal result when control the classifying probability, which is helpful when compare two classifiers with reject option. For further thinking, I think this method is sort of like a dual problem for the topic "minimizing the size of prediction set when controling the accuracy". Moreover, can we use hard classifiers with this proposed method since sometimes probability estimation is difficult, especially in high-dimensional cases. Also, we need to read related work tackling multiclass cases.
</h2>
|
Markdown
|
UTF-8
| 25,059 | 2.6875 | 3 |
[] |
no_license
|
Alatazan estava curioso com o desempenho de _Neninha_, sua modelo predileta.
<img src="http://www.aprendendodjango.com/media/img/ilustracao_7.gif" align="right"/>
- E aí, como foi lá, Nena?
- Puxa, foi mó legal, parece que eles gostaram dela!
- É? E ela foi contratada?
- Ahhh, você sabe como é o papai né... categórico, inseguro, todo certinho... ainda vai estudar melhor...
- Mas como isso funciona, essa coisa das passarelas e tal? Tem que começar tão novinha assim?
- É sim. Olha, é como uma obra de arte, sabe... quando uma modelo abre as cortinas e sai pela passarela, ela aparece e ganha os cliques, mas o fato é que sem um **empresário** no _backstage_, desde pequena, pra acertar as coisas e dar todo o suporte, ela vai ser só mais um rosto bonitinho por trás de um balcão de uma loja de roupas...
- Sei...
- E tem a **estilista** também, sabe... toda espirituosa! Ela produz, dá vida à modelo... é ela quem faz a arte. A modelo só representa o papel.
E então? Neninha estava perto de ser a nova contratada de uma dessas agências de modelo, mas daria pra confiar naquele _Manager_? E para quem ela representaria? Bom, vamos vendo...
## Buscando os números finais
No capítulo anterior, criamos uma aplicação de **Contas Pessoais** - a pagar e a receber.
Nós falamos muito sobre heranças e algumas funcionalidades bacanas do Admin. Mas hoje, vamos aprofundar um pouco mais ainda no ORM do Django.
Como você já sabe, o ORM é o **Mapeador Objeto/Relacional**. Trata-se de uma parte do Django que traduz as coisas de objetos Python para expressões em linguagem SQL, de forma a persistir as informações no banco de dados.
O ORM possui uma **trindade** fundalmental:
<p align="center">
<img src="http://www.aprendendodjango.com/gallery/model-manager-queryset/file/"/>
</p>
Através dos vários capítulos que se passaram, falamos em muitas ocasiões sobre classes de modelo, aquelas que herdam da classe **"django.db.models.Model"**, mas nada falamos sobre o Manager e a QuerySet.
Pois vamos falar agora!
### O Manager
Toda classe de modelo possui um Manager padrão. Ele se trata do atributo **"objects"** da classe, veja aqui um exemplo onde o Manager está presente e você nem sabia disso:
def albuns(request):
lista = Album.objects.all()
return render_to_response(
'galeria/albuns.html',
locals(),
context_instance=RequestContext(request),
)
Observe ali esta linha:
lista = Album.objects.all()
Sim, aquele **"objects"** ali se trata do Manager da classe **"Album"**!
E sabe o que ele faz? Ele é o ponto de apoio da classe. Veja, na grande maioria das situações em que usamos a classe de modelo diretamente, ele está lá, veja:
Criando um objeto...
novo_album = Album.objects.create(nome='Meu novo album')
Carregando um objeto:
album = Album.objects.get(id=1)
Carregando ou criando um objeto:
novo_album, novo = Album.objects.get_or_create(nome='Meu novo album')
Carregando uma lista de objetos:
lista = Album.objects.all()
Veja que lá está o Manager... nem um pouco popular e aparecido quanto o Model, mas ele está sempre lá, dando todo o suporte necessário e dando liga às coisas.
### A QuerySet
E existe também a QuerySet! Ela é de fato quem dá vida ao Modelo, sempre atendendo prontamente aos pedidos do Manager.
A QuerySet efetiva as **persistências** e **consultas** no banco de dados, e é ela quem de fato dá ação à coisa e faz a arte na comunicação com o banco de dados... veja novamente os exemplos acima... ela também está lá!
O método **"create()"** é passado do Manager **"objects"** para sua QuerySet padrão:
novo_album = Album.objects.create(nome='Meu novo album')
Aqui novamente: o método **"get()"** é passado à QuerySet padrão do Manager:
album = Album.objects.get(id=1)
A mesma coisa: o método **"get\_or\_create()"** também é passado à QuerySet padrão do Manager:
novo_album, novo = Album.objects.get_or_create(nome='Meu novo album')
E aqui mais uma vez:
lista = Album.objects.all()
Você pode notar que na maioria das operações que tratam uma classe de modelo **não instanciada** em sua relação com o banco de dados, lá estarão presentes também a organização do **Manager** e a arte da **QuerySet**.
As QuerySets são extremamente **criativas e excitantes** porque elas possuem métodos que podem ser encadeados uns aos outros, de forma a criar uma complexa e comprida sequência de filtros e regras, que somente quando é de fato requisita, é transformada em uma expressão SQL e efetivada ao banco de dados.
Agora vamos ver essas coisas na prática?
### Criando o primeiro Manager
Para começar, vá até a pasta da aplicação **"contas"** e abra o arquivo **"models.py"** para edição. Localize a seguinte linha:
class Historico(models.Model):
**Acima** dela, acrescente o seguinte trecho de código:
class HistoricoManager(models.Manager):
def get_query_set(self):
query_set = super(HistoricoManager, self).get_query_set()
return query_set.extra(
select = {
'_valor_total': """select sum(valor) from contas_conta
where contas_conta.historico_id = contas_historico.id""",
}
)
Opa! Mas espera aí, que tanto de novidades de uma vez só, vamos com calma né!
Ok, então vamos linha por linha...
Observe bem esta linha abaixo. Estamos criando ali um **Manager** para a classe **"Historico"**. Mas porquê criar um manager se ela já possui um?
É que o manager padrão tem um comportamento padrão, e nós queremos mudar isso. Sabe o que estamos indo fazer aqui? Nós vamos criar um novo **campo calculado**, que irá carregar o **valor total** das **contas a pagar e a receber** ligadas ao objeto de **Histórico**!
Todo Manager deve herdar a classe **"models.Manager"**:
class HistoricoManager(models.Manager):
Este método que declaramos, **"get\_query\_set"** retorna a QuerySet padrão toda vez que um método do Manager é chamado para ser passado a ela. Estamos aqui novamente mudando as coisas padrão, para ampliar seus horizontes:
def get_query_set(self):
E a primeira coisa que o método faz é chamar o mesmo método da classe herdada, mais ou menos aquilo que fizemos em um dos capítulos anteriores, lembra-se?
query_set = super(HistoricoManager, self).get_query_set()
Logo adiante, nós retornamos a **QuerySet**, encadeando o método **"extra()"** à festa.
O método **"extra()"** tem o papel de acrescentar informações que nenhuma das outras acrescentam. Aqui podemos acrescentar campos calculados adicionais, condições especiais e outras coisinhas assim...
return query_set.extra(
E o argumento que usamos no método **"extra()"** é o **"select"**, que acrescenta um campo calculado ao resultado da QuerySet, veja:
select = {
'_valor_total': """select sum(valor) from contas_conta
where contas_conta.historico_id = contas_historico.id""",
}
Com esse novo campo, chamado **"\_valor\_total"**, podemos agora exibir a soma total do campo **"valor"** de todas as **Contas** vinculadas ao Histórico.
Está um pouco confuso? Não se preocupe, vamos seguir adiante e aos poucos as coisas vão se encaixando... você não queria entender como funciona o **mundo da moda** em apenas algumas poucas palavras né?
Agora localize esta linha, ela faz parte da classe **"Historico"**:
descricao = models.CharField(max_length=50)
Acrescente abaixo dela:
objects = HistoricoManager()
def valor_total(self):
return self._valor_total
Veja o que fizemos:
Primeiro, efetivamos o Manager que criamos - **"HistoricoManager"** - para ser o Manager padrão da classe **"Historico"**.
Vale ressaltar que uma classe de modelo pode possuir quantos Managers você quiser, basta ir criando outros atributos e atribuindo a eles as instâncias dos managers que você criou...
objects = HistoricoManager()
E aqui nós criamos uma função para retornar o valor do campo calculado **"\_valor\_total"**.
Sabe porquê fizemos isso? Porque há algumas funcionalidades no Django que exigem atributos declarados diretamente na classe, e como o campo **"\_valor\_total"** é calculado, ele "aparece" na classe somente quando esta é instanciada, resultando de uma QuerySet.
Então o que fizemos? Nós já criamos o campo com um caractere **"\_"** como prefixo, e o encapsulamos por trás de um método criado manualmente...
def valor_total(self):
return self._valor_total
Ok, vamos agora fazer mais uma coisinha, mas não aqui.
Salve o arquivo. Feche o arquivo.
Na mesma pasta, abra agora o arquivo **"admin.py"** para edição, e localize este trecho de código:
class AdminHistorico(ModelAdmin):
list_display = ('descricao',)
Modifique a segunda linha para ficar assim:
class AdminHistorico(ModelAdmin):
list_display = ('descricao','valor_total',)
Você notou que acrescentamos o campo **"valor\_total"** à listagem da classe **"Historico"**?
Salve o arquivo. Feche o arquivo.
Agora execute o projeto, clicando duas vezes sobre o arquivo **"executar.bat"** e vá até o navegador, carregando a seguinte URL:
http://localhost:8000/admin/contas/historico/
Veja como ela aparece:
<p align="center">
<img src="http://www.aprendendodjango.com/gallery/contas-admin-com-campo-de-valor-total/file/"/>
</p>
Uau! Isso é legal, gostei disso! Mas vamos dar um jeito de tirar aquele **"None"** dali e deixar um **zero** quando a soma retornar um valor vazio? OK, vamos lá!
Na pasta da aplicação **"contas"**, abra o arquivo **"models.py"** para edição e localize estas linhas de código:
def valor_total(self):
return self._valor_total
Modifique a segunda linha, para ficar assim:
def valor_total(self):
return self._valor_total or 0.0
Isso vai fazer com que, caso o valor contido no campo calculado **"\_valor\_total"** seja inválido, o valor **"0.0"** retorne em seu lugar.
Salve o arquivo.
Agora vamos fazer o mesmo campo calculado para a classe **"Pessoa"**. Localize a seguinte linha:
class Pessoa(models.Model):
Acima dela, acrescente este trecho de código:
class PessoaManager(models.Manager):
def get_query_set(self):
query_set = super(PessoaManager, self).get_query_set()
return query_set.extra(
select = {
'_valor_total': """select sum(valor) from contas_conta
where contas_conta.pessoa_id = contas_pessoa.id""",
'_quantidade_contas': """select count(valor) from contas_conta
where contas_conta.pessoa_id = contas_pessoa.id""",
}
)
Veja que dessa vez fomos um pouquinho além, nós criamos dois campos calculados: um para **valor total** das contas e outro para sua **quantidade**. Observe que as _subselects_ SQL para ambos são semelhantes, com a diferença de que a do **valor total** usa a agregação **"SUM"**, enquanto que a de **quantidade** usa **"COUNT"**.
Agora localize esta outra linha:
telefone = models.CharField(max_length=25, blank=True)
E acrescente abaixo dela:
objects = PessoaManager()
def valor_total(self):
return self._valor_total or 0.0
def quantidade_contas(self):
return self._quantidade_contas or 0
Você pode notar que a definimos o Manager da classe Pessoa e em seguida declaramos as duas funções que fazem acesso aos campos calculados que criamos.
Mas qual é a diferença entre retornar **"0.0"** e retornar **"0"**?
Quando um número possui uma ou mais **casas decimais**, separadas pelo ponto, o Python entende que aquele é um **número flutuante**, e já quando não possui, é um número inteiro. O **valor total** das contas sempre será um valor flutuante, mas a **quantidade** de contas sempre será em número inteiro. É isso.
Salve o arquivo. Feche o arquivo. Agora é preciso ajustar o Admin da classe **"Pessoa"**.
Abra o arquivo **"admin.py"** da mesma pasta para edição e localize o seguinte trecho de código:
class AdminPessoa(ModelAdmin):
list_display = ('nome','telefone',)
Modifique-o para ficar assim:
class AdminPessoa(ModelAdmin):
list_display = ('nome','telefone','valor_total','quantidade_contas')
Salve o arquivo. Feche o arquivo.
Volte ao navegador e carregue esta URL:
http://localhost:8000/admin/contas/pessoa/
E veja como ela se sai:
<p align="center">
<img src="http://www.aprendendodjango.com/gallery/contas-admin-de-pessoa-com-campos-calculado/file/"/>
</p>
Bacana, não é? Agora vamos criar uma **conta a pagar** para ver como a coisa toda funciona, certo?
Vá a esta URL:
http://localhost:8000/admin/contas/contapagar/add/
E crie uma **Conta a Pagar** como esta abaixo:
<p align="center">
<img src="http://www.aprendendodjango.com/gallery/contas-nova-conta-a-pagar/file/"/>
</p>
Salve a conta e volte à URL da classe **"Pessoa"** no Admin:
http://localhost:8000/admin/contas/pessoa/
E veja agora como ela está:
<p align="center">
<img src="http://www.aprendendodjango.com/gallery/contas-pessoas-com-valores-sem-sinal/file/"/>
</p>
Isso não ficou legal... o campo de **quantidade de contas** mostra seu valor corretamente, mas veja o campo de **valor total**: se lançamos uma **Conta a Pagar**, ela deveria estar em **valor negativo**.
Então para resolver isso, abra o arquivo **"models.py"** da pasta da aplicação **"contas"** para edição e localize esta linha. Ela está dentro do método **"get\_query\_set()"** da classe **"HistoricoManager"**:
'_valor_total': """select sum(valor) from contas_conta
where contas_conta.historico_id = contas_historico.id""",
Modifique-a para ficar assim:
'_valor_total': """select sum(valor * case operacao when 'c' then 1 else -1 end)
from contas_conta
where contas_conta.historico_id = contas_historico.id""",
Observe que fazemos uma condição ali, e **multiplicamos** o campo **"valor"** por **1** ou **-1** caso a **operação financeira** seja de **crédito** ou não (de **"débito"**, no caso), respectivamente.
Agora vamos fazer o mesmo com a classe **"PessoaManager"**:
'_valor_total': """select sum(valor) from contas_conta
where contas_conta.pessoa_id = contas_pessoa.id""",
Modifique para ficar assim:
'_valor_total': """select sum(valor * case operacao when 'c' then 1 else -1 end)
from contas_conta
where contas_conta.pessoa_id = contas_pessoa.id""",
Salve o arquivo. Feche o arquivo. Volte ao navegador, pressione **F5** para atualizar, e veja como ficou:
<p align="center">
<img src="http://www.aprendendodjango.com/gallery/contas-pessoas-com-valores-com-sinal/file/"/>
</p>
Satisfeito agora?
### Totalizando campos
Bom, agora que você já teve um contato razoável com um Manager e sua QuerySet padrão, que tal fazermos uma pequena mudança no Admin das **Contas**?
Vamos fazer assim: na pasta da aplicação **"contas"**, crie uma nova pasta, chamada **"templates"** e dentro dela outra pasta chamada **"admin"**.
Diferente? Pois vamos criar mais pastas: dentro da nova pasta **"admin"**, crie outra, chamada **"contas"** e dentro dela mais uma, chamada **"contapagar"**.
Agora dentro desta última pasta criada, crie um novo arquivo, chamado **"change\_list.html"**. Deixe-o vazio por enquanto.
Agora feche a janela do Django **em execução** (aquela janela do MS-DOS que fica sempre _pentelhando_ por ali) e execute novamente, para que a nossa nova pasta de **templates** faça efeito. Para isso, clique duas vezes no arquivo **"executar.bat"** da pasta do projeto.
Agora vá à URL da classe **"ContaPagar"** no Admin, assim:
http://localhost:8000/admin/contas/contapagar/
Veja:
<p align="center">
<img src="http://www.aprendendodjango.com/gallery/contas-conta-a-pagar-vazia/file/"/>
</p>
Gostou? Lógico que não, mas o que houve de errado?
O arquivo **"change\_list.html"** que criamos e deixamos vazio fez esse estrago. Sempre quando existe uma pasta de **templates** com uma pasta **"admin"**, dentro dela uma pasta com o nome da aplicação ( **"contas"** ) e dentro dela uma pasta com o nome da classe de modelo ( **"contapagar"** ), o Admin do Django tenta encontrar ali um arquivo chamado **"change\_list.html"** para usar como **template da listagem** daquela classe. E o arquivo está vazio, o que mais você queria que acontecesse?
Pois então abra esse arquivo e escreva o seguinte código dentro:
{% extends "admin/change_list.html" %}
{% block result_list %}
<p>
Quantidade: {{ total }}<br/>
Soma: {{ soma|floatformat:2 }}
</p>
{% endblock result_list %}
Observe que no início de tudo, o template **"admin/change\_list.html"** é herdado. Esse template faz parte do próprio Django e deve ser usado como base para nossas modificações. Ele é o template original que o Django sempre usa para listagens no Admin.
{% extends "admin/change_list.html" %}
E logo depois, nós extendemos o bloco **"result\_list"** e colocamos ali duas linhas: uma para exibir a **quantidade** e outra, a **soma** das contas a pagar:
{% block result_list %}
<p>
Quantidade: <b>{{ total }}</b><br/>
Soma: <b>{{ soma|floatformat:2 }}</b>
</p>
{% endblock result_list %}
Salve o arquivo e volte ao navegador, atualize com **F5** e veja:
<p align="center">
<img src="http://www.aprendendodjango.com/gallery/contas-conta-a-pagar-sem-lista-de-objetos/file/"/>
</p>
Opa, cadê as minhas contas? Não se sinta aliviado, suas contas sumiram mas continuam existindo... é que nós nos esquecemos de uma coisa importante.
Localize esta linha no template que estamos editando:
{% block result_list %}
E modifique para ficar assim:
{% block result_list %}{{ block.super }}
Isso vai evitar que perdamos o que já está lá, funcionando bonitinho.
Salve o arquivo. Feche o arquivo. Atualize o navegador com **F5** e veja:
<p align="center">
<img src="http://www.aprendendodjango.com/gallery/contas-conta-a-pagar-sem-valores-no-sumario/file/"/>
</p>
Pronto, voltamos ao normal, com o nosso **sumário** ali, ainda que com valores vazios.
Agora vá até a pasta da aplicação **"contas"** e abra o arquivo **"admin.py"** para edição. Localize este trecho de código nele:
class AdminContaPagar(ModelAdmin):
list_display = ('data_vencimento','valor','status','historico','pessoa')
search_fields = ('descricao',)
list_filter = ('data_vencimento','status','historico','pessoa',)
exclude = ['operacao',]
inlines = [InlinePagamentoPago,]
date_hierarchy = 'data_vencimento'
Aí está a classe de Admin da classe **"ContaPagar"**. Acrescente este bloco de código abaixo dela:
def changelist_view(self, request, extra_context={}):
qs = self.queryset(request)
extra_context['soma'] = sum([i['valor'] for i in qs.values('valor')])
extra_context['total'] = qs.count()
return super(AdminContaPagar, self).changelist_view(request, extra_context)
Observe que se trata de um novo método para a classe de Admin da classe **"ContaPagar"**. Este método é a _view_ da URL de listagem do Admin desta classe de modelo. Na segunda linha, nós carregamos a **QuerySet** para ele, usando sua **request** (requisição):
def changelist_view(self, request, extra_context={}):
qs = self.queryset(request)
A QuerySet que carregamos para a variável **"qs"** já é devidamente filtrada e organizada pela chamada ao método **"self.queryset(request)"**, mas ela vai ser útil para nós.
Na declaração do método há um argumento chamado **"extra\_context"** e o nosso trabalho aqui é dar a ele duas novas variáveis:
extra_context['soma'] = sum([i['valor'] for i in qs.values('valor')])
extra_context['total'] = qs.count()
Uau! Veja, o método **"values()"** de uma QuerySet retorna **somente** os valores dos campos informados como argumentos, em uma lista de dicionários, assim:
>>> qs.values('valor')
[{'valor': Decimal("44.53")}, {'valor': Decimal("1.0")}]
Nós temos ali uma _list comprehension_, criada para retornar somente o conteúdo do campo valor, assim:
>>> [i['valor'] for i in qs.values('valor')]
[Decimal("44.53"), Decimal("1.0")]
E por fim, a função **"sum"** é uma função padrão do Python que soma todos os valores de uma lista, assim:
>>> sum([i['valor'] for i in qs.values('valor')])
Decimal("45.53")
Então, a soma do campo **"valor"** será atribuída ao item **"soma"** do dicionário **"extra\_context"**.
E veja que na linha seguinte nós retornamos a **quantidade** de contas a pagar:
extra_context['total'] = qs.count()
O método **"count()"** da QuerySet retorna a quantidade total dos objetos.
Por fim, a última linha é esta:
return super(AdminContaPagar, self).changelist_view(request, extra_context)
Como já existe um método **"changelist\_view()"** na classe herdada, nós invocamos o **super()** para trazer o tratamento do método original, mas acrescentamos o dicionário **"extra\_context"**, que vai levar as variáveis **"soma"** e **"quantidade"** ao contexto dos templates.
Salve o arquivo. Feche o arquivo. Volte ao navegador e pressione **F5**. Veja o resultado:
<p align="center">
<img src="http://www.aprendendodjango.com/gallery/contas-conta-a-pagar-com-sumario-funcionando/file/"/>
</p>
Muito bom! Agora crie outras contas a pagar, e observe como a **quantidade** e a **soma** dos valores são atualizados nessa página.
## Agora, por quê não um front-end mais amigável para isso?
Alatazan mal concluiu essa sequência e já começou a ter idéias...
- Porquê não criar uma seção no site para outras pessoas organizarem suas contas pessoais?
- Bacana, camarada, como seria isso?
- Sei lá, algo assim: o cara entra, faz um cadastro e começa a organizar suas **Contas Pessoais**. Simples assim...
- Alatazan, gostei da idéia, mas vamos resumir o estudo de hoje e deixar isso para amanhã?
Nena tinha razão... havia uma coisa em comum entre eles naquele momento: **a fome roncando na barriga**...
- Ok, vamos lá:
- Não existe Modelo sem Manager, e não existe Manager sem QuerySet. E as QuerySets trabalham principalmente com a classe de Modelo, é um ciclo que nunca se acaba;
- A classe de modelo define como é sua **estrutura** e sua instância representa um **objeto** resultante dessa estrutura;
- A classe de Manager **organiza** as coisas, é como o empresário de jogadores de futebol... mas o nosso Manager é justo e ético;
- A classe de QuerySet é o **artista** da coisa, faz as coisas acontecerem de forma muito elegante;
- Toda classe de modelo possui um Manager padrão, que possui uma QuerySet padrão;
- O Manager padrão é atribuído ao atributo **objects** da classe de modelo, já a QuerySet padrão é retornada pelo método **"get\_query\_set()"** do Manager;
- A QuerySet pode receber inúmeros métodos encadeados, como **filter()**, **exclude()**, **extra()**, **count()**, **values()**, etc. Somente quando for requisitada ela vai gerar uma expressão **SQL** como resultado disso e irá enviar ao banco de dados, da forma mais otimizada e leve possível;
- Para interferir no funcionamento da listagem do Admin, devemos sobrepôr o método **"changelist_view()"** da classe de Admin;
- E para mudar o template da listagem, criamos o template **"change\_list.html"** dentro de uma árvore de pastas que começa da pasta de **templates**, depois uma para o próprio **admin**, outra para o **nome da aplicação** e mais uma para o **nome da classe de modelo**.
- Algo mais?
- Ahh, camarada... eu já ia esquecendo de dizer uma coisa importate: quando uma QuerySet é requisitada ao banco de dados, o resultado do que ela resgatou de lá ficar em um **cache interno**. E caso ela seja requisitada novamente, ela será feita direto na memória, sem precisar de ir ao banco de dados de novo...
- Então vamos comer né gente!
Nos próximos capítulos vamos criar uma interface para a aplicação de **Contas Pessoais** e permitir que outros usuários trabalhem com ela.
|
Python
|
UTF-8
| 996 | 3.109375 | 3 |
[] |
no_license
|
#1226. [S/W 문제해결 기본] 7일차 - 미로1
def dfs(a,b):
if maze[a][b] == 3:
global result
result = 1
return
elif result ==1:
return
else:
global visited
visited[a][b] = True
if b+1 <16 and maze[a][b+1] != 1 and visited[a][b+1] == False:
dfs(a,b+1)
if b>0 and maze[a][b-1] != 1 and visited[a][b-1] == False:
dfs(a,b-1)
if a+1< 16 and maze[a+1][b] != 1 and visited[a+1][b] == False:
dfs(a+1,b)
if a>0 and maze[a-1][b] != 1 and visited[a-1][b] == False:
dfs(a-1,b)
visited[a][b] = False
for test_case in range(10):
tc = int(input())
maze = [list(map(int, input())) for _ in range(16)]
visited = [[False for _ in range(16)] for _ in range(16)]
result = 0
for i in range(16):
for j in range(16):
if maze[i][j] == 2:
dfs(i,j)
break
print('#{} {}'.format(tc, result))
|
Python
|
UTF-8
| 662 | 4 | 4 |
[] |
no_license
|
'''
要求
1、要有明确的结束条件 (递归最多999次)
2、每次进入更深一层递归时,问题规模相比上次递归都应有所减少
3、递归效率不高,递归层次过多会导致栈溢出(在计算机中,函数调用是通过栈(stack)这个数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈会漏一层栈桢。由于栈的大小不是无限的,所以递归调用的次数多,会导致栈溢出)
'''
def calc(n):
print(n)
return calc(n + 1)
# calc(0)
def calcs(n):
print(n)
if int(n / 2) > 0:
return calcs(int(n / 2))
calcs(100)
|
Java
|
UTF-8
| 752 | 2 | 2 |
[] |
no_license
|
package com.smartstudy.xxd.mvp.contract;
import com.smartstudy.commonlib.entity.SmartSchoolRstInfo;
import com.smartstudy.commonlib.mvp.base.BasePresenter;
import com.smartstudy.commonlib.mvp.base.BaseView;
import com.smartstudy.xxd.entity.SmartChooseInfo;
import java.util.ArrayList;
/**
* Created by louis on 2017/3/1.
*/
public interface SrtChooseSchoolContract {
interface View extends BaseView<SrtChooseSchoolContract.Presenter> {
void doChooseSuccess(ArrayList<SmartSchoolRstInfo> schoolInfo);
void getHasTestNumSuccess(String num);
}
interface Presenter extends BasePresenter {
void goChoose(SmartChooseInfo info, ArrayList<SmartSchoolRstInfo> schoolInfo);
void getHasTestNum();
}
}
|
Java
|
UTF-8
| 431 | 2.21875 | 2 |
[] |
no_license
|
package com.beeva.banco.BancoBeeva.dao;
import java.util.List;
import com.beeva.banco.BancoBeeva.entity.Cliente;
/**
* @author Armando Duran Salavador
*/
public abstract class ClienteDao {
public abstract Cliente saveCliente(Cliente cliente);
public abstract Cliente removeCLiente(int id);
public abstract Cliente updateCLiente(Cliente cliente);
public abstract Cliente getCliente(int Id);
public abstract List<Cliente> listClientes();
}
|
Swift
|
UTF-8
| 4,526 | 2.96875 | 3 |
[
"MIT"
] |
permissive
|
// Name: Brandon Siebert
// Course: CSC 415
// Semester: Fall 2017
// Instructor: Dr. Pulimood
// Project name: Discuss Action
// Description: iOS application that facilitates active discussion for social justice issues.
// Filename: MainViewController.swift
// Description: Entry point for the application. Controls the main event view list.
// Last modified on: 12/4/2017
import UIKit
class MainViewController: UITableViewController {
// MARK: - Application Properties (WRITTEN BY BRANDON SIEBERT)
let app_delegate = UIApplication.shared.delegate as! AppDelegate
var current_events : [Int] = []
var past_events : [Int] = []
// MARK: - View Controller data source
override func viewDidLoad() {
super.viewDidLoad()
// Count
for (index, event) in app_delegate.Stored_Events.enumerated() {
if event.get_date() == nil {
self.current_events.append(index)
}
else {
print("Comparing: \(event.get_date()!) and \(app_delegate.Current_Date)")
if event.get_date()! > app_delegate.Current_Date {
self.current_events.append(index)
}
else if event.get_date()! < app_delegate.Current_Date {
event.set_stage(stage : 3)
self.past_events.append(index)
}
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func add_topic(_ sender: Any) {
let view_controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Vote")
print("Stage : \(app_delegate.Stored_Events[0].get_stage())")
if app_delegate.Stored_Events[0].get_stage() == 0 {
app_delegate.Selected_Event = app_delegate.Stored_Events[0]
self.present(view_controller, animated: true, completion: nil)
}
}
@IBAction func about(_ sender: Any) {
let view_controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "About")
self.present(view_controller, animated: true, completion: nil)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return self.current_events.count
}
else if section == 1 {
return self.past_events.count
}
else {
return 0
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let view_controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Topic") as! TopicViewController
if indexPath.section == 0 {
view_controller.this_event = app_delegate.Stored_Events[self.current_events[indexPath.row]]
}
else if indexPath.section == 1 {
view_controller.this_event = app_delegate.Stored_Events[self.past_events[indexPath.row]]
}
navigationController?.pushViewController(view_controller, animated: true)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if indexPath.section == 0 {
cell.textLabel?.text = app_delegate.Stored_Events[self.current_events[indexPath.row]].get_topic().get_name()
cell.detailTextLabel?.text = app_delegate.Stored_Events[self.current_events[indexPath.row]].get_topic().get_description()
}
else if indexPath.section == 1 {
cell.textLabel?.text = app_delegate.Stored_Events[self.past_events[indexPath.row]].get_topic().get_name()
cell.detailTextLabel?.text = app_delegate.Stored_Events[self.past_events[indexPath.row]].get_topic().get_description()
}
return cell
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return section == 0 ? "Upcoming" : "Past"
}
}
|
Python
|
UTF-8
| 1,903 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
from .server_handler import ServerHandler
"""
Square Customer Group Object Handler between the Square Client and Squre Online server
"""
class Tournament:
def __init__(self, details):
# Dicitonary object to compensate for overall JSONObject usage
self.details = details
class TournamentHandler(ServerHandler):
# TODO: Create proper variables to perform correct actions based on assignment of APIs in server
CREATE_TOURNAMENT = "/tournament.create_new"
GET_DETAILS = "/tournament.details"
def __init__(self, access_token):
super().__init__(access_token)
self.tournament = None
self.customer_groups = self.square.customer_groups
# Create a new instance of customer with JSONObject
def create_tournament(self, details):
if self.customer_groups.create_customer_group(details).is_success():
self.tournament = Tournament(details)
return self.tournament is not None
#
def register_participant(self, customer_details, tournament_id):
result = False
if self.create_participant(customer_details):
"""
Pseudocode:
- Get the tournament ID from the tournament handler and append it into the customer's group id
- return true the participant is appended.
"""
customer_details['group_ids'] = self.tournament['id']
result = self.customer_groups.search_customers().is_success()
return result
# Get tournament details
def get_details(self):
return self.tournament.details
def generate_bracket(self):
"""
Pseudocode:
- Get the treelib structure used to represent the bracket structure
- From treelib structure, create a JSONObject which FrontEnd has
agreed to
- return true if successful
"""
|
Markdown
|
UTF-8
| 187,876 | 2.609375 | 3 |
[] |
no_license
|
# Debunking the List of Alleged atrocities committed by the US authorities
Correcting the record on US interventions—covert or overt—human rights issues, and more. This project relies on the established documentary record over allegations and sensational headlines. We must not embrace anti-intellectualism for it leads to a world of Idiocracy.
Leave your fallacies at the door. This is also not to defend every single action the US has taken, or suggest the US is perfect. Rather, to critique, one must not rely on misinformation or arguments that cannot hold their own when given even basic scrutiny. Individuals, such as service members, have done crimes—however this is few and far between—rare. Not as a matter of policy, doctrine, SOP, strategy, etc. The US investigates and holds those responsible when evidence warrants, as evidenced below, in this list.
_Definition: An extremely wicked or cruel act, typically one involving physical violence or injury._
_[Legal Definition](https://web.archive.org/web/20200825130159/https://www.un.org/en/genocideprevention/documents/atrocity-crimes/Doc.49_Framework%20of%20Analysis%20for%20Atrocity%20Crimes_EN.pdf): The term “atrocity crimes” refers to three legally defined international crimes: genocide, crimes against humanity and war crimes._
> "Around the world, the United States has promoted freedom: We have worked to expand the protection of human rights, end gender-based violence, and defend the freedoms of expression, peaceful assembly, and the press. In promoting these liberties and pushing back against tyranny, corruption, and oppression, we have recognized that universal human rights and fundamental freedoms do not stop at our borders. They are the birthright of people everywhere." - President Barrack Obama, Presidential Proclamation - Human Rights Day and Human Rights Week, 2016
- On July 12, 2021, the Biden Administration issued its [report](https://www.state.gov/2021-report-to-congress-pursuant-to-section-5-of-the-elie-wiesel-genocide-and-atrocities-prevention-act-of-2018) to Congress Pursuant to Section 5 of the Elie Wiesel Genocide and Atrocities Prevention Act of 2018 (P.L. 115-441). "The Biden Administration is committed to promoting democratic values that underpin a stable international system critical to freedom, prosperity, and peace. This Administration will defend and protect human rights around the world, and recognizes the prevention of atrocities is a core national security interest and a core moral responsibility. This report highlights countries of concern and whole-of-government efforts undertaken by the Atrocity Early Warning Task Force to prevent and respond to atrocities."
## Contents
<!-- toc -->
- [Alleged Imperialism](https://github.com/Factcheck11/US_atrocities_debunked/blob/main/README.md#imperialism)
- [Middle East](https://github.com/Factcheck11/US_atrocities_debunked/blob/main/README.md#middle-east)
- [Western Hemisphere](https://github.com/Factcheck11/US_atrocities_debunked/blob/main/README.md#western-hemisphere)
- [Africa](https://github.com/Factcheck11/US_atrocities_debunked/blob/main/README.md#africa)
- [Europe](https://github.com/Factcheck11/US_atrocities_debunked/blob/main/README.md#europe)
- [Asia](https://github.com/Factcheck11/US_atrocities_debunked/blob/main/README.md#asia)
<!-- tocstop -->
Notes:
- Right-click on a hyperlink to open. Clicking directly will cause the current tab to load the link.
- A clear documentary record advances a public reckoning that enables professional values and judgment to check disinformation and to counter authoritarian, anarchist, and populist movement's contempt for facts.
- Try to convey a sense of understanding of complex matters and history.
Putting aside misinformed, inital moral outrage in order to learn the facts, nuance and details.
- This is a living document, it will be updated as new facts are uncovered and information pours in.
- Due to the passage of time, some things in the list are hard to investigate.
- The list isn't in any specific order. _Generally_ it's in a most to least recent.
- Under international law, incidental (collateral) deaths or injuries of civilians, even in large number, does not indicate nor imply violation of the laws of war.
- When examining primary source records, one must note that they're not all equal. Raw intel cables from Station or an embassy, for example, should not be valued in the same light as finalised intelligence products. For Congressional investigations, keep in mind any disagreement between majority & minority, same for Agency/Department Inspectors General—management comments, Accountability Review Boards, should also be examined if they disagree. Not all Governments are monolithic; not all documents are treated the same.
- [Per the ICC](https://www.icc-cpi.int/resource-library/Documents/UICCEng.pdf), "The International Criminal Court is _not a substitute_ for national courts. According to the Rome Statute, it is the duty of every State to exercise its criminal jurisdiction over those responsible for international crimes. The International Criminal Court _can only intervene where a State is unable or unwilling genuinely to carry out the investigation and prosecute the perpetrators"_
## Imperialism
- It has been alleged that the US maintains an "imperialistic network" of over 800 military bases in 70 countries.
This is misleading and in factual error.
- Site: A specific geographic location that has individual land parcels or facilities assigned to it. Physical (geographic) location that is, or was owned by, leased to, or otherwise under the jurisdiction of a DoD Component on behalf of the United States. A site may be contiguous to another site, but cannot geographically overlap or be within another site. A site may exist in one of three forms: land only– where no facilities are present; facility or facilities only– where there the underlying land is neither owned nor controlled by the government, and land with facilities –where both are present.
- Installation: A military base, camp, post, station, yard, center, homeport facility for any ship, or other activity under the jurisdictionof the Department of Defense, including leased space, that is controlled by, or primarily supports DoD’s activities. An installation may consist of one or more sites.
The DoD has presence on only 45 countries, for a total of only 514 sits as of [2018.](https://www.acq.osd.mil/eie/Downloads/BSI/Base%20Structure%20Report%20FY18.pdf) This is at the full [consent of host countries.](https://www.state.gov/wp-content/uploads/2020/08/TIF-2020-Full-website-view.pdf)
### Middle East
- On June 27, 2021, President Biden, authorised US Military [defensive precision airstrikes](https://www.defense.gov/Newsroom/Releases/Release/Article/2672875/statement-by-the-department-of-defense/) against facilities used by Iran-backed militia groups in the Iraq-Syria border region. The targets were selected because these facilities are utilized by Iran-backed militias that are engaged in unmanned aerial vehicle (UAV) attacks against U.S. personnel and facilities in Iraq. Specifically, the U.S. strikes targeted operational and weapons storage facilities. These strikes were legal under US domestic and international law. 0 civilians were killed.
- On June 3, 2021, the US Department of Defense released its [annual](https://media.defense.gov/2021/Jun/02/2002732834/-1/-1/0/ANNUAL-REPORT-ON-CIVILIAN-CASUALTIES-IN-CONNECTION-WITH-UNITED-STATES-MILITARY-OPERATIONS-IN-2020.PDF) civilian casualty report pursuant to Section 1057 of the 2018 NDAA, as amended.
The report covers Calander Year 2020 for Global Military operations. It assesses that in 2020, US Military operations resulted in 23 civilians killed and 10 injured. The report also updated the Department's previous casualty numbers from prior years. The DoD assessment is based off of all NGO, media, and foreign Government submissions, self-reporting, etc. Its methodology is superior to that of NGOs, as it relies on classified and sensitive methods to determine casualties, including footage before, during, and after each incident. The Department is also transparent in updating prior reporting to increase the numbers, should new credible information be discovered. The new report details the near completion of two independent studies required by Congress.
- On May 1st, 2021, the Biden Administration declassified an [11-page document](https://int.nyt.com/data/documenttools/trump-psp-drone-strike-rules-foia/52f4a4baf5fc54c5/full.pdf) created under the Trump admin, that superseded Obama's policy framework dubbed "the [2013 PPG](https://www.justice.gov/oip/foia-library/procedures_for_approving_direct_action_against_terrorist_targets/download)" that governs Counterterrorism (CT) operations Outside Areas of Active Hostilities. Like the Obama guidance, it keeps intact layered oversight and bureaucracy. Key takeways from the 2017 Principles, Standards, and Procedures for US Direct Action Against Terrorist Targets, or, "PSP" for short, include:
- >The law of armed conflict imposes important constraints on the ways in which the United States uses force abroad.
- >Direct action will be discriminating and precise in order to avoid noncombatant casualties. The United States goes to extraordinary lengths to reduce the likelihood of noncombatant casualties in CT operations, exercising restraint as a matter of policy that often exceeds what is required by LOAC.
- >Direct Action should be undertaken wherever practicable and constistent with US interests and applicable domestic and international law.
- >The United States will continue to take extraordinary measures to ensure with near certainty that noncombatants will not be injured or killed in the course of operations, using all reasonably avillable information and means of verification.
Among many more restrictions and layered oversight for target approval, and general preference for capture rather than kill missions.
- On February 25th, 2021, in his first month in Office, [President Biden approved](https://www.whitehouse.gov/briefing-room/statements-releases/2021/02/27/a-letter-to-the-speaker-of-the-house-and-president-pro-tempore-of-the-senate-consistent-with-the-war-powers-resolution/) airstrikes on lawful infrastructure targets in eastern Syria used by Iran-supported non-state militia groups. These groups were involved in recent attacks against civilians, US and coalition personnel. 0 civilians killed or wounded.
- On January 2nd, 2020, President Donald Trump [authorised a lawful](https://assets.documentcloud.org/documents/6776446/Section-1264-NDAA-Notice.pdf) air strike that killed Qassem Soleimani, leader of the IRGC-Qods Force, a [designated terrorist organisation.](https://www.dni.gov/nctc/ftos.html) "As a matter of International Law, the strike targeting Soleimani in Iraq was taken in United States national self-defense, as recongnized in Article 51 of the United Nations Chater, in response to a series of escalating armed attacks that Iran and Iran-supported militias had already conducted against the United States." For an expert semi-deepdive, I recommend this [read](https://www.lawfareblog.com/was-soleimani-killing-assassination) by two world-leading experts. General Soleimani was actively developing plans to attack American diplomats and service members in Iraq and throughout the region...He had orchestrated attacks...culminating in the death and wounding of additional American and [Iraqi personnel.](https://www.defense.gov/Newsroom/Releases/Release/Article/2049534/statement-by-the-department-of-defense/)" Soleimani is a [well-documented](https://www.wsj.com/amp/articles/the-bloody-legacy-of-qasem-soleimani-11578093506) mass-murderer. His forces are known to rape innocent women on mass and commited many crimes against humanity and war crimes.
- On October 9, 2019, United Nations Mission Afghanistan released a report claiming US forces illegally struck drug facilities, resulting in civilian casualties. This report was [discredited](https://twitter.com/USFOR_A/status/1181831714714337280/photo/1) for citing Jihadi propaganda websites, its deeply flawed legal examination, etc. From the response:
> "United States Forces — Afghanistan (USFOR—A) disputes the findings, legal analysis, and methodology of the UNAMA report released. USFOR—A is concerned by the way UNAMA reached its conclusions and disagrees with their mischaracterization of the Taliban in the methamphetamine production facilities; their reliance on sources with conflicted motives or limited knowledge (including the Taliban propaganda website "Voice of Jihad"); and their narrow definition of legally targetable combatants.
> By the time USFOR—A decided to conduct precision strikes, intelligence and operations professionals knew what the Taliban narcotics production facilities looked like, exactly where they were and who was allowed entry. USFOR—A and partner organizations also knew the pattern–of–life for their operations and locales. Under US legal definitions and rules and policiies governing the conduct of war, and after exhaustive and comprehensive review of the facilities and those running them, USFOR—A and partner entities determined personnel in the labs were members of the Taliban and lawful military targets.
> USFOR—A deliberately chose the targets and the timing for the strikes to avoid non-combatant casualties, striking during the daylight hours to maximize the ability to obtain and share site pictures which ensured we could verify the absence of civilians. On the day of operations, USFOR—A observation of the targeted sites used multiple surveillance platforms, including aircraft with full-motion video gathering capabilities. USFOR—A pre-strike processes included scores of hours of scrutiny of targeted sites to ensure we could verify non-combatants were not present. USFOR—A had degrees of certainty required at the time of the precision strikes to assess forces were only striking legal targets and avoiding non-combatant casualties and collateral damage. USFOR—A even declined to strike nearly a dozen production facilities due to even a slight possibility for civilian casualties.
> The investigations leading to the identification and characterization of these methamphetamine production facilities, their ownership and oversight by the Taliban, the internal rules allowing entry only to Taliban combatants, as well as the flow of funds from these locations to Taliban operations, were combined operations with Afghan security partners. These operations against these Taliban revenue sources were planned and developed over the course of a year, drawing upon the expertise and resources of a wide array of interagency and inter-governmental organizations and relying upon extensive intelligence collection."
- In September 2019, a US drone strike targeted Da'esh terrorists in Nangarha province, according to Colonel Sonny Leggett, a spokesman for U.S. forces in Afghanistan. [Media alleged](https://www.reuters.com/article/us-afghanistan-attack-drones/u-s-drone-strike-kills-30-pine-nut-farm-workers-in-afghanistan-idUSKBN1W40NW) that 30 civilian farm workers were killed in the strike. However, according to the Department of Defense annual report on civilian casualties from US global opeations covering CY19, only [8 civilians were incidentally killed](https://media.defense.gov/2020/May/06/2002295555/-1/-1/1/SEC-1057-CIVILIAN-CASUALTIES-MAY-1-2020.PDF), not 30. Strike was in accordance with international law.
- US Navy SEAL, Eddie Gallagher was alleged to have killed/injured innocent civilians. This [turned out](https://www.navytimes.com/news/your-navy/2019/06/21/legal-bombshell-explodes-on-seal-war-crimes-trial/) to be a lie from his junior SEALs. Subsequently, Gallagher was [acquited](https://www.documentcloud.org/documents/20476626-complete_gallagher_files_ocr) of all charges, but found guilty of one crime he never challenged: Posing for a photo with a body—something his SEAL colleagues also did, however, due to their immunities, they weren't charged. A complete breakdown of the back history, pre-trial can be found [here.](https://youtu.be/qFe-n4Eu6Mw)
- [On April 13, 2018](https://www.justice.gov/olc/opinion/file/1067551/download), in coordination with the United Kingdom and France, the United States attacked three facilities associated with Syria’s use of chemical weapons: the Barzeh Research and Development Center, the Him Shinshar chemical-weapons storage facility, and the Him Shinshar chemical-weapons bunker facility. There have been [many](https://dod.defense.gov/portals/1/features/2018/0418_syria/img/timeline.pdf) instances of the Syrian regime using these illegal weapons on innocent civilians, which is, of course, a war crime. [No civilians](https://www.defense.gov/Newsroom/Transcripts/Transcript/Article/1493658/briefing-by-secretarymattis-on-us-strikes-in-syria/) were killed or injured as a result of the US/UK/France attacks—as great care was taken to avoid them. Russia has [enabled]( https://harvardnsj.org/wp-content/uploads/sites/13/2018/01/5_Lawless_StateofComplicity-1.pdf) the war crimes committed by the Syrian regime, and has also [commited](https://www.nytimes.com/2019/10/13/world/middleeast/russia-bombing-syrian-hospitals.html) many themselves. Because Russia is allied with such a thuggish rogue state, and has committed hanious acts themselves, they must [deny](https://www.bellingcat.com/news/mena/2014/08/20/attempts-to-blame-the-syrian-opposition-for-the-august-21st-sarin-attacks-continue-one-year-on/), [lie](https://www.bellingcat.com/news/mena/2017/11/13/russia-accidentally-provide-best-evidence-syrian-governments-involvement-sarin-attacks/) and spin truth. Just as they did for their deliberate attack on civilian airline, [MH17](https://www.bellingcat.com/news/uk-and-europe/2020/11/12/the-grus-mh17-disinformation-operations-part-1-the-bonanza-media-project/) more than [once](https://www.documentcloud.org/documents/4334396-2016-2017-ISC-AR.html) Russia has acted as a disinfo mill: Creating lies and spreading them far and wide. Through their proxy—wikileaks—Russia has spread fake news concerning a "whistleblower" in the OPCW via the leak of emails. That headline is enough to [convince](https://github.com/dessalines/essays/blob/master/us_atrocities.md) some to believe Syria is innocent, simply because they don't want to spend the time to fact-check. Suffice to say, the disinformation has been covered, and debunked by the [OPCW](https://www.opcw.org/media-centre/news/2020/02/opcw-independent-investigation-possible-breaches-confidentiality-report), [Bellingcat](https://www.bellingcat.com/news/mena/2020/01/15/the-opcw-douma-leaks-part-1-we-need-to-talk-about-alex/), and many others—including a sufficient skill at [reading comprehension.](https://www.bellingcat.com/news/2019/11/25/emails-and-reading-comprehension-opcw-douma-coverage-misses-crucial-facts/) To quote from the OPCW, "Inspector A, he was not a member of the FFM. As described by the investigators, Inspector A played a minor supporting role in the investigation of the Douma incident, and he did not have access to all of the information gathered by the FFM team, including witness interviews, laboratory results, and analyses by independent experts. Although Inspector A’s assessment purports to be an official OPCW FFM report on the Douma incident, it is instead a personal document created with incomplete information and without authorisation."
- Starting in [June 2017](https://www.snopes.com/news/2017/06/12/u-s-led-forces-accused-using-white-phosphorus-syria-iraq/), photos and videos from Raqqa, Syria claiming to have shown alleged US-backed groups "illegally" using white phosphorus. While it's hard to say who was deplying it—mere use of WP is not a war crime. U.S. Army Colonel Ryan Dillon told the Washington Post that the U.S. military only uses white phosphorus in “accordance with the law of armed conflict” – for example “for screening, obscuring and marking in a way that fully considers the possible incidental effects on civilians and civilian structures.”
Other Coalition forces have used WP in this manner before, in other countries: Talking to NPR, New Zealand Brig. Gen. Hugh McAslan said, "We have utilized white phosphorus to screen areas within west Mosul to get civilians out safely."
For an expert breakdown of the legality of WP, this [scholarly paper](https://www.loc.gov/rr/frd/Military_Law/pdf/08-2006.pdf) provides a fantastic breakdown, as does this [entry](https://www.lawfareblog.com/jus-bello-white-phosphorus-getting-law-correct) by another expert.
- From Janurary 2015 to December 2017, US air and artillery strikes conducted in Iraq & Syria, monthly, often resulted in 0 civilian casualties. Most peaks never breached 20 CIVCAS. All of these strikes were conducted in full compliance of domestic and international law, and other applicable governing authorities—according to an [independent study](https://www.documentcloud.org/documents/7048479-2018-Civilian-Casualty-Military-Study.html). The peak from March 17 2017 came from a single airstrike that [accidently killed](https://www3.centcom.mil/foialibrary/cases/17-0341/1._ar_15_6_investigation__part_1___a__clear.pdf) just-under 112 civilians. Unknown to Iraq & US forces, ISIS was holding onto civilian hostages. Also unknown to Iraq and US forces was the presence of additional explosives that resulted in a secondary explosives.
- On April 6, 2017, following the illegal [Khan Sheykkun chemical attack](https://www.securitycouncilreport.org/atf/cf/%7B65BFCF9B-6D27-4E9C-8CD3-CF6E4FF96FF9%7D/s_2017_904.pdf) [by the Syrian regime](https://www.diplomatie.gouv.fr/IMG/pdf/170425_-_evaluation_nationale_-_anglais_-_final_cle0dbf47-1.pdf), the United States carried out [lawful strikes](https://jnslp.com/wp-content/uploads/2018/01/Assessing_US_Justifications_for_Using-Force_2.pdf) against Al Shayrat airfield, used by the regime to conduct its illegal chemical & conventional weapons attacks against civilians.
- A [study](https://www.lawfareblog.com/should-us-military-receive-benefit-doubt-when-investigating-itself-alleged-war-crimes) by two world-leading experts concerning Iraq and Afghanistan US operations concludes, "We analyzed two sets of data dealing with these wars: the first, from the Naval Criminal Investigative Service (NCIS), details all founded investigations alleging serious law of armed conflict violations in Iraq and Afghanistan by Sailors, SEALs, and Marines; the second, from the Army Court of Criminal Appeals (ACCA), details all cases of alleged serious law of armed conflict violations by soldiers referred to court-martial. The NCIS data indicates that ninety-two allegations of serious law of armed conflict violations were substantiated, thirty-seven of which led to courts-martial (a number of others received non-judicial punishment), and twenty-eight of which resulted in conviction. The ACCA data shows 100 referred cases, of which seventy-eight resulted in conviction on at least one offense. Many of these cases resulted in substantial sentences, including life imprisonment."
- On March 17 2017, a US airstrike [accidently killed](https://www3.centcom.mil/foialibrary/cases/17-0341/1._ar_15_6_investigation__part_1___a__clear.pdf) 112 civilians in Mosul. Again, Unknown to Iraq & US forces, ISIS was holding onto civilian hostages. Also, unknown to Iraq and US forces was the presence of additional munitions that resulted in a secondary explosives effect. Again, targeteering, and other CIVCAS mitigation efforts were all present to avoid civilians and collateral damage to the surrounding buildings. Forensic analysis confirms it was the secondary explosives that ISIS owned, that caused the civilian deaths.
- A 2017 [report](https://www.sigar.mil/pdf/inspections/SIGAR%2017-47-IP.pdf), requested by Congress, examined between FY 2011–16, finds that the US investigated all allegations of human rights abuses committed by Afghan forces, including child abuse reports made externally and internally, as best they could and cut off aid to those units implicated. Convictions were landed on those who committed the crimes. The report does find some issues, and the agencies involved have their comments at the end. There wasn't a consolidated process, and as US forces drew down—they lacked the insights they once had into abuse allegations.
>"SIGAR found no evidence that U.S. forces were told to ignore human rights abuses or child sexual assault."
>"Following the establishment of the State and Defense Leahy Vetting Procedures for the Afghan National Security Forces in July 2014, and a biweekly joint DOD and State Afghanistan Gross Violation of Human Rights Forum (Leahy Forum), the Office of the Under Secretary of Defense for Policy (OUSD-P) began to track gross violation of human rights incidents—including child sexual assault—that were reported to and considered by the Leahy Forum. According to data provided by OUSD-P, as of August 12, 2016, the office was tracking 75 reported gross violation of human rights incidents. Of these reported incidents, 7 involved child sexual assault, 46 involved other gross violations of human rights, and 22 were classified at a level above Secret because of the sensitivity of the information or the sources and methods used to obtain the information. These incidents ranged in date from 2010 through 2016, and included gross violations of human rights allegedly committed by Afghan security forces within the MOD and MOI. The incidents reported to and considered by the Leahy Forum came from a variety of sources including intelligence reports, news articles, U.S. forces, and the Afghan government."
>"Of the 75 reported incidents in the OUSD-P tracker, 7 involved allegations of child sexual assault—1 that the Leahy Forum found to be credible, 5 that remain under review, and 1 that was found not credible. Fiveof the seven involved MOI units, and two involved MOD units. The one credible incident was reported by the Afghan government. In this instance, the government reported that two ANA Special Operations Command (ANASOC) noncommissioned officers (NCOs) attempted to sexually assault a girl to coerce information from hermother. Following a trial, both NCOs were indicted and convicted for attempted sexual assault of a minor in violation of the penal code and sentenced to 6 years of confinement. Based on the information the Afghan government provided, DOD determined that it had credible information of a gross violation of human rights and began the process to remediate the unit."
Also details improvements made on the Afghan side including legislative, as well as other high-level efforts by the US Government working with the Afghans.
It found no evidence, as NGOs/media alleged, that US forces were told to ignore child sex abuse/other human rights abuses.
- On 28 Janurary 2017, President Trump authorised a Special Operations raid in al-Bayda, Yemen. The raid was successful, though tragic, in its collection highly important information. Media and NGOs claimed that during the raid, a firefight killed as many as 30 or more civilians. This however, was a hoax. According to declassified documents obtained by the ACLU, show that high resolution footage (covering many Points of View), and sensitive intelligence, confirm between [4-12](https://www.aclu.org/sites/default/files/field_document/uscentcomfoia17-0328l_ocr_0.pdf) civilian casualties. [Women also participated](https://s3.documentcloud.org/documents/5553400/Attachment-4-SOCOM-ARR-YEMEN-2.pdf) in the fight. Classified documents also obtained by the ACLU show the mission was authorised because it satisified the [NCV 0](https://www.aclu.org/sites/default/files/field_document/17-L-0705JS022.pdf) policy. That is, if there was even the possibility that just one CIVCAS was possible, the mission could not be approved.
- From 2015 to 2020, the US had been [aiding](https://www.documentcloud.org/documents/4390794-Acting-GC-Letter-to-Majority-Leader-Re-Sanders.html) the Saudi-led coalition in mid-air refueling (outside Yemen airspace), International Humanitarian Law compliance, and limited intelligence sharing to help further mitigate impact to civilians. US & British Governments have worked well to train, advice and develop Saudi Arabia's international law compliance, according to a UK High Court [ruling](https://www.judiciary.uk/wp-content/uploads/2017/07/r-oao-campaign-against-arms-trade-v-ssfit-and-others1.pdf).
The [Kingdom](https://www.ksrelief.org/Pages/Partners/), [US](https://www.usaid.gov/news-information/press-releases/may-6-2020-united-states-announces-additional-humanitarian-aid-people-yemen), [UK](https://devtracker.fcdo.gov.uk/countries/YE), and many other countries pour in humanitarian aid as they work with the Yemen Government to fight off Iran-backed terrorist orgs.
- In 2011, President Obama authorised the [lawful, Constitutional](https://www.justice.gov/sites/default/files/olc/pages/attachments/2015/04/02/2010-07-16_-_olc_aaga_barron_-_al-aulaqi.pdf) strike on a [senior al-Qa'ida member](https://www.aclu.org/sites/default/files/field_document/107-3._panetta_declaration_6.10.2015_0.pdf), Anwar al-awlaki was the Chief of external operations. He was responsible for the planning and execution of terrorist attacks against the US and allied nations. He was most infamous for his pivotal role in AQAP's attempt to blow up a US airliner, bound for Detroit on December 25, 2009. The Government's [preferance was to capture him](https://fas.org/irp/eprint/doj-lethal.pdf), but it was not feasible—and was deemed continuing to be an imminent threat.
His son was killed in this strike, but was not made the target. In Janurary 2017, Trump approved a Special Forces raid in Yemen. Media alleged that among the [4-12 civilians killed](https://www.aclu.org/sites/default/files/field_document/uscentcomfoia17-0328l_ocr_0.pdf) (not 30 as media/NGOs claim), was Anwar's 8 year old daughter. However, declassified documents from ACLU litigation have confirmed no children were killed. [Women were among the combatants](https://www.documentcloud.org/documents/5553400-Attachment-4-SOCOM-ARR-YEMEN-2.html#document/p1).
- In 2016, Obama released, per EO 13732 Sec. 3, data concerning High Value Target CT missions Outside Areas of Active Hostilities.
[The first](https://www.dni.gov/files/documents/Newsroom/Press%20Releases/DNI+Release+on+CT+Strikes+Outside+Areas+of+Active+Hostilities.PDF) report covers from Jan 2009 to Dec 2015. It shows that there was a total of 473 strikes with a total of between 2372-2581 combatants killed and only between 64-117 civilians killed. Following this, the [2016](https://www.dni.gov/files/documents/Newsroom/Summary-of-2016-Information-Regarding-United-States-Counterterrorism-Strikes-Outside-Areas-of-Active-Hostilities.pdf) report was issued, giving us: 53 total strikes. With 431-441 combatants killed and only 1 civilian killed. Both records make clear to refute the allegations that any "military-aged male" in area of target is deemed a combatant. To quote, "Males of military age may be non-combatants; it is not the case that all military-aged males in the vicinity of a target are deemed to be combatants."
For an overview of the domestic, international law and policy frameworks that guide US Military operations, especially as they relate to Syria, Yemen, Afghanistan, Libya and Somalia: See this [compendium](https://obamawhitehouse.archives.gov/sites/whitehouse.gov/files/documents/Legal_Policy_Report.pdf) provided in 2016 by the Obama administration.
- US involvement in Syria has concerned AQ and ISIS, since the regime has been either unwilling or unable to address the threat they pose to allied countries, such as the US. These nations are [allowed](https://lawfareblog.com/who-board-unwilling-or-unable) this right under [international law and a moral obligation to address these threats](https://go.galegroup.com/ps/anonymous?id=GALE%7CA484155766&sid=googleScholar&v=2.1&it=r&linkaccess=abs&issn=00948381&p=AONE&sw=w).
US aid to SDF and other groups are only [allowed](https://assets.documentcloud.org/documents/3032777/DOD-Section-1209-Report-Assistance-to-VSO-Mar.pdf) if they do not engage in [human rights abuses](https://assets.documentcloud.org/documents/3032778/Section-1209-Report-Department-of-Defense.pdf) and [not connected to terrorism](https://assets.documentcloud.org/documents/3525400/FOIA-Final-Response-2015-00974.pdf).
- In 2011, Dictator and criminal, Muammar Gaddafi, due to peaceful protests caused by the Arab Spring started to slaughter innocent, paceful civilians with [lethal force](https://www.securitycouncilreport.org/atf/cf/%7B65BFCF9B-6D27-4E9C-8CD3-CF6E4FF96FF9%7D/Libya%20S%20PV%206528.pdf). For months he threatened to slaughter civilians—to the international communities warnings to not follow through. He did. Sending his forces out. Under UNSC Resolution 1973, a [no-fly zone](https://ssi.armywarcollege.edu/2013/pubs/the-north-atlantic-treaty-organization-and-libya-reviewing-operation-unified-protector/) was established. This [resolution](https://www.semanticscholar.org/paper/Wings-Over-Libya%3A-The-No-Fly-Zone-in-Legal-Schmitt/822ce0de5bb2451fe0ab967436b555111a156ee8) also provided member states to use [all neccisary means](https://www.justice.gov/sites/default/files/olc/opinions/2011/04/31/authority-military-use-in-libya_0.pdf) to [enforce compliance](https://www.documentcloud.org/documents/204673-united-states-activities-in-libya-6-15-11.html). The intervention by the international community was seen as [popular](http://news.gallup.com/poll/156539/opinion-briefing-libyans-eye-new-relations-west.aspx) by Libyans. The [United States](https://www.wilsoncenter.org/article/us-assistance-to-egypt-tunisia-and-libya) and the international community has since been [addressing](https://ly.usembassy.gov/the-us-commits-6-million-usd-in-humanitarian-assistance-to-libya-for-the-covid-19-response/) matters [since](https://fas.org/sgp/crs/row/RL33142.pdf) then.
Gaddafi was also a lover of brutish assassins to kill off dissedents, journalists, human rights activits and even attempts on heads of state and soon-to-be-rulers of Kingdoms. Thanks to the NSA, with new authorities granted under the Patriot Act, and other traditional SIGINT and hard work, and made public thanks to Snowden—we can see just one such assassination plot was [thwarted](https://www.documentcloud.org/documents/4389688-The-Saudi-Assassination-Plot-How-It-Was-Thwarted.html). What was the crime? A perceived insult. "This wealth of information tied the plot directly to Libyan leader Mu'ammar Qhadafi."
- From 2001 up to the present day, the drone campaign has resulted in disrupting many terrorist networks, and resulted in very few civilian casualties. Chair of the Senate Intelligence Committee during the confirmation hearing for John Brennan, confirmed as a result of Congressional oversight, that the civilian deaths per year as a result of drone strikes is often in the [single digits](https://www.intelligence.senate.gov/sites/default/files/hearings/11331.pdf). Lethal strikes are only sought if [capture of HVTs is not feasible](https://www.justice.gov/oip/foia-library/procedures_for_approving_direct_action_against_terrorist_targets/download). Leaked documents from the Intercept confirm that these missions (including ground raids) result in very few civilian casualties. From September 16, 2011 to September 16, 2012 in Afghanistan, out of a total of 2,082 missions only 14 civilians were killed or injured. That's 0.67%. Media have incorrectly claimed that these documents show a 90% civilian casualty rate from drone strikes. They neither are specific about drones nor, as shown, have a 90% percentile—only a 0.67%.
Another document leaked confirms the time and care taken into approving each strike. Missions can only be approved by POTUS if the host nation consents. See [slide 6](https://www.documentcloud.org/documents/2460856-small-footprint-operations-may-2013.html) and [slides 41 and 42](https://www.documentcloud.org/documents/2460855-small-footprint-operations-february-2013.html).
From these, a picture starts to emerge:
- The “average approval time” for a proposed strike under the AUMF process was 79 days. Even excluding the single longest approval, presumably an unrepresentative outlier, the average was 58 days. The fastest approval was 27 days.
- These approvals were preceded by lengthy periods of gathering and analyzing intelligence on the targets—an average of six years.
- Four out of 24 proposed concepts of operations covered by the study were disapproved under the AUMF review process.
- The process for approving strikes under the AUMF “requires significant intel/ISR to justify (and maintain) approvals.” “Relatively few, high-level terrorists meet criteria for targeting” under this process. (Note that this isn’t a press release touting the program’s robust oversight; it’s an internal DOD assessment, written from the perspective of operators for whom a laborious approval process is an obstacle rather than a virtue.)
- These “[p]olitical constraints” make these operations “challenging” and “fundamentally different from what we’ve experienced in Afghanistan and Iraq.”
- On 3 October, 2015, a United States Air Force AC-130U accidently missidentified the Kunduz Trauma Centre, operated by Doctors without Borders. Per an [independent investigation](https://s3.documentcloud.org/documents/2819730/RESPONSIVE-DOCUMENTS.pdf), "The ground force and aircrew were unaware theaircrew was firing on a hospital throughout the course of the engagement." This was caused due to technical and human error. "Due to the early launch, the aircrew did not have the typical information it would have on a mission. While enroute to Kunduz, one of the aircraft's critical communications systems failed, resulting in the aircraft's inability to recieve and transmit certain critical information to multiple command headquaters." While tragic—this is not a war crime. While hospitals are indeed protected buildings under international law, there are caveats: 1. A building can lose its protected status. 2. A building can become [duel-status](https://www.afjag.af.mil/Portals/77/documents/AFD-081009-011.pdf), see page 84 of this scholarly paper—and yet, it's a [real thing, see page 6 of this investigation](https://archive.org/details/informal-ar-15-6-investigation-findings-and-recommendations-for-the-al-hawijah), not just in academic theory. If part of the building is used by combatants while the rest by civilians, only that area may be targeted. 3. An accident. Since the tribunals of WW2, there has been a principle formed known as the Rendulic standard. To quote from the [2020 updated Operational Law Handbook](https://www.loc.gov/rr/frd/Military_Law/pdf/operational-law-handbook_2020.pdf), "The “Rendulic Rule:” The Rendulic case also stands for a broader standard regarding liability for battlefield acts: commanders and personnel should be evaluated based on information reasonably available at the time of decision...There may be situations where, because of incomplete intelligence or the failure of the enemy to abide by the LOAC, civilian casualties occur. Example: The Iraqi Al Firdos C3 Bunker. During the first Persian Gulf War (1991), U.S. military planners identified this Baghdad bunker as an Iraqi military command and control center. Barbed wire surrounded the complex, it was camouflaged, armed sentries guarded its entrance and exit points, and electronic intelligence identified its activation. Unknown to coalition planners, some Iraqi civilians used upper levels of the facility as nighttime sleeping quarters. The bunker was bombed, resulting in over 400 civilian deaths. Was there a violation of the LOAC? Not by U.S. forces, but there was a clear violation of the principle of distinction (discussed infra) by Iraqi forces. Based upon information gathered by Coalition planners, the commander made an assessment that the target was a military objective. Although the attack may have resulted in unfortunate civilian deaths, there was no LOAC violation because the attackers acted in good faith based upon the information reasonably available at the time the decision to attack was made."
- In 2014, Congress created a new authority for the Department of Defense (DOD) to train and equip select Syrians in the FY2015 National Defense Authorization Act (NDAA, Section 1209 of P.L. 113-291, as amended). This authority, as amended by subsequent legislation, enables DOD “to provide assistance, including training, equipment, supplies, stipends, construction of training and associated facilities, and sustainment, to appropriately vetted elements of the Syrian opposition and other appropriately vetted Syrian groups and individuals.” Such assistance activities are authorized for select purposes, including supporting U.S. efforts to combat the Islamic State and other terrorist organizations in Syria and promoting the conditions for a negotiated settlement to Syria’s civil war.[1](https://fas.org/sgp/crs/mideast/RL33487.pdf) These groups are vetted to make sure they're in compliance with international law regarding use of force, detention operations, etc. Per the [Leahy law](https://www.state.gov/wp-content/uploads/2020/06/PP410_INVEST_v2.1.pdf), the US Government is prohibited from using funds for assistance to units of foreign security forces where there is credible information implicating that unit in the commission of gross violations of human rights (GVHR). The training is not limited to military activity, but mandatorily includes promoting and educating the respect for the rule of law and human rights. An independent [audit](https://media.defense.gov/2019/Aug/22/2002174036/-1/-1/1/DODIG-2015-175.PDF) conducted by the DoD's internal watchdog, confirms that the vetting procedures designed to identify derogatory information that would keep an individual from participating in the Syrian Training and Equipment program meet and satisified the criteria established under the 2015 NDAA. It also provided some recommendations to further strengthen the effort.
- On November 25, 2010 media alleged, that, according to local sources: US Navy SEALs and Special Forces killed 6 civilians in Shah Wali Khot, having them tied back to back then burned them alive. The allegation was independently [investigated](https://www3.centcom.mil/FOIA_RR_Files/5%20USC%20552(a)(2)(D)Records/Shah%20Wali%20Kot%20Afghanistan%20Investigation%202010/Shah%20Wali%20Kot,%20Afghanistan%20Investigation%202010.pdf), and found to be a Taliban hoax. The District govenor also confirmed this—and his testimony was independently verified by HUMINT reporting, as well as by other Village elders.
- In 2010, Chelsea Manning leaked what became known as the 'Iraq war logs', however, it's worth noting that the vast maority of these leaks are in plain-text format. So while the [damaged caused was great](https://www.documentcloud.org/documents/3933088-Department-of-Defense-Final-Report-of-the.html)—the actual things that matter, to the concerned activity/member of public is the CIVCAS numbers. Sadly, no one is able to independently verify and confirm the plain-text files are accurate. Even worse, some stories don't even cite to the plain-text files on wikileaks site.
- 12 February 2010 in Gardez District, Paktia Province, Afghanistan, news reports had claimed US Special Forces deliberately killed a pregnant woman, and covering it up. An independent investigation was ordered to answer two principle questions:
- 1) Did the ground force deliberately mislead its higher headquaters in initial reports regarding this incident?
- 2) Did the ground force attempt to hide the circumstances surrounding the casualties by alterng, tampering with, and/or cleaning up the incident scene?
The investigation [concludes](https://www.documentcloud.org/documents/2849845-Gardez-FOIA.html) that the answer to both of these questions is "No" and recommends no disciplinary action against the assault force members. The facts gathered in this investigation indicate that ground forces were unaware that the famles were killed when they engaged Mohad Zahir after he emerged from a building in the compound with an AK-47 pointed at the assault force on the roof.
- In 4 May 2009, Bala Balouk District, Farah Province, Afghanistan—The Special Operations Marines (MARSOC) & Afghan SF units called in CAS with (4) F/A-18F strikes. Another (3) strikes were called in for a B-1B Bomber. Civilian casualties resulted because of the complex environment: "The use of military force in this engagement with the Taliban was an appropriate means to destroy that enemy threat within the requirements of the Law of Armed Conflict (LOAC). However, the inability to discern the presence of civilians and avoid and/or minimize accompanying collateral damage resulted in the unintended consequence of civilian casualties. Throughout the conduct of this operation, the Ground Force Commander' s (GFC) ability to break contact was hampered by the effects of direct fire contact with a significant enemy force, a lengthy effort to medically evacuate (MEDEVAC) U.S. and Afghan critically injured personnel by helicopter, and persistent, real-time intelligence on the enemy's continuing efforts to maneuver, mass, re-arm, and re-attack friendly forces from within the village. The independent [investigation](https://www.hsdl.org/?view&did=35748) concluded that the Laws of Armed Conflict were followed. At least 26 civilians were killed. Around 78 Taliban were killed.
- On 22 August, 2008, US Close Air Support killed 33 civilians in Azizabad, Afghanistan. US MARSOC and Afghan Special Forces executed a kill/capture of a High Value Target. After successful infiltration, the Afghan/US team recieved hostile force engagement. They requested CAS. Unknown to both US & Afghan forces, the hostile engagement positions were in close proximity to civilians. Allegations that the US/Afghan forces committed violations of the Rules of Engagemen or Law of War during the 21-22 August 2008 firefight resulting in 90 civilian deaths are [unsubstantiated](https://archive.org/details/Azizabad-august-2008-MARSOC/mode/2up). The first investigation concluded there was 6 civilians killed. Subsequent to new information provided by UNAMA, ICRC, etc, the US conducted another, more comprehensive investigation. It found that there were 33 CIVCAS and 22 anti-coalition millitants died. The independent investigation 28 interviews resulting in more than 20 hours of recorded testimony from Afghan government officials, Afghan village elders, officials from IGOs/NGOs, US and Afghan service members, 236 documents and 11 videos. It also found villager statements heavily inconsistent, and other severe methodological flaws by the NGOs and UNAMA. The second investigation also incorporated FBI forensic teams to aid its efforts.
- Between 2004 and 2007, only [568 civilians](https://www3.centcom.mil/FOIA_RR_Files/5%20USC%20552(a)(2)(D)Records/Incidents%20Reports%20or%20Actual%20Civilian%20Deaths%20in%20Iraq/r_TAB%20C%20EOF%20Incidents%20SIGACTS%2005%20Bracketed.pdf) were killed or injured as a result of US forces in Iraq.
- [4 March, 2007](https://htv-prod-media.s3.amazonaws.com/files/galvin-pentagon-report-1549974003.pdf), Nangarhar Pronvince, Afghanistan, a MSOC-F (a unit of MARSOC, Marine Special Operations Command), "convoy was subject to a complex ambush. Small arms fire, and a Suicide Vehicle Borne Improvised Explosive Device approached the convoy at a righ rate o speed and detonated. The convoy defended agaisnt additional near-simultaneous attacks, quickly regrouped, and resumed movement west on Highway A1 using authorised procedures to dispurse the crowds and unblock the road to allowing the convoy to continue its westward route. Within 30 minute of the blast, and the convoy's return to base, internet media reports began surfacing indicating that a colaition convoy had opened fir on civilians, killing and wounding many. An Air Force Colonel was apointed to conduct an investigation into the facts surrounding the incident. The Colonel ignored statements by those in the convoy, ignored EOD specialists, and placed too much at face valueon alleged witness testimony.
Another investigation was appointed, a formal Court of Inquiry (COI) to independently determine the facts and circumstances relative to the actions of MSOC-F. After hundreds of interviews, a complete examination of the documentary evidence, the COI found the statements and testimony of the personnel in the MSOC-F convoy to be consistent, truthful, and credible. The COI found that MSOC-F Marines defended appropriately and proportionately against the 4 March 2007 enemy ambush, and that a non-governmental organization employee's unbiased testimony independently corroborated the testimony of the MSOC-F personnel. The COI opined that the findings and conclusions found in Col P's investigation run counter to the weight of the evidence considered by the Court. Additionally, Col P never interviewed the Reconnaisance Operations Center (ROC) Watch Officer on duty, nor did he review the ROC log to determine the sequence of events on 4 March to determine exactly what was reported and to whom it was reported. Based on his conclusion that the use of force applied by the personnel in the convoy was excessive, Col P recommened various personnel in the MSOC-F convoy be charged. Col P's investigation was discredited and the magnitude of his errors cannoted be overstated. Col P was in possession of overwhelmingly clear evidence that MSOC-F was ambushed and responded in a discriminate and effective manner. Col P. supressed exculpating evidence and inexplicicably accepted the testimony of Afghans he stopped, apparently randomly, and questioned, making no effort to ascertain the location of the Afghans on 4 Mach 2007 and making no effort to corroborate their statements. Col P did not examine key locations, did not interview any of the Afghans allegedly injured by the Marines, and did not examine the ammunition logs."
- On September 16, 2007, members of Blackwater who were protecting a VIP were rushed into evacuating the VIP after a bomb went off outside the venue they were at. Spooked, the security detail rushed out of the area. Coming to a square, in the high-tensions of what had happened, accidently engaged several civilians. The real issue comes after this occured. The team tried to cover themsleves by replacing parts of the vehicle with one already damaged, to bolster their mistake to the FBI. [They were found out](https://edition.cnn.com/2020/12/24/opinions/blackwater-defendants-pardon-trump-opinion-oconnor/index.html). Arrested, charged and convicted.
- On August 19, 2007, an article from the Washington Post claimed soldiers committed LOAC violations in what is dubbed as "The Battle of Donkey Island".
The allegation claimed the US Soldiers shot and killed injured insurgents. The independent [investigation](https://www3.centcom.mil/FOIALibrary/cases/00-0001/r_14%20OCT%2007%20VIOL%20OF%20LAWS%20OF%20ARMED%20CONFLICT.pdf) finds the article, while compelling, suffers numerious inaccuracies, that, while don't appear to be intentional by the author, was due to incomplete, contradictory information, and general confusion. Seperately, the investigation finds it likely that noncombatants were killed. But could not determine by who.
- On July 12, 2007, a US Apache helicopter was providing force protection to Bravo Company 2-16. The Company had been in near continious contact from insurgents since dawn. The Apache spotted a group of armed men heading in the direction of Bravo Company. The Apache kept its eye on the group until one person peaked around a corner, knelt, and shouldered what appeared to be an RPG. Indeed, the leaked footage from wikileaks confirms this. After the Apache cleared the building, it was cleared to engage the insurgents. After the dust settled: Unknown to the Apache crew, all but two people turned out to be insurgents—they were two journalists with Reuters. It must be highlighted that these two journalists were not wearing the standard 'press' or 'media' vests, nor did they tell the military they'd be present in an area that had seen fighting for days on end. Among the bodies, there were RPGs, AKMs, and other weapons. There was [no violation of the Laws of War, Rules of Enagement](https://www.documentcloud.org/documents/1506533-30-2nd-brigade-combat-team-15-6-investigation-pdf.html), etc.
The leaker of the footage, and many other records that [put innocent civilians at risk](https://www.documentcloud.org/documents/3933088-Department-of-Defense-Final-Report-of-the.html) was charged and convicted for a [number of crimes](https://web.archive.org/web/20190304152646/https://www.jagcnet.army.mil/Apps/ACCAOpinions/ACCAOpinions.nsf/ODD/818BA3ADDACC08A28525829E0060B9B1/$FILE/oc-manning,%20be.pdf)
- On March 15, 2006, between 3-9 civilians were killed in a raid on a building that was later destroyed. According to an [independent investigation](https://www.nytimes.com/2006/06/04/world/africa/04iht-raid.1880380.html), "Allegations that the troops executed a family living in this safe house, and then hid the alleged crimes by directing an airstrike, are absolutely false, the raid's ground commander had adhered to the rules of engagement."
- On November 19, 2005, in Haditha, Iraq: a patrol from Company K, 3d Battalion, 1st Marines (3/1), mounted in High Mobility Multi-purpose Wheeled Vehicles(HMMWVs), was struck by an IED and recieved some small arms fire near the intersection of Routes Chestnut and Viper in Haditha, Iraq. The patrol suffered one FKIA and two FWIA as a result of the IED attack. During actions taken by the patrol in response to the attack, at least 24 Iraqi civilians were killed near the IED site.
Following standard procedures of condolnce payments sent to family of victims, reporting came in containing allegations of deliberate and wrongful killings by the Marines. On 14 Februrary 2006, the MNC-1 Commander directed Colonel G.A. Watt to conduct an AR 15-6 investigation into the incident. The investigation concluded that there had been no intentional targeting of noncombatants; that overall, throughout the entire engagement, Marines had attempted to distinguish combatants from noncombatants; that the force used was proportional, and that the Marines provided adequate medical care to non-coalition force casualties. His investigation concluded that the insurgents had violated the LOAC essentially by using homes occupied by noncombatants to attack the Marines. Colonel Watt, however, did conclude that Marines had failed to comply with the ROE in that they had failed to postively identify (PID) tagets as legitimate before engaging, resulting in the death of noncombatants. As a result, Colonel Watt recommended further investigation by the Criminal Investigations Division (CID) or NCIS.
NCIS investigated this matter and found some evidence that two individuals talked to each other about fabricating their accounts of the incident. However, a new, authoritative, final review known as the [Chiarelli report](https://www.mcmilitarylaw.com/documents/000_mg_bargewell_15-6__haditha_report_.bates.pdf) was established and found, even with the additional evidence provided by NCIS, " as noted, NCIS did uncover evidence that certain squad members coordinated false stories on specific aspects of the incident; however, the preponderance of the evidence shows that the overall deficiencies in reporting and follow-on action—while somtimes perplexing—were not the result of an extensive and orchestrated criminal cover-up throughout the chain of command."
An Investigating Officer [report](https://www.washingtonpost.com/wp-srv/world/specials/iraq/documents/SharrattReport070607.pdf), examined all evidence presented at an Article 32 hearing, and independently concluded Marines acted in accordance with ROEs, specifically LCpl Sharratt.
- In 2004, allegations of unauthorised detainee abuse poured in from the media, concerning Abu Ghraib. These are not to be confused with the [lawful](https://www.aclu.org/files/torturefoia/released/082409/olcremand/2004olc164.pdf)[*](https://www.aclu.org/sites/default/files/torturefoia/released/082409/olc/2007%20OLC%20opinion%20on%20Interrogation%20Techniques.pdf), [effective](https://www.documentcloud.org/documents/1377197-ssci-minorityviews.html) means of gaining actionable intelligence by the CIA's [Enhanced Interrogation Techniques](https://archive.org/details/RDI-Brief). By [mid-2004, 155 investigations](https://www.globalsecurity.org/military/library/report/2004/d20040824finalreport.pdf) into detainee abuse allegations had been completed, resulting in 66 substantiated cases.
- On November 8, 2009, an [investigation](https://www.esd.whs.mil/Portals/54/Documents/FOID/Reading%20Room/Detainne_Related/FormicaReportRelease.pdf) of US Special Forces at Abu Ghraib found that allegations of detainee abuse were unsubstantiated and contradicted by the evidence. In general, facilities met the standards under international law as well as US law and policy. It did discover some issues, and made recommendations for mandatory corrective training.
- On June 9, 2005, an [investigation](https://www.globalsecurity.org/security/library/report/2005/d20050714report.pdf) into FBI allegations of detainee abuse was finished. After reviewing a _three-year_ period covering more than _24,000 interrogations_, Furlow and Schmidt identified _three_ interrogation acts that were never approved for use by the government. The investigation revealed no evidence of torture or inhumane treatment at Guantanamo Bay.
- A 2005 Navy Inspector General report, also known as the [Church report](https://www.esd.whs.mil/Portals/54/Documents/FOID/Reading%20Room/Detainne_Related/church_report_1.pdf) concluded, "we examined the 187 DoD investigations of alleged detainee abuse that had been closed as of September 30, 2004. Of these investigations, 71 (or 38%) had resulted in a finding of substantiated detainee abuse, including six cases involving detainee deaths. 8 of the 71 cases occured at GTMO, all of which were relatively minor in their physical nature. Additionally, 130 cases remained open, with investigatins ongoing. Finally, our investigation indicated that commanders are making vigorous efforts to investigate every allegation of abuse—regardless of whether the allegations are made by DoD personnel, civilian contractors, detainees, the ICRC, the local populace, or any other source." One case was removed from this statistical report leaving it to just 70 substantiated. Of the 70, there were only 121 victims. Disciplinary action was taken against a total of 115 personnel. The investigation found no link between approved interrogation techniques and detainee abuse.
- In November, 2004, in Fallujah, Iraq, TF 2-2 provided indirect firesupport to US forces during the battle for Fallujah. During the battle, TF 2-2 lawfully deployed White Phosphorus munitions, described as "shake and bake", to flush out insurgents out of trench lines and spider holes, because of its Psychological impact. To quote from the March 2005 magazine [Field Artillery](https://sill-www.army.mil/fires-bulletin-archive/archives/2005/MAR_APR_2005/MAR_APR_2005_FULL_EDITION.pdf), 'The Fight for Fallujah', "WP proved to be an effective and versatile munition. We used it for screening missions at two breeches and, later in the fight, as a potent psychological weapon against the insurgents in trench lines and spider holes when we could not get effects on them with HE. We fired “shake and bake” missions at the insurgents, using WP to flush them out and HE to take them out." This entry was misquoted by media to allege that US forces were deploying WP munitions against combatants for its incindary and/or chemical effects.
- On May 12, 2004, CIA Deputy Director McLaughlin, in closed [testimony](https://archive.org/details/may-12-2004-ddcia-testimony) corrected the record to Congress that CIA was not involved in any of the photos seen that leaked to the media, of unauthorised detainee abuse at Abu Ghraib. He said, "We are not authorised in the program to do anything like what you have seen in those photographs." As noted by the Office of Medical Services (OMS) on the RDI program during their [review](https://assets.documentcloud.org/documents/5301943/CIA-OMS-Summary.pdf), "The empirical record affirmed effectiveness and, through the presence of OMS, the safety of the program. Finally, critically and urgency each received case-by-case analysis from CTC. Though imperfect this review nonetheless limited the application of EITs to less than a third of the detainees who came into Agency hands, and further limited the use of the most aggressive techniques to only 5 or 6 of the highest value detainees. A criterion of"'necessity" also requires that no aggressive measure be used when a lesser measure would suffice."
- In May 2004, US conducted a raid near the Iraq-Syrian border, targeting several HVTs of the Zarqawi network. The NYT and AP alleged this was a wedding where many civilians were killed as a result of the raid. However, Signals, Human and Satellite intelligence as well as forensic and contradictory and inconsistent local testimony during interviews proved this allegation [false](https://www3.centcom.mil/FOIA_RR_Files/5%20USC%20552(a)(2)(D)Records/U.S.%20Raid%20Near%20the%20Syrian-Iraq%20Border%20on%2019%20May%2004/r_Responsive_Docs-Facts_Findings-new-Bracketed.pdf).
- On December 10, 2002, a number of US Military personnel (20) were involved in [detainsee abuse](https://archive.org/details/doddoacid-011770) that resulted in the death of two men, one of whom was Dilawar. CIA had no involvement in this matter.
- On September 23, 2009, an [independent](https://media.defense.gov/2017/Oct/31/2001836211/-1/-1/1/09-INTEL-13.PDF) investigation found that allegations that the DoD, between September 2001 to April 2008 was using "mind-altering drugs" on detainees to be unsubstantiated. Some detainees were medicated to treat diagnosed mental conditions.
- On 30 June, [2002](https://web.archive.org/web/20021207215250/http://www.centcom.mil/News/Reports/Investigation_Oruzgan_Province.htm), in Oruzgan Province, Afghanistan, recon and other coalition aircraft came under fire from a number of compounds by AAA batteries. An AC-130 was called in. There were people within this area of Oruzgan Province that regularly aimed and fired of variety of weapons at coalition aircraft. These weapons represented a real threat to coalition forces. As OFT commenced, AAA weapons were fired and, as a result, an AC-130 aircraft, acting properly and in accordance with the rules, engaged the locations of those weapons. Great care was taken to strike only those sites that were actively firing that night. While the coalition regrets the loss of innocent lives, the responsibility for that loss rests with those that knowingly directed hostile fire at coalition forces. The operators of those weapons elected to place them in civilian communities and elected to fire them at coalition forces at a time when they knew there were a significant number of civilians present.
- On November 2002, Gul Rahman died in CIA detention. An independent [investigation](https://www.cia.gov/readingroom/docs/0006555318.pdf) found that he was not subject to torture or mistreated—that his own actions lead to his death. It reached the following conclusions:
- >There is no evidence to suggest that Rahman's death was deliberate.
- >There is no evidence to suggest Rahman was beaten, tortured, poisoned, strangled, or smothered.
- >Gul Rahman's actions contributed to his own death. By throwing his last meal he was unable to provide his body with a source of fuel to keep warm. Additionally, his violent behavior resulted in his restraint which prevented him from generationg body heat by moving around and brought him in direct contact with the concrete floor leadng to the loss of bodyheat through conduction.
This was also subject to an OIG investigation, and forwarded to DOJ for prosecutoral determination. DOJ notified it would not charge, but would include it in an ongoing special counsel review by the Attorney's Office for the Eastern District of Virginia. An independent [study](https://assets.documentcloud.org/documents/1377196/cia-response-to-senate-report.pdf) of the RDI program found that in addition to OIG investigations and criminal prosecutions—including the extensive multi-year investigation of RDI activity by a DOJ special prosecutor, which reviewed more than 100 detainee cases—CIA convened six accountability proceedings, either at the directorate or higher level, from 2003 to 2012.
In total, these reviewed assessed the performance of 30 individuals (staff officers and contractors), and 16 were deemed accountable and sansctioned. OIG conducted two seperate major reviews and at least 29 seperate investigations of alleged misconduct. Some of these reviews were self-initiated by Agency components responsible for managing the program. CIA made numerous referrals to the OIG relating to the conduct of Agency officers and their treatment of detainees, during the life of the program as well as after. When actions appeared to violate criminal prohibitions, referrals were made to the DOJ.
In total, OIG conducted nearly 60 investigations on RDI-related matters. In over 50, OIG found the allegations to be unsubstantiated or otherwise did not make findings calling for accountability review. Of the remaining cases, one resulted in a felony conviction, one resulted in termination of a contractor, and revocation of his security clearances, and six led to accountability reviews.
- After 9/11, the US passed into law the Patriot Act. [A law that streamlined many already-existing laws at a federal level](https://www.justice.gov/archive/ll/subs/add_myths.htm). It, along with the USA Patriot Improvement Act, [strengthened privacy and civil liberties protections](https://www.justice.gov/archive/911/legal.html)
A detailed overview of one of the PA's provisions can be found [here](https://www.documentcloud.org/documents/750227-patriot-act-section-215-white-paper.html) and a deep-dive [here](https://jnslp.com/wp-content/uploads/2014/05/On-the-Bulk-Collection-of-Tangible-Things.pdf)
For an overall view of surveillance changes post 9/11 see [here](https://www.alston.com/-/media/files/insights/publications/peter-swire-testimony-documents/professorpeterswiretestimonyinirishhighcourtcase.pdf) Chapter 5 details the many means in which the Foreign Intelligence Surveillance Court holds the Government's feet to the fire, via various mechanisms—via a systematic evaluation of the declassified record. "The FISC has been criticized in some media outlets as a “rubber stamp,” particularly in the wake of the Snowden disclosures.This section shows howrecently-declassified materialsare not consistent with that claim. In my view, the FISC exercises effective oversight, backed by constitutional authority, over government applications to conduct surveillance."
The Chapter is divided into four sections:
- I. The newly declassified materials support theconclusion that the FISC today provides independent and effective oversight over US government surveillance. Especially since the Snowden disclosures, the FISC was criticized in some media outlets as a “rubber stamp.” This section shows that this claim is incorrect. It examines FISC opinions illustrating the court’s care in reviewing proposed surveillance. For many years, an important role of the FISC was to insist that the Department of Justiceclearly document its surveillance requests, with the effect the Department would only go through that effort for high-priority requests. Since the passage of the USA FREEDOM Act, the number of surveillance applications that the FISC has modified or rejected has,at least initially,grownsubstantially, to 17 percent of surveillance applications inthe second half of2015.6The section closes by showing the FISC’s willingness to exercise its constitutional power to restrict surveillance that it believes is unlawful.
- II. The FISC monitors compliance with its orders, and has enforced with significant sanctions in cases of noncompliance. The FISC’s jurisdiction is not confined to approving surveillance applications. The FISC also monitors government compliance and enforces its orders. This section outlines the interlocking rules, third-party audits, and periodic reporting that provide the FISC with notice of compliance incidents. It then discusses examples of the FISC’s responses to government noncompliance. FISC compliance decisions have resulted in (1) the National Security Agency(NSA)electing to terminate an Internet metadata collection program; (2)substantial privacy-enhancing modifications to the Upstream program; (3) the deletion of all data collected via Upstream prior to October 2011; and (4) a temporary prohibition on the NSA accessing one of its own databases.
- III. In recent years, both the FISC on its own initiative and new legislation have greatly increased transparency. Under the original structure of FISA, enacted in 1978, the FISC in many respects was a “secret court” –the public knew of its existence but had very limited information about its operations. This section describes how, in recent years, the FISC itself began to release more of its own opinions and procedures, and the USA FREEDOM Act now requires the FISC to disclose important interpretations of law.It also discusses how litigation before the FISC resulted intransparency reporting rights, and how these rights have been codified into US surveillance statutes.
- IV. The FISC now receives and will continue to benefit from briefing by parties other than the Department of Justice in important cases. Originally, the main task of the FISC was to issue an individual wiretap order, such as for one Soviet agent at a time. Aswith other search warrants, these proceedings were ex parte, with the Department of Justicepresenting its evidence to the FISC for review. After 2001, the FISC played an expanded role in overseeing entire foreign intelligence programs, such as under Section 215 and Section 702. In light of the more legally complex issues that these programs can raise, there was an increasing recognition that judges would benefit from briefing by parties other than the Department of Justice. This section reviews newly declassified materials concerning how the FISC began to receive such briefing of its own initiative. Prior to the USA FREEDOM Act, the FISC created some opportunities for privacy experts and communication services providers to brief the court. The USA FREEDOM Act has created a set of six experts in privacy and civil liberties who will have access to classified information and will brief the court in important cases.
No country on earth comes as close to transparency or to the protectinons of privacy and civil liberties compared to the US, [even for non-citizens](https://www.documentcloud.org/documents/5003660-PCLOB-PPD28-Report.html) "PPD-28 was a milestone. It responded to an important and difficult issue in US foreign intelligence practice: How to conduct necessarily robust collection of communications data outside the United States while respecting the privacy rights of non-US persons — privacy rights inherent, according to the long-standing policy of the United States, in all human beings. By codifying for the first time significant limits on intelligence activities affecting non-US persons outside the United States, the directive gave substance to our government's claim to respect the human rights of all individuals. It affirmed and strengthened the role of the United States as the world's leader by (1) establishing express limits on intelligence activities, even as it reaffirmed the need for robust intelligence capabilities; (2) promoting transparency about those limits; and the (3) establishing a greater degree of equivalence, where feasible, between protections for the personel information of US persons and non-US persons."
Indeed the above review said, "We urge the CIA _not_ to apply the PPD-28's retention rules to [blank] unless it develops a way to avoid over-application of the Directive." and that, "The CIA, for example, has decided to apply PPD-28 to a broad range of activities, including some that it explicity acknowledged "are not SIGINT." Of course, PPD-28 didn't change NSA's activities that much, as the report notes, "NSA's past practice was to limit all signals intelligence activities, including the dissemination of personal information of non-US persons in disseminated SIGINT products, to those necessary to accomplish its foreign intelligence mission."
One may be forgiven to think this is "just on paper", alas, that is not so. Thousands of declassified pages confirm that these governing laws, policy and guidance are all followed. Where honest mistakes are made, they are corrected promptly.
Lets look at 4 such records, that cover, in total, almost decades—from 9/11 to 2019.
- [ST-09-0002](https://archive.org/details/JointIGreviewPSP/page/n129/mode/2up?view=theater) "NSA activity conducted under the PSP was authorised by Foreign Intelligence Surveillance Court (FISC) orders by 17 Janurary 2007, when NSA stopped operating under PSP authority. The NSA Office of the Inspector General (OIG) detected _no intentional misuse of Program authority._"
- [18th Joint Assessment](https://www.dni.gov/files/icotr/18th_Joint_Assessment.pdf) "Consistent with previous Joint Assessments, no instances of intentional circumvention or violation of those procedures were found during this reporting period."
- [SID Oversight & Compliance](https://www.aclu.org/sites/default/files/field_document/Letter%20from%20David%20S.%20Kris%2C%20Assistant%20Attorney%20General%2C%20to%20the%20Honorable%20John%20D.%20Bates%2C%20Presiding%20Judge%2C%20United%20States%20Foreign%20Intelligence%20Surveillance%20Court.pdf) "Conducted a complete (100 percent) audit of all PR/TT metadata queries, and this audit has confirmed that there has been no inappropriate access to the sensitive PR/TT metadata via intelligence analysis tools. Compliance audits have determined that the EAR has prevented all queries on non-RAS approved identifiers from accessing the metadata."
- [Several](https://assets.documentcloud.org/documents/2809657/Nsa-Ig-Bulk-Nyt-15-0811.pdf) NSA OIG reports confirm in monthly reporting instances of finding no non-compliance. Though it finds issues here and there, and provides recommendations. Not a single case of misuse/abuse was found.
None of the above involved "warrantless wiretapping either. It was always the case that to do surveillance on a US person, located in the US or outside the US, or an alian within the US: A warrant is required. PRISM/Upstram collection under FAA Sec. 702 cannot target USPs and are annually approved by FISC. The bulk collection of CDRs also wasn't a wiretap, and required Court order every 90 days. The above records provide details on this, but the following do as well:
- [ST-14-0002](https://www.nsa.gov/Portals/70/documents/news-features/declassified-documents/3IGReports-Sealed.pdf) Contains 3 OIG reviews but 14-0002 Covers 702 and 215 authorities. p. 224 for 702's PRISM/Upstream. p. 155 for bulk CDR.
- [ODNI Infographic](https://www.dni.gov/files/icotr/Section702-Basics-Infographic.pdf) Provides a very basic rundown of how 702 works, oversight, value.
- [Covers 702 targeting procedures](https://www.dni.gov/files/documents/icotr/Assessment_Oversight_Compliance_702_Targeting_Procedures-Redacted.pdf) A small read (12 pages).
- [Fleisch Decl.](https://fas.org/sgp/jud/statesec/jewel-fleisch.pdf) and [Bonanni Decl.](https://fas.org/sgp/jud/statesec/jewel-bonanni-redacted.pdf)
These two are another good overview, though more basic to an extent, of the evolution from TSP to 702 and 215 authorities, etc.
also specifically debunks the notion of "key words"
- It has been alleged by several media outlets and NGOs that the CIA had several of the following individuals in CIA custody:
- Khalid Al-Zawahiri
- Osama Bin Yousaf
- Qari Saifullah Akhtar
- Walid bin Azmi
- Iban Al Yaquti al Sheikh al-Sufiyan
- Amir Hussein Abdullah al-Misri
- Safwan al-Hasham
- Jawad al Bashar
- Saif Al-Islam Al-Masri
A [review](https://www.documentcloud.org/documents/20392756-savage-nyt-foia-redacted-durham-report-to-holder-on-cia-detainees-not-in-cia-custody) of FBI, CIA and DoD documents confirms none of these individuals were in CIA custody.
- In 2003, the US legally invaded Iraq pursaunt to UNSC Resolution 1441. This was preceeded by years of Iraqi non-complinace with prior resolutions + a ceasefire agreement. The popular myth is that the US and UK Governments lied to justify invasion. However, a review of the declassified record shows this claim to be a haox:
[Response to the independent report of the UK's Intelligence and Security Committee](https://www.gov.uk/government/publications/government-response-to-the-intelligence-and-security-committee-report-on-iraqi-weapons-of-mass-destruction) concerning Iraq WMDs and in examining whether the available intelligence, which informed the decision to invade Iraq, was adequate and properly assessed and whether it was accurately reflected in Government publications.
The Committee found the following key conclusions:
- 1. The September dossier was endorsed by the whole JIC (ISC Report, paragraph 106).
- 2. The September dossier was founded on the intelligence assessments then available (paragraph 107).
- 3. The September dossier was not ’sexed up’ by Alastair Campbell or anyone else (paragraph 108).
- 4. The JIC was not subjected to political pressures. Its independence and impartiality were not compromised in any way (paragraph 108)
A Senate Intelligence Committee study, titled, _[Whether public statements regarding Iraq by US Govt Officials were substantiated by Intelligence information](https://www.intelligence.senate.gov/sites/default/files/publications/110345.pdf)_ found that all public statements by US officials were indeed supported by the intelligence at the time, see page 117 of PDF/133 of scan.
Another [study](https://web.mit.edu/simsong/www/iraqreport2-textunder.pdf) by the same commitee found that no intelligence was fabricated, or skewed or that analysts were pressured to making an assessment.
>"The Committee was not presented with any evidence that intelligence analysts changed their judgments as a result of political pressure, altered or produced intelligence products to conform with Administration policy, or that anyone even attempted to coerce, influence or pressure analysts to do so. When asked whether analysts were pressured in any way to alter their assessments or make their judgments conform with Administration policies, not a single analyst answered yes."
It has been alleged in the media and by pundists, that then SecDef Rumsfeld created a "rouge intel op" to justify invading Iraq, and created false intel reports, etc. This conspiracy theory was debunked by a [2007](https://archive.org/details/IraqPreWarActivitiesResponse/mode/2up) DODIG report, and management comments.
- Under the September 17, 2001 Memorandum of Notification, the CIA engaged in a covert program to hunt down, capture, detaine, and later interrogate HVT AQ detainees. This program exampled effective oversight improvements over time, indeed, [Congressional staffers](https://ciasavedlives.com/bdr/cia-congress-interactions-regarding-cia-rdi-program.pdf) notes that one CIA Black Site, "upon departing... compared the facility to both the US Military detention facility at Bagram and the facility at Guantanamo Bay. Both remarked that the facility "was markedly cleaner, healthier, more humane and better administered facility."
An independent [audit](https://assets.documentcloud.org/documents/4454538/Document-20-CIA-Office-of-the-Inspector-General.pdf) of CIA facilities notes, "Detainees at facilities operated by CTC/RDG are provided essentials of shelter, clothing, mourishment, and hygiene; medical and psychological examinations and treatment; limited dental and vision care; opportunities for physical exercise and intellectual, religious, and recreational pursuits; and daily contact with facility staff. Detainees are held in solitary confienment in climate-controlled, lighted, aboveground, windowless cells that are equipped with a mattress, a sink, and a toilet. None of the detainees showed any apparent physical signs of mistreatment."[1](https://www.documentcloud.org/documents/20887990-00000000-cia-hvd-program)
Even within CTC, any detainees reporting to be mistreated and use of unauthorised techniques were thoroughly, independently investigated. Indeed, CTC/Legal [forwarded](https://web.archive.org/web/20201120073426/https://www.cia.gov/library/readingroom/docs/0006541723.pdf) Mr. Hawsawi's complaints to the OIG. They, inturn, forwarded it to the DOJ, as the allegations as alleged, if true—would be in violation of Title 18 U.S.C. 2340A Torture. All investigations found no evidence to support the allegations, however, still updated the DOJ on the matter in 2006. This, among others, shows the Agency is not afraid to self-report allegations even by detainees for investigation.
It was also falsely claimed by Dianna Feinstein that the CIA spied on her Committee when conducting their review of the program. This was thoroughly debunked by an independent [review](https://assets.documentcloud.org/documents/1502797/redacted-12-2014-agency-accountability-board.pdf).
- Claims that the United States invaded Afghanistan to control the poppy fields and protect the market have proven time and time again to be false, ignoring the US-led effort to destroy, desrupt and phase out poppy cultivation in the land, working with the Afghanistan Government and ISAF to reach this goal. This goal has had its ups and downs, and did work overall. While poppy production increased over the years; it stemmed from Taliban/AQ-controlled regions—not those controlled by the Government.[1](https://2001-2009.state.gov/p/inl/rls/other/102214.htm) [2](https://2001-2009.state.gov/documents/organization/90671.pdf) [3](https://www.sigar.mil/interactive-reports/counternarcotics/index.html) [4](https://www.everycrsreport.com/files/20171213_RL30588_0a51c51635f5c5fcd227fe6dc9d4dda135ef1aa4.pdf) [5](https://media.defense.gov/2007/Jul/01/2001712995/-1/-1/1/Counternarcotics_Pgr_Afghan%20_Final%20Rpt.pdf) [6](https://www.justice.gov/sites/default/files/testimonies/witnesses/attachments/2016/02/02/01-15-14_dea_capra_testimony_re_future_us_counternarcotics_efforts_in_afghanistan_web_ready.pdf)
- After the terrorist attack on 9/11, the US responded by sending in [small CIA/Special Forces teams](https://www.archives.gov/files/declassification/iscap/pdf/2012-041-doc01.pdf) into Afghanistan. They knew their enemy. "In CTC/SO, we operated on the understanding that the enemy was not Afghanistan, not the Afghan people, and not even the Taliban as a government institution. The enemy was al-Qaida, particularly the terrorists' command and control network and their specific Taliban leadership allies."
US later invaded Afghanistan. [Legal under US domestic & international law](https://archive.org/details/warinafghanistan85schm)
The US invaded Iraq because of its [non-compliance with UNSC Resolution 1441](https://archive.org/details/wariniraqlegalan86pedr)
- The First Gulf War, led by the US to repel the illegal invasion & occupation of the Iraqi military from Kuwait was both devestatingly effective, and in [full compliance with international law](https://babel.hathitrust.org/cgi/pt?id=uiug.30112004365182&view=2up&seq=638&skin=2021), as emphasis was placed on [reducing civilian casualties and collateral damage to infrastructure as much as possible](https://babel.hathitrust.org/cgi/pt?id=uiug.30112004365182&view=2up&seq=664&skin=2021) this includes the "highway of death". As the final report to Congress notes:
>"In the early hours of 27 February, CENTCOM received a report that a concentration of vehicles was forming in Kuwait City. It was surmised that Iraqi forces were preparing to depart under the cover of darkness. CINCCENT was concerned about the redeployment of Iraqi forces in Kuwait City, fearing they could join with and provide reinforcements for Republican Guard units west of Kuwait City in an effort to stop the Coalition advance or otherwise endanger Coalition forces. The concentration of Iraqi military personnel and vehicles, including tanks, invited attack. CINCCENT decided against attack of the Iraqi forces in Kuwait City, since it could lead to substantial collateral damage to Kuwaiti civilian property and could cause surviving Iraqi units to decide to mount a defense from Kuwait City rather than depart. Iraqi units remaining in Kuwait City would cause the Coalition to engage in military operations in urban terrain, a form of fighting that is costly to attacker, defender, innocent civilians, and civilian objects.The decision was made to permit Iraqi forces to leave Kuwait City and engage them in the unpopulated area to the north. In the aftermath of Operation Desert Storm, some questions were raised regarding this attack, apparently on the supposition that the Iraqi force was retreating. The attack was entirely consistent with military doctrine and the law of war. The law of war permits the attack of enemy combatants and enemy equipment at any time, wherever located, whether advancing, retreating, or standing still. Retreat does not prevent further attack. At the small-unit level, for example, once an objective has been seized and the position consolidated, an attacking force is trained to fire upon the retreating enemy to discourage or prevent a counterattack."
- During the first Persian Gulf War (1991), [U.S. military](https://babel.hathitrust.org/cgi/pt?id=uiug.30112004365182&view=2up&seq=649&skin=2021&q1=Al%20Firdus%20bunker) planners identified Al Firdos C3 Bunker (Amiriyah shelter), as an Iraqi military command and control center. Barbed wire surrounded the complex, it was camouflaged, armed sentries guarded its entrance and exit points, and electronic intelligence identified its activation. Unknown to coalition planners, some Iraqi civilians used upper levels of the facility as nighttime sleeping quarters. The bunker was bombed, resulting in over 400 civilian deaths. Was there a violation of the LOAC? Not by U.S. forces, but there was a clear violation of the principle of distinction (discussed infra) by Iraqi forces. Based upon information gathered by Coalition planners, the commander made an assessment that the target was a military objective. Although the attack may have resulted in unfortunate civilian deaths, there was no LOAC violation because the attackers acted in good faith based upon the information reasonably available at the time the decision to attack was made. A review of the targeting policies at the time were determined to be proper.
- In 1991, the United States and allied countries [under UNSCR resolution & strict Rules of Enagement](https://digital-commons.usnwc.edu/cgi/viewcontent.cgi?article=1459&context=ils), imposed 3 no-fly zone operations to secure the Kurdish people from slaughter at the hands of the brutal Iraqi regime. This measure allowed the Allied nations to also provide humanitarian aid.
- In August 1990, Saddam Hussein’s army invaded Kuwait and consequently the United Nations imposed economic sanctions on Iraq.
Saddam lied about the effect of these sanctions, by manipulating census data. A [paper](https://gh.bmj.com/content/2/2/e000311) published in BMJ Global Health confirms, "Since 2003, however, several more surveys dealing with child mortality have been undertaken. Their results show no sign of a huge and enduring rise in the under-5 death rate starting in 1991. It is therefore clear that Saddam Hussein’s government successfully manipulated the 1999 survey in order to convey a very false impression—something that is surely deserving of greater recognition."
- In 1988, a US Navy ship accidentally shot down civilian airline flight 655. An [independent investigation](https://www.documentcloud.org/documents/6660400-1988-Iran-Plane-Crash-Fp.html#document/p1) determined that Iran was at fault for the tragedy. Its actions that day led to the incident. "On the morning of 3 July, MONTGOMERY observed seven IRGC small boats approaching a Pakistani vessel. The number shortly thereafter grew to 13 and they began to challenge nearby merchantmen. VINENNES was ordered to the area to support MONTGOMERY and launched a helicopter to reconnoiter the scene. In the progress the helicopter was fired upon. VINCENNES and MONTGOMERY closed the general areas of the small boats. Two of the boats turned toward VINCENNES and MONTGOMERY while the others began to maneuver erratically. These actions were interpreted as manifesting hostile intent and both ships, after being given permission, engaged. This action, involving high speed course changes and gunfire at close range, was still in progress when Air Bus 655 took off from the joint military/civilian airfield at Bandar Abbas and headed toward Dubai. It is hard to overemphasize the fact that Bandar Abbas is also a military airfield. The Air Bus was probable not informed of the surface action taking place in the Strait. Informed or not, Flight 655 logically appeared to have a direct relationship to the ongoing surface engagement.
During the critical seven minutes that Flight 655 was airborne, Captain Rogers and his CIC Watch team were integrating a multitude of ongoing events. Specifically, VINCENNES was engaged in a high-speed surface battle with at least two groups of Iranian small boasts—all of which had the capability to inflict serious damage. At the same time, she was monitoring one of her helos which was airborne and had already come under attack. CIC was also tracking an Iranian P-3 military aircraft airborne approximately 60 nautical miles to the northwest which was presenting a classic targeting profile. (i.e., furnishing information to an attack aircraft.) In the midst of this highly charged environment, an unknown aircraft took off from a joint military/civilian airport on a flight path headed directly toward VINCENNES and MONTGOMERY. This was the same airfield from which Iran had launched F-4s in support of an attack on US naval forces on 18 April. This unknown aircraft was 27 minutes behind any scheduled commerical airline departure from Bandar Abbas airport. Although it was flying within a known commercial air corridor, it was off centerline some 3 or 4 miles, which was not the usual centerline profile for commercial air traffic previously monitored by VINCENNES. Moreover, its mid-range altitude was consistent with either a hostile or commerical aircraft. VINCENNES could detect no radar emanations from the contact which might identify it, but was reading a Mode III IFF squawk. This situation was confused somewhat when a Mode II IFF squawk was detected and the aircraft was identified as an F-14. Complicating the picture was an Iranian P-3 to the west which was in excellent position to furnish targeting information to an attacking aircraft. More importantly, the unknown contact continued at a gradually increasing speed on a course headed toward VINCENNES and MONTGOMERY. It failed to respond to repeated challenges from VINCENNES over both military and international emergency distress frequencies.
- It has been alleged that the CIA aided the Taliban and AQ, or extremist elements of the Mujahideen; funded and trained Bin Ladin, etc. These are all false, but rely on a partial truth. The US did aid the Mujahideen to fight off the illegal Soviet invasion/occupation.
[In summary](https://web.archive.org/web/20050310111109/http://usinfo.state.gov/media/Archive/2005/Jan/24-318760.html):
>U.S. covert aid went to the Afghans, not to the "Afghan Arabs."
>The "Afghan Arabs" were funded by Arab sources, not by the United States.
>United States never had "[any relationship whatsoever](https://web.archive.org/web/20191101205458/https://www.cia.gov/news-information/cia-the-war-on-terrorism/terrorism-faqs.html)" with Osama bin Laden.
>The Soviet invasion of Afghanistan, Arab backing for the "Afghan Arabs," and bin Laden's own decisions "created" Osama bin Laden and al Qaeda, not the United States.
It should also be [noted](https://www.cia.gov/static/9fa9520134e1c2f3068001de69c9964b/Curator-Pocket-History-CIA.pdf) that the [CIA/SF](https://www.archives.gov/files/declassification/iscap/pdf/2012-041-doc01.pdf) units the US sent in after 9/11, met up with these very same moderates they helped in the 80s, to fight AQ and the Taliban.
- In 1980s, US had no involvement in the Turkish coup. According to the list's own wiki citation, the alleged source for the claim clarified in a June 2003 interview, "I did not say to Carter "Our boys did it." It is totally a tale, a myth, It is something Birand fabricated. He knows it, too. I talked to him about it." And, "General Kenan Evren said 'the US did not have pre-knowledge of the coup but we informed them of the coup 2 hours in advance due to our soldiers coinciding with the American community JUSMAT that is in Ankara.'"
- Despite many allegations, no evidence exists that the US supported either or both sides of the Iran-Iraq conflict.
It is [confirmed](https://web.archive.org/web/20170124020754/https://www.cia.gov/library/readingroom/docs/CIA-RDP90T01298R000300670001-8.pdf) that the USSR was a major supplier for chemical agents and other gear to Iraq. CIA only, naturally, [monitored](https://www.cia.gov/readingroom/docs/CIA-RDP81B00401R000500030002-5.pdf) the conflict—it is after all—the _Central Intelligence Agency_.
- In 1953, the CIA spearheaded an operation to aid the Shah, who legally dismissed Mossadeq. Pundits and historical revistionists claim Mossadegh was "democratically elected" this is furthest from the truth. Indeed, he was widely seen as unopular, and the "election" is widely considered a sham. As noted in the most comprehensive & authoritative [study](https://www.documentcloud.org/documents/4375470-Document-2-Zendebad-Shah.html) of the CIA's involvement, the author concludes,
"Did the CIA act against a legitimate leader enjoying popular support? Although there is no doubt that Mossadeq captured the imagination of segments of Iranian society with the nationalization of the Anglo-Iranian Oil Company in 1951, his political support dwindled steadily. By August 1953 he did not command mass support. The Tudeh and splinters of the National Front were the only political parties willing to support him. The pro-Shah sentiments of the Tehran crowds on 19 August 1953 were genuine. Although CIA had a hand in starting the demonstrations, they swelled spontaneously and took on a life of their own that surprised even Kermit Roosevelt. By August 1953, Mossadeq's support was vociferous by increasingly narrow. The Shah's support was latent but deep, and took a crisis—like the news of Tudeh demonstrators pulling down the Shah's statutes—to awaken. Khorramabad residents, for example, wildly rejoiced at hearing of the monarch's return. Before dismissing reports like those from Khorramabad as propaganda, it must be remembered that CIA was able to influence directly events only in the capital city, and there only barely. Kermit Roosevelt had neither the money nor the agents to initiate the kinds of demonstrations that took place in Iran's widely separated cities.
Did CIA restore the Shah to his throne? TPAJAX did not "restore" the Shah to his throne either technically or constitutionally. Although the Iranian monarch left Tehran during the operation, he never abdicated. Mossadeq's argument that the Shah's _firmans_ were invalid was disingenuous. The Iranian constitution gave the Shah the right to dismiss the Prime Minister. As soon as Mossadeq refused to obey the Shah's legal order, he was rebelling against constitutional authority. From that point on, TPAJAX became an operation to remove the usurper Mossadeq and permit Zahedi, the legitimate Prime Minister, to take office. Unlike Mossadeq's government, Zahedi's government recognized the Shah's constitutional authority."
- In 1949, the US had no involvement in the Syrian coup. The lists own' [wiki citation](https://en.wikipedia.org/wiki/March_1949_Syrian_coup_d%27%C3%A9tat#Political_context_and_allegations_of_U.S._involvement) makes it clear it's just a mere allegation, with contradictory narratives from the same author of several books. Nothing in the documentary record exists to even suggest a possible connection.
### Western Hemisphere
- In 2004, at the [request](https://2001-2009.state.gov/r/pa/prs/ps/2004/29990.htm) of President Jean-Bertrand Aristide of Haiti, the United States facilitated his safe departure, after resigning.
- In Peru, between 1995 and 2001, the CIA worked with the Peruvian Government in a counternarcotics operation. In 2001, the Peruvian Air Force accidently shot down a US plane carrying missionaries. Shortly after the incident, Director Hayden tasked the CIA's Inspector General reviewed the matter: Finding a lapse in procedures and charged that some CIA officers involved attempted to cover it up. This was disputed by a another seperate, independent [Agency Accountability Board](https://abcnews.go.com/Blotter/cia-statement-2001-peru-shootdown/story?id=9738624) review, that examined both the IG's report as well as conducting its own investigation. 16 officers were administratively punished after the Board's report was sent to Director Panetta. DOJ concurred with this finding, declining to criminally charge anyone involved. The fault lied mostly with the Peruvian Air Force in failing to adhere to the procedures as they had done so in the past.
- Haiti, September 1994, US Military forces were ordered to execute [Operation Uphold Democracy](https://www.armyupress.army.mil/Portals/7/combat-studies-institute/csi-books/kretchikw.pdf). The objective was to return to office the democratically elected President, and to facilitate a stable and secure environment in which democratic institutions could take hold. This was successful. President Aristide reassumed his duties, the Junta that ousted him was forced to leave the country, and national elections were successfully held in 1996. The democratic process there was given the opportunity to succeed due, in large part, to Operation Uphold Democracy.
- In June 1996, the President's Intelligence Oversight Board issued its _[Report on the Guatemala review](https://web.archive.org/web/20110926214324/http://www.ciponline.org/iob.htm)_ which examined CIA's interaction with security services on human rights issues concluded:
"The human rights records of the Guatemalan security services—the D-2 and the Department of Presidental Security (known informally as "Archivos." after one of its predeccesor organizations)—were generally known to have been reprehensible by all who were familiar with Guatemala. US policy-makers knew of both CIA's liason with them and the service's unsavory reputations. The CIA endeavored to improve this behavior of the Guatemalan services through frequent and close contact and by stressing the importance of human rights—insisiting, for example, that Guatemalan military intelligence training include human rights instruction. The station officers assigned to Guatemala and the CIA headquaters officials whom we interviewed believe that the CIA's contact with the Guatemalan services helped improve attitudes towards human rights.
DO Guidance on Human Rights:
The CIA's Directorate of Operations (DO) and Guatemala station were clearly aware of the potential for human rights violations by assets and liason contacts. In November 1988, the DO's Latin America (LA) division provided a guidance cable to its Central American stations:
>"Point we would like to make is that we must all become sensitized to the importance of respecting human rights, and we must ensure that those assets and resource we direct and/or fund are equally sensitive. The issue will only become more important, and we serve our objectives best if we remember that if we ignore the importance of the human rights issue in the final analysis we do a great damage to our mission. We are under great scrutiny.
>Finally, aside from the legal and policy considerations which are constant in any allegations concerning violations of human rights we also recognize a basic moral obligation. We are Americans and we must reflect American values in the conduct of our buisness. We are all inherently opposed to the violation of human rights. Those who work with us in one capacity or another must also respect these values."
The IOB also notes:
>"US policy objectives in Guatemala from 1984 to the present--the period we reviewed--included supporting the transition to and strengthening of civilian democratic government, furthering human rights and the rule of law, supporting economic growth, combating illegal narcotics trafficking, combating the communist insurgency, and advancing the current peace process between the government and the guerrillas."
>"The CIA's successes in Guatemala in conjunction with other US agencies, particularly in uncovering and working to counter coups and in reducing the narcotics flow, were at times dramatic and very much in the national interests of both the United States and Guatemala.
The CIA's Independent Inspector General issued a multi-volume series on Guatemala. [Volume 1](https://www.cia.gov/readingroom/docs/DOC_0000690161.pdf) concludes similar.
The Department of Defense also issued its 1995 [report](https://media.defense.gov/2017/Sep/11/2001806396/-1/-1/1/REPORT%20TO%20THE%20SECRETARY%20OF%20DEFENSE%20ON%20DOD%20ACTIVITIES%20IN%20GUATEMALA%20(U).PDF), 'Guatemala Review - Report to the Secretary of Defense on DoD Activities in Guatemala. which found that US Policy towards Guatemala was:
>Promoting a stable democratic government to include ending the Marxist insurgency;
>eliminating human rights abuses;
>responding to the economic and social needs of the Guatemalan people; and
>reducing drugs and drug trafficking.
Based on the documentation reviewed, all significant DoD programs and activities in Guatemala from 1980 to 1995 were within the stated US Policy objectives:
>There were 1,366 deployments to Guatemala during the period. Involving at least 25,021 DoD personnel. US military personnel performed humanitarian and civic action exercises designed to demonstrate the role of the military in stabilizing a democratic government and improving the economic and social welfare of the Guatemalan people.
>Since 1990, DoD personnel have supported the Drug Enforcement Administration's effort to interdic narcotics trafficking in Guatemala by transporting law enforcement personnel, detecting suspected trafficking activity, providing intelligence support and assisting in planning counterdrug operations.
>The DoD security assistance program during the period totalled 28 million in grant aid and 3.384 million in International Military Euducation and Training. With the exception of one UH-1 helicopter in 1983, no major end items were provided to the Government of Guatemala.
- The CIA had no involvement drug trafficking has alleged by Gary Webb. Several independent investigations could not substantiate the claims and found contradictory information to said allegations, such as when CIA learned of such illegal activities, they tipped off local Law Enforcement to take action.
- [CIA's independent Inspector General](https://web.archive.org/web/20201204233325/https://www.cia.gov/news-information/press-releases-statements/press-release-archive-1998/pr100898.html) "[Volume I](https://www.hsdl.org/?view&did=725779) of the report, which was issued on January 29, 1998, found no evidence that would substantiate The San Jose Mercury News allegations that the CIA had any involvement with Ricky Ross, Oscar Danilo Blandon, or Juan Norwin Meneses, or in cocaine trafficking in California to raise funds for the Contras."
- [A House Intelligence Committee investigation](https://web.archive.org/web/20170427105948/https://www.cia.gov/news-information/press-releases-statements/press-release-archive-2000/house_pr05112000.html) from 2000, "In summarizing its findings, the Committee stated: 'The allegations of the ‘Dark Alliance’ series warranted an investigation, and the Committee performed its role mindful of the thousands of American lives that have been lost to the scourge of crack cocaine. Based on its investigation, involving numerous interviews, reviews of extensive documentation, and a thorough and critical reading of other investigative reports, the Committee has concluded that the evidence does not support the implications of the San Jose Mercury News—that the CIA was responsible for the crack epidemic in Los Angeles or anywhere else in the United States to further the cause of the Contra war in Central America."
"Concluding its investigation into allegations of CIA complicity in drug trafficking to the United states during the 1980’s, the House Permanent Select Committee on Intelligence (HPSCI) today released a detailed report which concludes that evidence does not support those allegations, made initially in a newspaper series entitled "Dark Alliance."
- [DOJ's Independent Inspector General report](https://oig.justice.gov/sites/default/files/archive/special/9712/index.htm) concludes the same.
- In responding to requests from El Salvador, the US aided covertly and overtly, resistance movements to the [anti-democratic](https://www.brown.edu/Research/Understanding_the_Iran_Contra_Affair/documents/d-all-19.pdf) regime in Nicaragua. Nicaragua was engaging in a massive, illegal covert program—backed by the USSR, to overthrow the democratic government in El Salvador and surround countries. To expand on this further, I'll quote at length from the ICJ dissenting [opinion](https://www.icj-cij.org/public/files/case-related/70/070-19860627-JUD-01-09-EN.pdf) on the matter. It's worth noting the dissenting opinion is more than twice as long as the judgement, and revists the factual and legal record before it. Applying far more care:
"I am profoundly pained to say, I dissent from this judgement because i believe that, in effect, it adopts the false testimony of representatives of the Government of the Republic of Nicaragua on a matter which, in my view, is material to its disposition...
The facts are in fundamental controversy. I find the Court's statement of the facts to be inadequate, in that it is sufficiently sets out the facts which have led it to reach conclusions of law adverse to the United States, while insufficiently sets out the facts which should have led it to reach conclusions of law adverse to Nicaragua.
Without any pretence, still less actuality, of provocation, Nicaragua since 1979 has assisted and persisted in efforts to overthrow the Government of El Salvador by providing large-scale, significant and sustained assistance to the rebellion in El Salvador - a rebellion which, before the rendering of Nicaraguan assistance, was ill-organised, ill-equipped and ineffective. The delictual acts of the Nicaraguan Government have not been confined to provision of very large quantities of arms, munitions and supplies; Nicaragua (and Cuba) have joined with the Salvadoran rebels in the organisation, planning and training for their acts of insurgency; and Nicaragua has provided the Salvadoran insurgents with command-and-control facilities, bases, communications and sanctuary, which have enabled the leadership of the Salvadoran insurgency to operate from Nicaraguan territory. Under both customary and conventional international law, that scale of Nicaraguan subserve activity not only constitutes unlawful intervention in the affairs of El Salvador; it is cumulatively tantamount to an armed attack upon El Salvador."
"Not only is El Salvador entitled to defend itself against this armed attack; it can, and has, called upon the United States to assist it in the exercise of collective self-defense. The United States is legally entitled to respond. It can lawfully respond to Nicaragua's covert attempt to overthrow the Government of El Salvador by overt or covert pressures, military and other, upon the Government of Nicaragua, which are exerted either directly upon the Government, territory and people of Nicaragua by the United States, or indirectly through the actions of Nicaraguan rebels - the "contras" - supported by the United States."
A [thorough investigation](https://beta.documentcloud.org/documents/2702452-Iran-Contra-Minority-Report) over the actual Iran/Contra should be a read for anyone interested in the case.
As for the "guerilla manual" is largely overstated by pundits. After press reporting, [several investigations](https://www.reaganlibrary.gov/archives/speech/statement-principal-deputy-press-secretary-speakes-central-intelligence-agency) followed: One by CIA's Independent Inspestor General; one by the President's Intelligence Oversight Board and lastly a [Congressional investigation](https://ia601409.us.archive.org/5/items/united-states-congressional-serial-set/United_States_Congressional_Serial_Set.pdf). All concluded the purpose of the manual was to aid moderate gurilla's against a brutal regime, and how to win support of the people. However, due to poor translation by the contractor who made the report, was misinterpreted.
- It was alleged that the CIA, in El Salvador and Nicaragua supported death squads. This has been a [throroughly debunked](https://archive.org/details/united-states-congressional-serial-set) USSR hoax, to cover their support for such groups through Nicaraguan regime.
"The staff's investigation looked at press reports and materials from private organizations alleging a range of US intelligence activities with reference to death squads. These allegations can be summarized as follows:
- That US intelligence trained, organized, financed and advised Salvadoran security forces that engaged in death squad activities;
- That US intelligence was aware of torture and killing by Salvadoran security services and death squads, and in some cases participated in such killings.
The Committee staff conducted a comprehensive review aimed at providing as much information as couble be gathered bearing on these allegations. It reviewed intelligence reporting on death squads as well as the intelligence tasking which established priorities for intelligence collection. The Staff examined all intelligence reporting bearing on death squads from 1979 to present. It reviewed State Department cables bearing on the same subject. The staff conducted interviews with numerious intelligence officials knowledgable about intelligence activities in El Salvador from 1979 to 1984. The staff also reviewed in detail a CIA Inspector General report requested by the Committee in connection with H. Res.467. This report reviewed CIA operational relationships that might have involved members of death dquads. Finally, the staff made additional requests for information. The staff review of operational intelligence relationships leads it to conclude that US intelligence agencies have not conducted any of their activities in such a way as to directly encourage or support death squad activities. To the contrary, US intelligence activities have been directed, sometimes successfully, at countering death squad activity, reducing thee power of individuals connected with death squads, and seeking their removal from positions of authority.
The staff has uncovered no evidence that US intelligence oficials or US intelligence policy in any way encouraged torture by Salvadoran security service or by any death squads. To the Contrary, all that the staff can discover indicates US intelligence efforts to moderate the behavior of Salvadoran security service and armed forces personnel to prevent such activities. Further, as the US has learned more about death squad activity, and as it has concenreated more policy attention on this subject, some improvements have taken place. The staff poins in this regard to the exile from El Salvador of certain officials identified by the United States as having death Squad connections."
- 20 December, 1989, Operation Just Cause was launched. United States lawfully invaded the Republic of Panama to overthrow the dictatorship of General Manuel Antonio Noriega. By capturing the general, defeating the military forces he commanded, and [installing a democratic government](https://history.army.mil/html/books/just_cause/CMH_55-1-1_Just_%20Cause_opt.pdf) in the country. There are many authoritative [studies](https://www.jcs.mil/Portals/36/Documents/History/Monographs/Just_Cause.pdf) on Operation Just Cause. One that should be noted is [In the Aftermath of War: US support for reconstruction & nation-building in Panama following Just Cause](https://media.defense.gov/2017/Apr/05/2001727349/-1/-1/0/B_0061_SHULTZ_AFTERMATH_WAR.PDF)
- On October 1983, the United States [legally intervened](https://www.loc.gov/rr/frd/Military_Law/Military_Law_Review/pdf-files/277865%7E1.pdf) in Grenada, with international partners, with [Minimal civilian casualties](https://web.archive.org/web/20170129131916/http://insidethecoldwar.org/sites/default/files/documents/Grenada%20A%20Preliminary%20Report%20December%2016%2C%201983.pdf), "Grenadian casualties were 45 killed and 337 wounded. 24 of the Grenadian dead were civilians, 21 of whom were killed in an unfortunate bombing of a mental hospital located adjacent to an anti-aircraft installation. 24 Cubans were killed and 59 wounded of the approximately 800 Cuban 'construction workers' on the island... By December 15, all U.S. combat forces had withdrawn; among the U.S. forces only training, police, medical and support elements remained."
- In 1981, Soviet propaganda outlet TASS, alleged that the United States was behind the death of Panamarian President Omar Torrijos. This was [confirmed](https://www.cia.gov/readingroom/docs/CIA-RDP84B00049R001303150031-0.pdf) to be be Soviet disinformation.
- During the 1980s, allegations from the Bailtimore Sun, reported in 1995, allegations of CIA's complicity in Honduran human rights abuses. This triggered then-DCI John M. Deutch to direct a review of the allegations, from the 1980s to 1995, the review, known as the Honduras Working Group concluded, "there is no information in CIA files indicating that CIA officers either authorized or were directly involved in human rights abuses." Some issues remained unresolved, and reported this to CIA Executive Director Nora Slatkin. In July 1996, she requested the Inspector General investigate these outstanding matters. The IG report corroborated the Working Group's findings, "No evidence has been found to substantiate the allegation that any CIA employee was present during sessions of hostile interrogation or torture in Honduras." It also found no connection to the CIA in connection to, or evidence of the existance to ELACH, an alleged right-wing paramilitary organization; nor involved in any attempts to cover-up or downplay reporting. These two reviews independently corroborated a 1988 IG investigation that found no CIA aid or connection to any human righs abuses.. An OGC review also confirmed CIA had no involvement in, planned, or therwise connected to Olancho Operation. CIA policy regarding interrogations, and human rights in general is best described in a Janurary 14, 1985 HQ cable:
>"...Intervewing and interrogation of suspect in custody is a method routinely used by police, security and intelligence services around the world. In many countries, legal and basic rights of the suspect in custody may not be given full consideration, resulting in deprivaction of his/her human rights. CIA policy is not to participate directly in nor to encourage interrigation that results in the use of force, mental or physical torture, extremely demeaning indignities or exposure to inhumane treatment of any kind, as an aid to interrogation. CIA policy is to actively discourage the use of these methods during interrogations. CIA should play a positive role in influencing foreign liasion to respect human rights." Participation includes being in the room during an interrogation, sitting in an adjoining room monitoring the interrogation or providing questions while an interrogation is in progress.
A March 1976 HQ cable described CIA's Human Righs Policies and guidance,
>"...employees mus be especially sensitive to the political and possible legal remifications of what the CIA does. This cable also included a description of CIA officer's responsibilities if it were to be discovered that a host or third country intelligence or security service was about to undertake actions that could reasonably be construed to be gross violations of internationally recognized human rights. CIA personnel also were advised in this cable that, as a general rule, they should make appropriate efforts to prevent or delay such actions..."
[1](https://www.cia.gov/readingroom/docs/DOC_0000159944.pdf)
- From 1963-1973, CIA was involved in Chile politics. Though, not as broad as people claim. CIA aided in propaganda to help elect Frei. Frei lost the following election. CIA thought to reach out to some in the military for resistance before Allende could have his power confirmed by Congress. This went nowhere. CIA had 0 involvement in the coup itself. CIA had no involvement in Pinochet's claim to power. [An overview of CIA's activities confirms the following](https://web.archive.org/web/20040409084054/http://www.foia.state.gov/Reports/HincheyReport.asp):
- Many of Pinochet's officers were involved in systematic and widespread human rights abuses following Allende's ouster. Some of these were contacts or agents of the CIA or US Military. the IC followed then-current guidance for reporting such abuses and admonished its Chilean agents against such behavior. Today's much stricter reporting standards were not in force and, if they were, we suspect many agents would have been dropped.
- During a period between 1974 and 1977, CIA maintained contact with Manuel Contreras Sepulveda, who later became notorious for his involvement in human rights abuses. The US Government policy community approved CIA's contacts with Contreras, given his position as chief of the primary intelligence orginization in Chile, as necessary to accomplish the CIA's mission, in spite of conerns that this relationship might lay the CIA open to charges of aiding internal political repression. From the start, the CIA made it clear to Contreras was that it would not support any of his activities or activities of his service which might be construde as "internal political repression." In its contacts with Contreras, the CIA urged him to adere to a 17 Janurary 1974 circular, issued by the Chilean Ministry of Defense, spelling out guidelines for handling prisoners in a manner consistent with the 1949 Geneva Convention.
- In May and June 1975, elements within the CIA recommended establishing a paid relationship with Contreras to obtain intelligence based on his unique position and access to Pinochet. This proposal was overruled, citing the US Government policy on clandestine relations with the head of an intelligence service notorious for human rights abuses. However, given the miscommunisations in the timing of this exchange, a one-time payment was given to Contreras.
A review of CIA's files has uncovered no evidence that CIA officers and employees were engaged in human rights abuses or in covering up any human rights abuses in Chile."
- The US Government also had no involvement in Operation Condor. The US also tried to [prevent & disrupt](https://nsarchive.gwu.edu/sites/default/files/documents/5817664/National-Security-Archive-Doc-03-CIA-memorandum.pdf) the illegal activities and distance itself. The US asked Contreras to confirm its existance. [He did](https://nsarchive2.gwu.edu/NSAEBB/NSAEBB416/docs/780822cia.pdf).
- In the 1970s the United States took a large effort to promote Human Rights via humanitarian aid, military assistance, intelligence cooperation, international institutions, etc. Carter's administration set up NSC 28 to coordinate US Human Rights [policy](https://www.cia.gov/readingroom/docs/CIA-RDP91M00696R000100030020-1.pdf), assess [impacts](https://www.cia.gov/readingroom/docs/CIA-RDP80R01362A000200100001-6.pdf) and to detail [efforts](https://www.cia.gov/readingroom/docs/RESPONSE%20TO%20PD-30%5B15516322%5D.pdf) to promote Human Rights. In 1977, Human Rights reporting became a main focus on US Intelligence reporting requirements, with positive customer feedback in formulating US foreign policy.[1](https://www.cia.gov/readingroom/docs/CIA-RDP83M00171R001200180001-5.pdf)
- CIA had [no involvement](https://www.fordlibrarymuseum.gov/library/document/0005/7324009.pdf) in dictator, Rafael Trujillo's assassination. Some Latin American countries thought the US had allowed his brutal regime, however, it was just US policy to refrain from actions that would hasten his downfall. The US did enourage moderate democractic groups to resist the regime. The policy of non-intervention, while required by treaty, convinced Latin Americans that the US was supportive.
- In Bolivia, 1971, CIA made a one-time payment to [discourage](https://history.state.gov/historicaldocuments/frus1969-76ve10/d76a) a reportedly imminent coup and to “cement relations” with Bolivian military figures. Unknown to the CIA, a coup would follow two days later.
- US President Johnson took office in 1963, he inherented a longstanding U.S. Government policy of providing financial support for Bolivian political leaders. The policy was intended to promote stability in Bolivia by strengthening moderate forces, especially within the National Revolutionary Movement (MNR) itself, which had a strong left wing under the leadership of Juan Lechin Oquendo, General Secretary of the Mine Workers’ Federation. In August 1963 the 5412 Special Group approved a covert subsidy to assist the MNR to prepare for the presidential elections scheduled for May 1964. The Special Group agreed in March 1964 that the MNR receive additional financial support. Paz won the election; Lechin (who had been Vice President under Paz) left the government and founded a rival leftist party. Covert action expenditures in Bolivia between fiscal year 1963 and fiscal year 1965 were as follows: FY 63—$337,063; FY 64—$545,342; and FY 65—$287,978. The figure for FY 65 included funds to influence the campesino movement, for propaganda, to support labor organizations, and to support youth and student groups. The FY 66 program also allocated funds to support moderate political groups and individuals backing General Barrientos for President.
On November 4, 1964, the new Vice President, General René Barrientos Ortuño (MNR), led a successful military coup d’etat, forcing Paz into exile, (No US involvement in coup). In February 1965 the 303 Committee authorized a financial subsidy to the MNR under Barrientos (who was aware of U.S. financial support to the MNR) to help establish an organizational base for the presidential election scheduled for September. In May 1965 Barrientos responded to growing labor unrest by arresting and deporting Lechin and postponing the election. The 303 Committee, which considered a recommendation to support Barrientos as the best available candidate, agreed in July 1965 and March 1966 to authorize additional funds for MNR propaganda and political action in support of the ruling Junta’s plans to pacify the country and hold elections to establish a civilian, constitutional government.
When the presidential election was finally held in July 1966, Barrientos won easily, and officials concerned with the covert operation concluded that the objectives of the program—the _end of military rule_ and a _civilian, constitutional government_ whose _policies would be compatible with those of the United States—had been accomplished._ [1](https://history.state.gov/historicaldocuments/frus1964-68v31/d147)
- In 1962, the Chairman of the Joint Chiefs of Staff for the DoD approved a draft plan, known as Operation [Northwoods](https://ia600908.us.archive.org/7/items/pdfy-vlGx2NTBHA-M19I3/Operation%20NORTHWOODS%20Document%20-%20Official%20Origin%20of%20Modern%20US%20False-Flag%20Attacks.pdf), which authorised:
- Start rumors
- Land friendly Cubans in uniform "over the fence" to stage attack on base
- Capture (friendly) saboteurs inside base
- Start riots near base (friendly Cubans)
- Blow up ammunition inside the base; start fired.
- Sink ship near harbor entrance. Conduct funerals for mock-victims.
It goes on to say, "we could blow up a drone (unmanned) vessel anywhere in the Cuban waters."
The media has incorrect claimed that the plans were intended to cause harm to civilians.
- In 1954, Guatemala saw a military Junta, led by Carlos Castillo Armas, in a coup against the Árbenz government. It has been alleged the CIA had a role in this coup. The reason for this being a popularly held belief is that declassified CIA records do indeed outline CIA plans for such an activity, such as training exiles, assassination lists, etc. These are known as PBFORTUNE and PBSUCCESS. However: This [never came to fruition](https://web.archive.org/web/20180609064148/https://www.cia.gov/library/readingroom/docs/DOC_0000135796.pdf). No Árbenz official or Guatemalan Communist were killed—due to US plans being dropped.
### Africa
- On July 20, 2021, US Africa Command (AFRICOM), in coordination with the Federal Government of Somalia, conducted one airstrike in the vicinity of Galkayo, Somalia, against al-Shabaab fighters engaged in active combat against Somali Government forces. Initial assessment confirms [0 civilians killed](https://www.africom.mil/pressrelease/33893/us-africa-command-conducts-strike-against-al-shabaab).
- In March 2019, Amnesty International issued a report about US Airstrikes in Somalia, alleging US ignores CIVCAS claims, commits war crimes, etc.
Several [experts](https://sites.duke.edu/lawfire/2019/03/31/why-you-should-be-very-skeptical-of-amnesty-internationals-report/) have gone over the inferior methodology employed by NGOs like Amnesty on such matters. However, an [independent review](https://www.africom.mil/pressrelease/31697/u-s-africa-command-commander-directed-review-reveals-civilian-casualties) conducted confirms Amnesty got it wrong—again. This isn't the first time. The NGO, (and others have been shown to not even get the [month correct](https://archive.org/details/africomcivcas/mode/2up), when alleging a US airstrike.
- Since 2007, US Africa Command (AFRICOM), has done a number of assistance programs to African countries, ranging from [humanitarian aid, civil assistance](https://www.africom.mil/what-we-do), etc.
Some of these are:
- >Foreign Disaster Relief: Foreign Disaster Relief activities are unique Department of Defense capabilities (normally airlift or logistics) supporting USAID Bureau for Humanitarian Assistance (BHA) specific requests as approve by the U.S. Secretary of Defense. AFRICOM has responded to two disasters in the last decade (Ebola in West Africa in 2014, and Tropical Storm Idia in Mozambique in 2018), while BHA responds to dozens annually. The international community and BHA are normally able to respond to most disasters without DoD support. It is only the sudden onset catastrophic disasters overwhelming international community that require DoD support.
- >Humanitarian and Civic Assistance: Humanitarian and Civic Assistance (HCA) activities are conducted in conjunction with authorized operations and exercises of the military services in a foreign country, with the approval of the partner nation national and local civilian authorities, and complement - not duplicate - other forms of humanitarian assistance provided to the partner nation by the Department of State and USAID. Funded by AFRICOM, these activities also serve the basic economic and social needs of the partner nation and promote the security and foreign policy interests of the U.S., the security interests of the country in which the activities are to be performed, and the specific operational readiness skills of the service members who participate in the HCA activities.
- >Humanitarian Assistance – Disaster Preparedness Program: The Disaster Preparedness Program (DPP) increases the capacity of African nations to mitigate and prepare for an all-hazard disaster response within the ministry designated to respond. The program supports civilian-military interface, and enhancing collaboration and the military’s ability to perform their civil support functions. It also improves the capacity for regional interaction and stability in the event of a complex emergency such as a pandemic event. Working with national and regional entities in a comprehensive, holistic manner, the program builds capacity and capability over time. Funded by the Overseas Humanitarian, Disaster and Civic Aid appropriation (OHDACA), the DPP may provide training, planning support, technical assistance, exercise validation, and equipment purchases.
- >Humanitarian Mine Action: The Humanitarian Mine Action (HMA) program relieves human suffering and the adverse effects of land mines and other explosive remnants of war on noncombatants - including ammunition stockpiles - while advancing theater campaign plan strategies and U.S. national security objectives. The Department of Defense supports foreign governments in detection, clearance, physical security, and stockpile management of landmines and other explosive remnants of war by executing cadre development programs designed to develop capabilities for a wide range of HMA activities including education, training, and technical assistance.
- >Humanitarian Assistance – Other: U.S. Africa Command’s Humanitarian Assistance - Other (HA-O) program includes activities designed to relieve or reduce endemic conditions such as human suffering, disease, hunger, and privation, particularly in regions where humanitarian needs may pose major challenges to stability, prosperity, and respect for universal human values. These program activities are funded by the Overseas Humanitarian, Disaster and Civic Aid appropriation (OHDACA), and address basic healthcare, education, and infrastructure needs. Common projects include construction of health clinics, schools, and provision of humanitarian supplies, and are intended to reduce the risk of, prepare for, mitigate the consequences of, or respond to humanitarian disasters.
- >Pandemic Response Program: Since 2008 U.S. Africa Command has worked with the U.S. Agency for International Development to establish a Pandemic Response Program (PRP) aimed at assisting African militaries develop influenza pandemic response plans that are integrated into their country’s overall national response plans. Militaries can play key roles in the event of a pandemic, working in collaboration with other governmental, non-governmental and international organizations to maintain security, provide logistical support for food, medicine and other commodities, maintain communications, and provide augmented medical care. PRP strives to improve the capacity for regional stability in the event of a complex emergency by providing training and technical assistance, and identifies - and at times purchases - limited equipment needed for selected countries.
- >Department of Defense HIV/AIDS Prevention Program (DHAPP): The Department of Defense HIV/AIDS Prevention Program is the DoD initiative in support of the President's Emergency Plan for AIDS Relief (PEPFAR) that aims to support healthy and functional military forces to provide stability and safety to national and regional populations. Africa’s high rates of HIV/AIDS negatively impact African militaries and other uniformed organizations by reducing readiness, limiting peacekeeping deployments, and increasing risk to military and civilian personnel. DHAPP provides military-to-military program support by assisting in the development and implementation of culturally focused, military-specific HIV prevention, care and treatment programs. AFRICOM provides oversight and strategic guidance so that DHAPP can develop and implement a culturally focused, military-specific HIV prevention, care and treatment program. At over $100 million annually and operating in 38 countries, DHAPP is AFRICOM’s largest program on the Continent.
Current strategies and interventions employed by DHAPP include: Index case HIV testing (testing spouses, sexual partners, and all children of women who test HIV-positive); Documentation of every new HIV-positive individual and linking him or her into care and treatment; Periodically updating military HIV policies to address HIV testing strategies, chain of command notifications, deployments, stigma and discrimination, and antiretroviral treatment initiation and retention to reflect changes in international normative guidance; Antiretroviral treatment services thru mobile units; Condom and lubricant (where feasible) promotion, skills building, and facilitated access to condoms; Promotion of voluntary medical male circumcision services which can reduce the risk of acquiring HIV infection in HIV-negative men by 60%; and stigma and discrimination prevention training.
- The US Department of Defense offers legal education to any nation who requests, through the [Defense Institute of International Legal Studies (DIILS)](https://www.youtube.com/watch?v=zEpHRVqEgs4). A highly effective program that tailors to the specific host country. Members of the a foreign Military may visit the US, in Resident programs, or, the US may conduct workshops within the Country. These cover a [wide-varity](https://globalnetplatform.org/system/files/diils_2020_catalog_no_contacts.pdf) of legal issues: Human rights law, military justice, equal rights, etc. It has seen [major success](https://youtu.be/zEpHRVqEgs4?t=497), over a decade, DILLS worked with a number of African nations on justice reform, and methods to investigate and prosecute military personnel for sexual violent and gender-based crimes within the military. This sustained effort saw a sharp decline in sexual assault cases, an increase in successful investigations and prosecutions. These offer the ability to increase civilian oversight of the military, to either enhance, or develop their legal framework.
- Between 1992 and 1994, the United States Military worked with the United Nations in [humanitarian](https://history.army.mil/html/documents/somalia/SomaliaAAR.pdf) operations in Somalia, to combat famine during the civil war. This proved to initially be [successful](https://www.jcs.mil/Portals/36/Documents/History/Monographs/Somalia.pdf) in its core mission, "The efforts of UNITAF could be rated a success in the sense that, when UNOSOM took over on 4 May 1993, Mogadishu was calm, heavy weapons had been stored in cantonments, and marauding gangs were suppressed. Food supplies were flowing, starvation practically had ceased, drought eased, and seeds and livestock were being replenished."
- CIA had [no involvement](https://www.fordlibrarymuseum.gov/library/document/0005/7324009.pdf) in Prime Minster Patrice Lumumba's death in 1961.
### Europe
- It has been alleged that Abu Omar subject to a CIA rendition in Italy in 2003. There has been 0 evidence to confirm the allegation. However, even if it were true, the rendition is perfectly legal under international law. Indeed, the Italian judicial system [violated international law](https://harvardnsj.org/2010/11/all-human-rights-are-equal-but-some-are-more-equal-than-others-the-extraordinary-rendition-of-a-terror-suspect-in-italy-the-nato-sofa-and-human-rights/), in respect to human rights.
- In 1999, the United States & NATO engaged in major [military operation](https://www.airforcemag.com/PDF/DocumentFile/Documents/2005/Kosovo_013100.pdf) for 78 days—to end the atrocities committed by the Serbian regime in Kosovo. The major goals were:
- Ensuring the stability of Eastern Europe. Serb aggression in Kosovo directly threatened peace throughout the Balkans and thereby the stability of all of southern Europe. There was no natural boundary to this violence, which had already moved through Slovenia and Croatia to Bosnia.
- Thwarting ethnic cleasning. The Belgrade regime's cruel repressio in Kosovo, driving thousands from their homes, created a humanitarian crisis of staggering proportions. Milosevic's campaign, which he dubbed "Operation Horseshoe", would have led to even more homeless, starvation, and loss of life had his ruthlessness gone unchecked.
- Ensuring NATO's credability. The Federal Republic of Yugoslavia and the Republic of Serbia signed agreements in October 1998 that were to be verified by the Organization for Security and Cooperation in Europe and monitored by NATO. in the period leading up to March 1999, Serbian forces increasingly and flagrantly violated these agreements. Had NATO not responded to Milosevic's defiance and his campaign of ethnic cleansing, its credability would have have been called into question.
The US/NATO campaign, Operation Allied Force—was in [full compliance with international law](https://archive.org/details/legalethicalless78wall/mode/2up).
Indeed, the International Tribunal has ruled all aspects of the campaign were [lawful](https://www.icty.org/en/press/final-report-prosecutor-committee-established-review-nato-bombing-campaign-against-federal#IVB4).
- In 1995, NATO launched [Operation Deliberate Force](https://www.airforcemag.com/article/1097deliberate/). The air campaign resulted in few civilian casualties, and ended the civil conflict. Indeed, experts [have documented](https://www.airuniversity.af.edu/Portals/10/AUPress/Books/B_0074_OWEN_DELIBERATE_FORCE.pdf) the Operation's efforts to avoid civilian casualties and applaud its efforts and results, "constraints on force application entailed avoidingcollateral effects and unintended consequences that would becounterproductive to the political peace process. This effort toavoid collateral and unintended damage extended not only to the surrounding physical targets but also to concerns aboutfratricide, refugees, and noncombatant civilian casualties.2 Theneed for precision offensive air operations (OAS) platforms andweapons to limit collateral damage while accomplishinh mission objectives became an overriding concern during the Balkans air campaign. Thus, precision-guided munitions (PGM) became the overwhelming weapons of choice during air strike operations. Indeed, Deliberate Force became the first air campaign in history to employ more precision-guided bombs andmissiles than unguided ones."
- It has been alleged that the CIA supported right-wing terror groups in Italy from the 50s to the 90s, under "Operation Gladio". This has been a long-debunked, [Soviet propaganda piece](https://www.scribd.com/document/114855262/Misinformation-About-Gladio-Stay-Behind-Networks-Resurfaces).
- The list claims the CIA installed Georgious Papadopoulos in a Greece military coup in 1967. The list cited a wiki entry that contradicts the allegation, and confirms it was just that: An allegation. The wiki entry states, "during William Colby's confirmation hearing to be Director of Central Intelligence, Colby was asked by Stuart Symington, chairman of the United States Senate Committee on Armed Services, if there was any justification for the assertions. Colby [replied](https://babel.hathitrust.org/cgi/pt?id=mdp.39015074749253&view=2up&seq=7) that he had the allegations researched and found that the CIA had not engineered the coup, Papadopoulos was not an agent of the CIA, and that Papadopoulos was never paid by the CIA."
- In 1956, the U2 spy plane flew into the Soviet Union. Fully [legal](https://core.ac.uk/download/pdf/147637917.pdf) under [international law](https://scholar.smu.edu/cgi/viewcontent.cgi?referer=&httpsredir=1&article=3108&context=jalc), the plane was seen as a success in its missions. Some have claimed, without evidence, it was used to support (unspecified) crimes. Nothing in its [history](https://www.archives.gov/files/declassification/iscap/pdf/2014-004-doc01.pdf) details any criminal support. The Open Skies Treaty also [permits](https://www.osce.org/library/14127) such activities.
- It has been alleged that the CIA, from 1948 onwards, had an operation called, "mockingbird" as an operation to manipulate media domestically and abroad. This is a hoax. As confirmed in the CIA's '[Family Jewels](https://web.archive.org/web/20201101104822/https://www.cia.gov/open/Family%20Jewels.pdf)', all Mockingbird was, was a wiretap on two journalists for a few months as they were suspected of making public some classified information. "During the period from 12 March 1963 to 15 June 1963, this office installed telephone taps on two Washington-based newsmen who were suspected of disclosing classified information..." This activity was also [lawful](https://www.repository.law.indiana.edu/cgi/viewcontent.cgi?article=1108&context=ilj) at the time, ad would be today.
- It was alleged that the CIA's predecessor, OSS—was involved in aiding Nazi war criminals to further US Scientific inquiry and Intelligence operations. This is a [distortion](https://web.archive.org/web/20201018014445/https://www.cia.gov/library/center-for-the-study-of-intelligence/kent-csi/vol40no5/pdf/v40i5a12p.pdf) of truth. It has been confirmed by the CIA, DOJ and DoD that there was no operation to rescue criminals from prosecution. Indeed the opposite is true, these bodies worked hard to bring justice to many of these criminals. The CIA, [more than any](https://ia801301.us.archive.org/17/items/EagleAndSwastika/Eagle%20and%20Swastika.pdf), aided in bringing such justice in aiding the DOJ's Office of Special Investigations.
- During and after WW2, US and allied forces investigated allegations against their own forces. Rape, murder, detainee abuse, etc. Against civiians and German soldier. These efforts resulted in thousands of US and allied service members being charged and convicted, some of whom sentenced to life in prison for violating international law. See:
[E.T.O. Board of Review](https://www.loc.gov/rr/frd/Military_Law/pdf/ETO-BOR_Vol-31.pdf)
The General Board, E.T.O. War Crimes and Punishment of War Criminals [report](https://web.archive.org/web/20161223233956/http://usacac.army.mil/cac2/cgsc/carl/eto/eto-086.pdf)
[NARA](https://historyhub.history.gov/thread/2367) records containing many investigations.
- At the end of World War II, the US undertook, with allied forces, an unprecedented effort to remove the stain of Nazism from Germany, and rebuild the nation.
This collosal effort has been well document, in particular on how the US provided care to local populations that were liberated, as well as after hostilities ended. Of note was their US' efforts to combat hunger, disease outbreaks, etc. As detailed in this authoritative, independent [Official History](https://collections.nlm.nih.gov/bookviewer?PID=nlm:nlmuid-9009947-bk#page/570/mode/2up) from the Medical Department, US Army.
- The Rheinwiesenlager (Rhine meadow camps) were a group of 19 US prison camps built in the Allied-occupied part of Germany to hold captured German soldiers at the close of the Second World War. The US and allied forces did their best to [maintain compliance with international law, and did](https://collections.nlm.nih.gov/bookviewer?PID=nlm:nlmuid-1278003RX7-mvpart#page/366/mode/2up), with regards to detention operations of captive Germans. However, due to unforeseen issues such as the overwhelming numbers of German troop surrender, far more than planned—the Allied forces struggled to maintain sanitation conditions and other needs. They did improve overtime, but struggled. No Geneva violations occured.
- In April 1945, the German [Concentration camp](https://www.eisenhowerlibrary.gov/sites/default/files/research/online-documents/holocaust/report-dachau.pdf) Dachau was liberated by US forces. The 45th Infantry Div executed 21 German POWs. 17 SS were segregated and shot. Another seperate incident involved two US soldiers killing 4 German guards. This was substantiated upon an independent [investigation](https://www.metrolibrary.org/archives/document/2020/02/45th-infantry-memorandum-inspector-general-seventh-army-regarding-dachau) by the Seventh Army's Inspector General which refuted the rational, justified and lawful explanation by Walsh.
- In the Feburary 1945, the United States Air Forced lawfully bombed military targets in [Dresden](https://media.defense.gov/2011/Feb/08/2001329907/-1/-1/0/Bombings%20of%20Dresden.pdf). Numerous scholars have [detailed](https://www.raf.mod.uk/what-we-do/centre-for-air-and-space-power-studies/documents1/air-power-review-vol-13-no-3/) the legal regime during this period—ultimately concluding the Allied bombing campaign to be [lawful](https://law.unimelb.edu.au/__data/assets/pdf_file/0009/3567438/Bennett.pdf).
- On Janurary 22, 1944, the United States set up the [War Refugee Board](https://archives.jdc.org/topic-guides/jdc-and-the-u-s-war-refugee-board-1944-45/) to coordinate a systematic, formal response to aid Jews from the Holocaust.
- In Sicily, 1943, at the Biscari airfield, Sergeant Horace T. West of the 180th Infantry Regiment, singlehandedly murdered 37 POWs. This was reported by LTC William E. King, the Division Chaplain. At this same location, though hours apart, CPT John T. Compton ordered a few of his men to kill a 36 POWs. Both cases were independently investigated and corroborated. Major General Troy H. Middleton convened a general court-martial for both men. West was found guilty, sentenced to life in prison. Compton's men didn't face Court-martial, since they acted under the orders of Compton, per Field Manual (FM) 27-10, Rules of Land Warfare, "Individuals of the armed forces will not be punished for these offenses in case they are committed under orders or sanction of their government or commanders. The commanders ordering the commission of such acts, or under whose authority they are committed by their troops, may be punished by the belligerent into whose hands they may fall." However, this also provided a defense in Compton's case—as, he claimed he was acting under the orders of General Patton. General Patton was cleared of wrong-doing by a seperate IG investigation. His speech didn't order killing of POWs, however it was misinterpreted as such. Since Compton thought he was acting on orders in good faith. [1](https://www.loc.gov/rr/frd/Military_Law/pdf/03-2013.pdf)
### Asia
- The 1970s-80s position on Khmer Rouge is compliated, spanning several years. For this reason, I'll quote at length from a deep-dive [study](https://www.ushmm.org/m/pdfs/Todd_Buchwald_Report_031819.pdf) on how the US addresses genocides over several decades, and why it takes certain actions over others. At no point did the US acually support, covertly or otherwise, Khmer Rouge.
"The Cambodia case is complicated. There is a widespread public understanding that the atrocities committed by the Khmer Rouge government during its 1975-1978 rule constituted genocide, but a large portion of its atrocities were directed against the “wrong” kinds of groups—political and social groups, as opposed to “national, ethnical, racial or religious” groups—to fit neatly into the definition of genocide in the 1948 Convention. Indeed, only over time did it become well-understood that some of the atrocities—such as those directed against the ethnic Vietnamese and Cham—fit within the Convention’s definition.
State Department lawyers recognized early the potential gap between the abuses and the Genocide Convention, and they expressed doubts internally that, at least on the basis of the facts as then known, the Khmer Rouge atrocities constituted genocide.162 Nevertheless, in September 1978, they proactively sought to stir the British government’s interest in bringing a formal genocide case against Cambodia in the Inter-national Court of Justice, telling their UK colleagues that the negative publicity generated by an ICJ case could inhibit further atrocities.163 In the end, the British lawyers concluded the substance of the allegation was too doubtful and declined to move forward with an ICJ case.164 As the Carter administration faced pressure to make clear how its human rights policy applied to this gravest of cases, its rhetorical condem-nation of the Khmer Rouge came to include, on a handful of occasions, statements that at least obliquely characterized Khmer Rouge abuses as genocide.165
Vietnam’s invasion of Cambodia in December 1978 changed the geopolitical context. The Khmer Rouge were ousted and a government aligned with the Soviet Union was installed at a time when US ties with Moscow were fraught and relations with China were stronger. This shift in power created strong incen-tives for the United States to tamp down its rhetoric regarding the Khmer Rouge, as part of a broader decision by the United States to support the Cambodian opposition—which included the Khmer Rouge—in opposing Vietnam’s invasion as unlawful aggression. This extended to supporting the seating of Pol Pot’s ousted regime to continue representing Cambodia in the United Nations.166 Fearful of reinforcing Vietnam’s argument that the Khmer Rouge’s crimes had justified its invasion, Carter administration officials appear to have ceased alluding to the ex-regime’s atrocities as genocide from early 1979, and in a number of instances instead used the term to describe the conduct of the Vietnam-backed successor government.167 Reagan Administration officials did use genocide language regarding the Khmer Rouge from time to time thereafter, though usually in the context of general statements about atrocities or Communist rule, rather than statements focused on Cambodia.168 Through all this, however, the State Department’s Office of the Legal Adviser had never formally concluded that the Khmer Rouge atrocities in fact fell within the definition of genocide.169
The US government ultimately confronted the issue in a more systematic way in connection with the Cambodian peace talks that began with a multinational conference held in Paris in 1989, and continued in New York, Beijing, Jakarta, and elsewhere. In preparing for those peace talks and the negotiations of arrangements for power sharing in a potential transitional government, the US participants anticipated that the Vietnamese and their Cambodian allies would take every opportunity to justify the invasion—and the exclusion of the Khmer Rouge from a future government—by claiming that the invasion had saved Cambodia from “genocide” while, for their part, the Cambodian opposition would insist on character-izing the main issue as Vietnamese “settlers”—those who had come to Cambodia after the invasion and symbolized Vietnamese hegemony over the country. The twin issues of “genocide” and “settlers” perme-ated much of the 1989 conference and, predictably, the two sides were unable to agree on mention of the words.170 For its part, the United States saw no advantage in intervening in the debate and avoided stating a formal view on whether the atrocities constituted genocide.171
After the 1989 conference ended without an agreement, key members of Congress sharply criticized the administration’s approach. They had expressed concern as early as 1979 that the Khmer Rouge were likely to fight their way back into power if Vietnam withdrew its forces from Cambodia without appro-priate arrangements in place to exclude them.172 As Vietnamese withdrawal now loomed, they expressed alarm that the US government was not taking a sufficiently hardline posture in ensuring arrangements that would prevent the Khmer Rouge from regaining power. At a House Foreign Affairs Subcommittee hearing in September 1989, Chairman Stephen Solarz and Congressman Chester Atkins raised partic-ular concerns that the United States in Paris had not supported draft language that the Khmer Rouge was responsible for genocide—the deletion of which Atkins, at least, saw as giving the group legitimacy and facilitating its entry into a transitional government.173 They pressed Assistant Secretary of State for East Asian and Pacific Affairs Richard Solomon to say at the hearing whether “what happened in Cambodia between 1975 and 1979 can appropriately be characterized as genocide.” Solomon declined to provide a direct answer, saying that the legal definition was complex and that in any event there were practical concerns that using the word would bolster the Vietnamese negotiating position in the talks. Solomon’s unwillingness to use the word “genocide” appeared to fuel the Congressmen’s concerns about the US government’s posture toward the Khmer Rouge’s participation in a new government.174
At a hearing two months later where Solomon’s deputy and the department’s deputy legal adviser testi-fied, Solarz and Atkins pressed the point again, as it had been anticipated they would. US officials had discussed how to answer these questions after the September hearing, though different participants have different recollections of the decision-making process. Unlike the later cases in Bosnia and Rwanda, it appears that no formal memorandum was prepared for approval by the secretary of state.175 In any event, the deputy legal adviser, Michael Young, testified that the Khmer Rouge had committed genocide, but said that he wanted to qualify his answer to make clear that the term “genocide” “seemed some-what under-inclusive for what [the Khmer Rouge] actually did.”176 Apparently perceiving even Young’s remarks as evasive, an annoyed Congressman Atkins cut off the explanation, saying that he had had enough of “namby-pamby sensitivities.”177
The resistance to what Congressman Atkins viewed as parsing of the words by the administration witness was in some ways a harbinger of what we will see in later situations in which advocates became impa-tient with anything they perceived as equivocation. In any event, the State Department provided a formal written answer after the hearing that made clear the point that the deputy legal adviser had wanted to make—i.e., that it was only the attacks against particular groups that constituted genocide. His answer stated —
>The Convention’s definition of genocide does not, however, address the full extent of atroci-ties committed by members of the Khmer Rouge. Mass murder not intended to destroy any of [the groups mentioned] is not genocide under the Convention, regardless of the numbers killed. Because much of the Khmer Rouge slaughter was random, politically motivated, or the result of harsh conditions imposed on society at large, many acts would probably not constitute genocide as defined in the Convention.
- In the 1975 Australian Constitutional Crisis, CIA nor Royal Crown had any involvement in the dismisal. All historians and investigations confirm this is an unsupported [conspiracy theory](https://www.aspistrategist.org.au/arthur-tange-the-cia-and-the-dismissal/).
- During the Vietnam war, the US deployed herbicides to allow better troop movement in the jungle. This was known as Operation Ranch Hand.
Unknown to the US, one of its agents, agent orange, was toxic. Agent Orange was actually safe, however, a contamination issue occurred during the manufacture of 2,4,5,T. This was what was toxic: 2,3,7,8- tetrachlorodibenzo-p-dioxin (TCDD). [Contamination](https://www.springer.com/gp/book/9780306422478) was between less than [0.05 to almost 50 parts per million, with a mean of about 2 parts per million](https://www.nal.usda.gov/exhibits/speccoll/items/show/1318). Allegations that it was used to harm/kill combatants or civilians is [false](https://2009-2017.state.gov/documents/organization/98481.pdf). The US did deploy one of its agents [_briefly_ to target _few, select_ crops belonging to the viet cong](https://media.defense.gov/2010/Sep/28/2001329797/-1/-1/0/AFD-100928-054.pdf). The Americans were very relectent to do this, however, South Vietnam insisted its use. The US only accepted under very strict controls & criteria, and if the South Government would gurantee humanitarian supplies should it be needed.
- In July 1972, the Hanoi propaganda effort ramped up, claiming the US deliberately attacked several Dikes, causing civilian casualties. However, an [independent, internal review](https://www.cia.gov/readingroom/docs/CIA-RDP85T00875R001700040062-8.pdf) confirmed this not to be the case. "A study of available photography shows conclusively that there has been no concerted and intentional bombing of North Vietnam's vital dike system. A few dikes have been hit, apparently by stray bombs directed at military-associated targets nearby. The observable damage is minor and no major dike has been breached."
- Operation Linebacker 1, from May 9 to October 23, 1972 and Operation Linebacker 2, from December 18 to December 29, 1972 were bombing campaigns against North Vietnam. North Vietnam illegally invaded South Vietnam, which triggered Operation Linebacker 1, targeting their military supply lines, etc. This was a successful effort in forcing the North to the peace table. However, the North Vietnam Government stalled peace talks, while trying to secretly build their forces. This prompted the Nixon Admin to begin Linebacker 2. A shorter campaign that while effective, was surrounded by disinformation alleging "indiscriminate targeting of civilians". An [independent assessment](https://archive.org/details/DTIC_ADA191278/page/n1/mode/2up) concludes, "that the Linebacker campaigns were militarily effective and that, had AFP 110-31 been in effect in 1972, the campaigns, as they were actually conducted, would have conformed to the pamphlet's restrictions on aerial bombardment. These campaigns demonstrate that the pamphlet's rules on aerial bombardment are practical and can be complied with, given the proper technology and a conscious effortby commanders, their staffs, and aircrews."
A [scholarly paper](https://www.airuniversity.af.edu/Portals/10/ASPJ/journals/1983_Vol34_No1-6/1983_Vol34_No2.pdf) from W. Hays Park, a world-leading LOAC expert, also confirms these operations were in compliance with international law, and details the efforts to mitigate collateral damage and civilian casualties. He concludes, "Both Linebacker campaigns were also conducted with anacute awareness by the military of its responsibilities under the law of war, with mission parameters well within the prohibitions of the law. Although unprecedented in the degree of precaution taken by an attacker to minimize collateral injury to the civilian population of an enemy, each campaign was successful inattaining its objectives."
- In the early 1970s, allegations of CIA's complicity in illegal drug trafficking in Laos (and the broader Golden Triangle). One such popular purpetrator of this lie was Alfred W. McCoy's 'The politics of heroin in Southeast Asia'. However, this book, and media claims of this were far from the facts of reality. CIA Headquaters and Stations in Asia actively pressured the resistance groups they aided from engaging in such activities, such as driving the Yao chieftain Chao out of the buisiness; the Agency also made sure no US assets would be used for illegal smuggling. CIA's sensitivities to the illegal activity was so great, that one "acting chief of security once proposed a sting operation, with narcotics on an Air America plane going to Saigon used to lure traffickers there into a trap. Devlin imagined the press hysteria that would result if word got out about drugs moving on the CIA's airline, and he rejected the idea on the spot." Other details of CIA efforts to counter the narcotics smuggling can be found in the declassified book, '[Undercover Armies, CIA and Surrogate Warfare in Laos](https://nsarchive2.gwu.edu/NSAEBB/NSAEBB284/6-UNDERCOVER_ARMIES.pdf)'
- In 1970, in Cambodia, the CIA had no involvement in Prince Sihanouk's coup. The list's own wiki citation even admits there is no evidence.
- In 1965, the United States with South Vietnam the air campaign under the [Rolling Thunder program](https://www.cia.gov/readingroom/docs/CIA-RDP78T02095R000900070018-0.pdf). This program resulted in [effective military gains](https://www.cia.gov/readingroom/docs/CIA-RDP79T00472A000800020017-1.pdf), while producing very few civilian casualties: Between [3,900 and 5,400](https://www.cia.gov/readingroom/docs/CIA-RDP78T02095R000900070009-0.pdf) and [34,000, of which 21,000 were killed](https://www.cia.gov/readingroom/docs/CIA-RDP78S02149R000200020003-4.pdf) by then-standards. The second study reviews all propaganda claims made by the North Vietnam regime and concludes most of them false and inaccurate. The purpose of the program was to impede the North regime's supply of weapons and men to aid insurgent groups in the South, and in the long-term make continued physical support to insurgents too costly for North Vietnam.
Another detailed overview of the program can be found [here](https://www.cia.gov/readingroom/docs/CIA-RDP80T01629R000300080014-9.pdf) From target selection to casualty estimates, to goals, etc. A [study](https://web.archive.org/web/20161106133619/http://www.airpower.maxwell.af.mil/airchronicles/aureview/1982/jan-feb/parks.html) by one of the world's leading law of war experts, concludes that it complied with, and far exceeded international law,"Rolling Thunder was one of the most constrained military campaigns in history. The restrictions imposed by this nation’s civilian leaders were not based on the law of war but on an obvious ignorance of the law —to the detriment of those sent forth to battle."
- Many pundits and historical revisionists allege the US was behind the 1965 coup in Indonesia. The 30 September Movement. This couldn't be furthest from the truth. In the declassified publication, _[The lessons of the September 30 affair](https://web.archive.org/web/20201017175932/https://www.cia.gov/library/center-for-the-study-of-intelligence/kent-csi/vol14no2/pdf/v14i2a02p.pdf)_ a fantastic summary of events is detailed, however a brief mention to the largest, comprehensive and authoritative study is summized, "In her study _[The Coup that backfired](https://web.archive.org/web/20171208040813/https://www.cia.gov/library/readingroom/docs/esau-40.pdf)_, Ms Helen Hunter went a long way toward dispelling the myth of the Chinese Communist involvement in the purge attempt. She concluded that while Peking had probable learned of the Sukarno/PKI plan, as indeed it must have through agent penetration of the Palace and the PKI, the Chinese did not instigate the plot or particupate in carrying it out. The same conclision is implicit in an earlier article in _studies in Intelligence_ in _[The Steptember 30 Movement](https://web.archive.org/web/20170123064222/https://www.cia.gov/library/readingroom/docs/CIA-RDP78T03194A000300010008-4.pdf)_ by John T. Pizzicaro.
Like us, the Chinese knew something important was imminent. But I doubt whether they could truly have comprehended the nature of the plot and its implications."
CIA had [no involvement](https://www.fordlibrarymuseum.gov/library/document/0005/7324009.pdf) in the assassination is also confirmed by the declassiied Rockefeller commission.
- The Vietnam war and the US' entire air campaign; counter to many historical revisionists, was actually hampered by strict Rules of Engagement that often left the Military allowing the Vietcong to remain safe, even though they're far clear of any surrounding civilian populations. In another [scholarly paper](https://www.loc.gov/law/mlr/Military_Law_Review/27687D~1.pdf) by a world-leading legal expert and practitioner, it was found while studying Air Force ROEs, "the policy of gradualism, implemented by the Rolling Thunder bombing campaign over North Vietnam between 1965 and 1968, resulted in ROE of unprecedented detail and restrictiveness." Indeed, an [internal air force study](https://archive.org/details/DTIC_ADA597620/page/n1/mode/2up) prior concluded the same, "military barracks were prohibited. The suppression of SAMS and gun-laying radar systems was prohibited in this area as were attacks on NVN air bases from which attacking aircraft might be operating."
- In 1950, it was alleged that A US airstrike deliberately targeted South Korean refugees in the village of Nogeun-ri.
An [independent and authoritative investigation](https://permanent.access.gpo.gov/websites/armymil/www.army.mil/nogunri/default.htm) summarised as follows:
"Over the last year, the Review Team has conducted an exhaustive factual review by examining over a million documents from the National Archives, conducting interviews with approximately 200 American witnesses, and analyzing the interview transcripts and oral statements of approximately 75 Korean witnesses. The U.S. Review Team also closely examined press reports, aerial imagery, and other forensic examination results. This U.S. Report reflects the U.S. Review Team’s factual findings based upon all the evidence available on the incident. During late July 1950, Korean civilians were caught between withdrawing U.S. forces and attacking enemy forces. As a result of U.S. actions during the Korean War in the last week of July 1950, Korean civilians were killed and injured in the vicinity of No Gun Ri. The Review Team did not find that the Korean deaths and injuries occurred exactly as described in the Korean account. To appraise these events, it is necessary to recall the circumstances of the period. U.S. forces on occupation duty in Japan, mostly without training for, or experience in, combat were suddenly ordered to join ROK forces in defending against a determined assault by well-armed and well-trained NKPA forces employing both conventional and guerilla warfare tactics. The U.S. troops had to give up position after position. In the week beginning July 25, 1950, the 1st Cavalry Division, withdrawing from Yongdong toward the Naktong River, passed through the vicinity of No Gun Ri. Earlier, roads and trails in South Korea had been choked with civilians fleeing south. Disguised NKPA soldiers had mingled with these refugees. U.S. and ROK commanders had published a policy designed to limit the threat from NKPA infiltrators, to protect U.S. forces from attacks from the rear, and to prevent civilians from interfering with the flow of supplies and troops. The ROK National Police were supposed to control and strictly limit the movements of innocent refugees.
In these circumstances, especially given the fact that many of the U.S. soldiers lacked combat-experienced officers and Non-commissioned officers, some soldiers may have fired out of fear in response to a perceived enemy threat without considering the possibility that they might be firing on Korean civilians."
- In 1950s, The Soviet Union, China and North Korea started propaganda that the US had used Biological weapons against civilians and combatants. This has been a long-debunked conspiracy theory. Tactics used by China and NK include the establishment of [fake Scientific panels, presenting fabricated evidence](https://digitalarchive.wilsoncenter.org/collection/250/korean-war-biological-warfare-allegations).
Other papers from [1995](https://pubmed.ncbi.nlm.nih.gov/7783939/) and even recent [declassified documents](https://web.archive.org/web/20200425205433/https://www.cia.gov/library/readingroom/docs/CIA-RDP80R01731R003300190004-6.pdf) discussing analysis of the ISC report have flaws in logic, biology and [methodology](https://cissm.umd.edu/sites/default/files/2019-07/leitenberg_biological_weapons_korea.pdf) as well as intelligence reporting about the [deliberate lies](https://assets.documentcloud.org/documents/20419558/bw-comint-baptism-files.pdf) from the USSR on the matter. This type of propaganda wasn't unique to USSR/NK/China allegations to the US. Other [countries also accused each other](https://web.archive.org/web/20190502135521/http://www.au.af.mil/au/awc/awcgate/medaspec/Ch-18electrv699.pdf) It's also worth noting that when the international community such as the ICRC and UN asked to do investigations, China, the Soviets and NK all declined.
- In 1968, My Lai was substantiated by the [Peers investigation](https://www.loc.gov/rr/frd/Military_Law/pdf/RDAR-Vol-I.pdf). Those responsible were held to account. Since then, nothing like it has returned. However the list incorrectly states it was between 347-504 civivlians killed. It was 175.
- In 1967, the South Vietnamese government operated a program called Phung Hoang or Phoenix. CIA aided in it, but it was [not theirs](https://www.cia.gov/readingroom/docs/CIA-RDP77M00144R000300130040-4.pdf). It has been calleged that it was an assassination/torture program—this is [not true](https://www.cia.gov/readingroom/docs/CIA-RDP80R01720R000800090012-8.pdf). Since independent actions against the CVI were deemed inefficient and ineffective, the Phung Hoang program was concieved to unite and coordinate a total government effort against the VCI. As such, Phung Hoand represented an intelligence coordination mechanism—in the form of coordinating committees at the province, regional and national level; and intelligence and operations coordinating centers at the province and district level—which aimed at a united total governmental effort against the CVI. It was _not_ a program of assassination or terror in response to Communist terror, and the program did not authorise torture, brutality or cruel methods in the interrogation or handling of captives. The US further worked with the Government to make sure [adequate, humane treatment as focal, observing fair concepts of due process and improve conditions of internment](https://www.cia.gov/readingroom/docs/CIA-RDP80R01720R001100060018-1.pdf).
- A series scholarly publications from the US Air Force History Office cover operations in Cambodia, Laos, North and South Vietnam, etc.
The following are a select few:
- [The United States Air Force in Southeast Asia, 1961-1973: An illustrated account](https://web.archive.org/web/20210427064250/https://apps.dtic.mil/dtic/tr/fulltext/u2/a160932.pdf)
- [Air War over South Vietnam 1968–1975](https://media.defense.gov/2010/Sep/24/2001330077/-1/-1/0/Air%20War%20Over%20South%20Vietnam%20opt.pdf)
- [The War against Trucks, Aerial Interdiction in Southern Laos 1968-1972](https://media.defense.gov/2010/Oct/06/2001329752/-1/-1/0/AFD-101006-027.pdf)
- [Interdiction in Southern Laos 1960-1968](https://media.defense.gov/2010/Sep/27/2001329814/-1/-1/0/AFD-100927-078.pdf)
- [USAF Plans and Operations: Air Campaign Against North Vietnam, 1966](https://media.defense.gov/2011/Mar/18/2001330141/-1/-1/0/AFD-110318-005.pdf)
- [The Air Force in Southeast Asia: Role of Air Power Grows, 1970](https://media.defense.gov/2011/Mar/18/2001330144/-1/-1/1/Air%20Power%20Grows%201970.pdf)
- [The United States Air Force in Southeast Asia, the war in Northern Laos: 1954-1973](https://nsarchive2.gwu.edu/NSAEBB/NSAEBB248/war_in_northern_laos.pdf)
- In 1953, an insurgent pseudo-nationalist, the Pathet Lao, under the control of North Vietnam started an insurrection against the Royal Government of Laos. Their false propaganda has been [well documented](https://www.cia.gov/readingroom/docs/CIA-RDP78-00915R000600080007-0.pdf) and widely disregarded by academics and historians. The US, responding within the [framework of the Geneva Agreements](https://www.cia.gov/readingroom/docs/CIA-RDP80R01720R001300050007-2.pdf), supplied military equipement and supplies for the Lao armed forces. This was within the provisions of Article 6 of the Protocol to the Declaration the Neutrality of Laos signed in Geneva in 1962. Because of the consistent refusal by the Pathet Lao to allow the ICC teams to enter their territory to inspect alleged violations of the Geneva agreement, the first American reconnaissance flight was flown over the southern part of Laos on 19 May 1964 after consultations with Prime Minister Souvanna Phouma the previous day. On 28 May 1964 Souvanna Phouma publically endorsd these recon missions over Laos stating that they were necessary to observe communist violations of the Accords.
- It has been alleged that the Gulf of Tonkin incident was a US false flag to justify the Vietnam war, and that it's admitted in the declassified record. This is a well-debunked myth. The list cites a wiki entry, which cites to a declassified NSA document as evidence. However, problems arise when one actually reads the document in question. 1) It's an opinion piece in NSA's Cryptologic Quaterly. 2) The author in the study actually caustions against a conspiracy theory take, "This mishandling of SIGINT was not done in a manner that can be construde as conspiratorial , that is, with manufactured evidence and collusion at all levels. Rather, the objective of these individuals was to support the Navy's claim that the Desoto patrol had been deliberately attacked by the North Veitnamese." It's worth noting as well, that the NSA, while appreciative of the study, [disagrees](https://www.nsa.gov/Portals/70/documents/news-features/declassified-documents/gulf-of-tonkin/articles/release-2/rel2_thoughts_intelligence.pdf) with the author's central premise: That SIGINT/COMINT was mishandled. According to the response, "This article does dispute Mr. Hanyok's assertion that SIGINT was mishandled, deliberately skewed or not provided to the Johnson administration. In fact, the record shows that NSA performed magnificently during this period of crisis, providing all SIGINT available in a timely manner to a broad spectrum of customers. With only a few trained Vietnamese linguists at NSA Headquarters and field stations analyzing encrypted North Vietnamese communications, NSA still provided U.S. forces advance warning of possible intended attacks that quite likely prevented the sinking of a U.S. destroyer on 2 August.
Further evidence refuting the claim that COMINT information was presented in such a manner as to preclude responsible decision makers in the Johnson administration from having the complete and objective narrative of events of 4 August 1964 can be found in the NSA review of Secretary McNamara's testimony before Congress. NSA noted that McNamara systematically used overkill language with COMINT and that the COMINT surrounding Tonkin was "flexible for interpretation". Again in 1972, as noted by Mr. Hanyok, NSA Deputy Director Dr. Tordella provided Senator Fulbright's staff director Carl Marcy access to all NSA material relating to the Gulf of Tonkin and told Mr. Marcy that the intercept of 4 August could indeed refer to events that occurred on 2 August.
These facts make it clear that NSA consistently provided the Administration, as well as Congress, all COMINT information related to the events of 2-4 August. In fact, one NSA manager present during the August 1964 events has stated, "the folks downtown were provided all of the COM INT as they wanted to do their own analysis. They weren't overly interested in what we thought." Some would argue that NSA should have explicitly informed decision makers in formal SIGINT reporting that COMINT showed there was no attack on 4 August. However, the available COMINT could not support such a position. While some analysts did indeed come to such a conclusion, the COMINT itself, as noted by Dr. Tordella, was "flexible for interpretation".
In the final analysis, it is clear that not only was SIGINT information _not_ presented in such a manner as to preclude responsible decision makers in the Johnson administration from having the complete and objective narrative of events of 4 August 1964, but that all of the COM INT produced was distributed to CIA, JCS, DIA and other customers and that NSA uncertainties, even of single words, were made known to decision makers."
- In the summer of 1950 in South Korea, South Korea engaged in a massacre. British and US Governments tried to prevent it, and managed to save a large number of civilians. United States official documents show that John J. Muccio, then United States Ambassador to South Korea, made recommendations to South Korean President Rhee Syngman and Defense Minister Shin Sung-mo that the executions be stopped. Great Britain raised this issue with the U.S. at a diplomatic level, causing Dean Rusk, Assistant Secretary of State for Far Eastern Affairs, to inform the British that U.S. commanders were doing "everything they can to curb such atrocities".[8] During the massacre, the British protected their allies and saved some citizens.
- CIA has [no involvement](https://www.archives.gov/files/research/jfk/releases/2018/104-10214-10036.pdf) in the 1963 assassination/coup in Vietnam of President Diem.
- Several studies of US post-WW2 activities, policies and views have been made public, and offer the most detailed overview of 3 decades (50s-70s) in Asia:
- _[US Intelligence and Vietnam](https://web.archive.org/web/20170123192047/https://www.cia.gov/library/readingroom/docs/DOC_0001433692.pdf)_ is an independent study designed to undertake a detailed examination of finished intelligence relating to the Vietnam conflict from the time of introduction of US combat forces in 1965 through the fall of the Saigon Government in 1975. In settling on the scope of the study, it was decided to go back to the beginning of the American involvement in Indochina toward the end of World War II and cover at least the major developments that occured during a period of approximately three decades. 1945-1975.
- A compendium, _[Estimative Products on Vietnam: 1948-1975](https://chinhnghia.com/Vietnam_1948-1975_Book.pdf)_ provides a lengthy, detailed overview before the documents.
- Thomas Ahern Jr.'s monograph, _[CIA and Rural Pacification in South Vietnam](https://nsarchive2.gwu.edu/NSAEBB/NSAEBB284/3-CIA_AND_RURAL_PACIFICATION.pdf)_ which details CIA's efforts to win the "hearts and minds" of the South Vietnamese rural population. It's a compelling account of CIA's contributions to the US effort to establish and preserve an independent nation in South Vietnam. Despite local success, the CIA effort was, in the end, part of a major tragedy. No one, either in Washington or in the field, grasped the immense complexity and difficulty in instituting a massive effort to control the contryside, win the support of the peasantry, and promote political reforms, while fighting a determined and entrenched enemy.
- _[Baptism by fire: CIA analysis of the Korean War](https://web.archive.org/web/20170911114643/https://www.cia.gov/library/publications/international-relations/korean-war-baptism-by-fire/baptism-by-fire.pdf)_ Notes, among other things, that the Truman administration believed that the USSR orchestrated the Korean War.
- History of the Joint Chiefs of Staff, _The Joint Chiefs of Staff and The War in Vietnam 1960–1968 [Part 1](https://www.jcs.mil/Portals/36/Documents/History/Vietnam/Vietnam_1960-1968_P001.pdf)_ & _[Part 2](https://www.jcs.mil/Portals/36/Documents/History/Vietnam/Vietnam_1960-1968_P002.pdf)_
- _[CIA and the House of Ngo](https://nsarchive2.gwu.edu/NSAEBB/NSAEBB284/2-CIA_AND_THE_HOUSE_OF_NGO.pdf)_ notes how the CIA aided in establishing a civilian government in South Vietnam. As Diem became more authoritarian and suppressive of minorities, the US tried to persuade him to abide by human rights, however, upon this failing, encouraged but was not involved in, the coup by the military. Ahern traces CIA efforts to bring stability and democracy to South Vietnam and to influence Diem. Although not uncritical of US policy and CIA operations, Ahern's study reveals a CIA Station-indeed in the early years, two Stations-working diligently and effectively to aid Diem in forming a viable state.
- _[CIA and the Generals](https://nsarchive2.gwu.edu/NSAEBB/NSAEBB284/1-CIA_AND_THE_GENERALS.pdf)_ "illustrates Saigon Station efforts to work with and understand the various military governments of South Vietnam which followed Diem, and carefully details CIA attempts to stabilize and urge democratization on the changing military regimes."
- In 1954, the US detonated a series of nuclear bombs to study their yield. This was part of Operation Castle. Due to a [miscalculation](https://www.osti.gov/opennet/servlets/purl/16380885-g1vuWf/16380885.pdf) (p. 205), there was an increase in radiation output than expected. The US Department of Energy estimated that 253 inhabitants of the Marshall Islands were impacted by the radioactive fallout. It is alleged that the US deliberately used the Marshallese as "ginea pigs" for testing radiation. This allegation has been throughouly investigated and is not supported by any evidence. [Operation Castle had no biomedical program](https://www.osti.gov/opennet/servlets/purl/16061854-leUIeE/16061854.pdf). US Military personnel were also exposed to large amounts of radiation, when they thought they were in safe areas of the _expected_ yield.
- In 1945, it has been alleged that Douglas MacArthur pardoned the Japanese unit 731, a unit involved in biological weapons testing.
During the interrogations for war crimes prosecutions, the members gave up information to the US, however, [no evidence](https://networks.h-net.org/node/20904/reviews/21143/fouraker-harris-factories-death-japanese-biological-warfare-1932-1945) indicates that MacArthur pardoned anyone.
- US Firebombings in Germany and Japan, as well as the use of nuclear weapons fell well within international law at the time As one of the world's leading experts [notes](https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2924907), "President Truman’s classification of the bombing as a purely military objective has caused some historians to speculate that the President engaged in “self-deception.”4 Under the mid-twentieth century military’s targeting lexicon, however, the President’s understanding of Hiroshima as a military target was accurate. Although Hiroshima was not a military base as understood today, it was a “military city” as it housed the 2d Army Headquarters, which commanded the defense of all of southern Japan.5 The city was also a communications center, a storage point, and an assembly area for troops... Nagasaki’s military industry made it significant. The atomic bomb landed between the two principal targets in the city: the Mitsubishi Steel and Arm Works and the Mitsubishi-Uramaki Ordnance Works (Torpedo Works).
The atomic strikes on Hiroshima and Nagasaki were lawful under the laws of war existing in 1945. These attacks also represent the only two instances of atomic weapon strikes in history. They illustrate the definitional confusion existing with respect to the U.S. lassification of lawful military objects exclusive of civilian objects. If some historians believe President Truman was engaged in “self-deception” in labeling Hiroshima a military target, those historians may be equally perplexed by modern American usage of law-of-war target labels."
- Between October/November 1901, during the Philippine–American War in the battle of Samar, General Jacob H. Smith is famously quoted as ordering, “I want no prisoners. I wish you to kill and burn. The more you kill and burn the better you will please me... The interior of Samar must be made a howling wilderness.”
When asked by Major Waller asked about the age of those to whom he should apply this guidance, Smith replied that males over ten years old should be considered as being capable of bearing arms. This is cited as evidence that Smith ordered unlawful killings and atrocities against the villagers. This narrative, however, ignores some key facts: When court-martialed for their actions on Samar. Waller would testify that rather than taking the order literally, his interpretation of Smith’s intemperate guidance was, “that the General wanted all insurrectos killed... people who were bearing arms against Americans... I understood that we were not to take prisoners if they were armed.” In fact, Waller testified that he cautioned his officers that “we were not sent here to make war on women and children and old men." While smith was seen as ruthless and excessively forceful, "... a circular he is-sued on 18 November 1901 specifically sought to ensure that accommodating natives were cared for: “Emphasis is laid upon the point that the brigade commander desires not only to permit proper food supplies to reach all friendly natives, but he particularly desires that these supplies do so reach them." Besides this, Smith was was "not tried for issuing illegal orders or for inciting war crimes. Instead, he was charged with 'conduct to the prejudice of good order and military discipline' for the excessive nature of his orders. A military court headed by Maj. Gen. Loyd Wheaton, who had commanded the Department of North Philippines, that convened in Manila in April 1902 found General Smith guilty of instructing Waller to “kill and burn” as much as possible and not take any prisoners. Commenting on this verdict three months later, Secretary of War Elihu Root described the language Smith was convicted of using as containing “intemperate, inconsiderate, and violent expressions, which, if accepted literally, would grossly violate the humane rules governing American armies in the field.” But the court exercised leniency and sentenced Smith merely to be 'admonished by the reviewing authority.' It justified this outcome by concluding that Smith “did not mean everything that his unexplained language implied; that his subordinates did not gather such a meaning; and that the orders were never executed in such sense.” Root commented, “Fortunately they [Smith’s instructions] were not taken literally and were not followed. No women or children or helpless persons or noncombatants or prisoners were put to death in pursuance of them." Smith was still forced out of the Military for his actions. Others were also convicted and served life in prison for unlawful acts unrelated to Smith. [1](https://www.jstor.org/stable/26296824?seq=2#metadata_info_tab_contents)
|
Python
|
UTF-8
| 1,521 | 2.5625 | 3 |
[] |
no_license
|
from server.dao.ign_review_dao import IGNReviewDAO
from server.db_driver import initializeDB
from server.model.ignReviewModel import IGNReviewModel
from server.read_csv import read
def setup():
initializeDB()
read()
global dao
dao = IGNReviewDAO()
def testSelect():
model = dao.select((1,))
assert isinstance(model,IGNReviewModel) == True
def testSelectAll():
models = dao.selectAll()
assert len(models) == 100
def testInsert():
isInserted = dao.insert((101,"Great","NHL 13","/games/nhl-13/xbox-360-128182","Xbox 360",8.5,"Sports","N",2012,9,11))
model = dao.select((101,))
assert model != None
assert model.scorePhrase == "Great"
assert isInserted == True
def testUpdate():
newTitle = "test"
props = ("title",)
isUpdated = dao.update((newTitle,1),props)
model = dao.select((1,))
assert isUpdated == True
assert model.title == newTitle
def testDelete():
isDeleted = dao.delete((101,))
assert isDeleted == True
def testDoubleInsert():
isInserted = dao.insert((101, "Great", "NHL 13", "/games/nhl-13/xbox-360-128182", "Xbox 360", 8.5, "Sports", "N", 2012, 9, 11))
assert isInserted == True
isInserted = dao.insert((101, "Great", "NHL 13", "/games/nhl-13/xbox-360-128182", "Xbox 360", 8.5, "Sports", "N", 2012, 9, 11))
assert isInserted == False
if __name__ == "__main__":
setup()
testSelectAll()
testSelect()
testUpdate()
testInsert()
testDelete()
testDoubleInsert()
testDelete()
|
Java
|
UTF-8
| 3,577 | 2.171875 | 2 |
[] |
no_license
|
package com.example.aciko11.tennistournaments;
import android.content.Context;
import android.content.Intent;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.example.aciko11.tennistournaments.Classes.DataStructure;
public class DefaultView extends AppCompatActivity {
Button btnShowAllPlayers,btnShowAllTournaments, btnSearchPlayer, btnSearchTournament;
Context context;
String packageName = "com.example.aciko11.tennistournaments.";
String urlPlayers = "https://theaciko.000webhostapp.com/TournamentsApi/showPlayers.php";
String urlTournaments = "https://theaciko.000webhostapp.com/TournamentsApi/showTournaments.php";
Integer numFieldsPlayers = 3, numFieldsTournaments = 4;
String dataNamesPlayers[] = {"firstName", "lastName", "id"};
String dataNamesTournaments[] = {"tournamentName", "tournamentCity", "tournamentRegion", "id"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_default_view);
context = this;
btnShowAllPlayers = findViewById(R.id.btnShowAllPlayers);
btnShowAllTournaments = findViewById(R.id.btnShowAllTournaments);
btnSearchPlayer = findViewById(R.id.btnSearchPlayer);
btnSearchTournament = findViewById(R.id.btnSearchTournament);
btnSearchPlayer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(context, searchPlayer.class);
startActivity(intent);
}
});
btnSearchTournament.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(context, SearchTournament.class);
startActivity(intent);
}
});
btnShowAllPlayers.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(context, ResultShow.class);
DataStructure data = new DataStructure(numFieldsPlayers);
for(int i = 0; i < numFieldsPlayers; i++){
data.setName(dataNamesPlayers[i], i);
data.setValue("", i);
}
data.setJsonArrayName("Players");
data.setIsInsert(false);
intent.putExtra(packageName + "data", data);
intent.putExtra(packageName + "url", urlPlayers);
startActivity(intent);
}
});
btnShowAllTournaments.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(context, ResultShow.class);
DataStructure data = new DataStructure(numFieldsTournaments);
for(int i = 0; i < numFieldsTournaments; i++){
data.setName(dataNamesTournaments[i], i);
data.setValue("", i);
}
data.setJsonArrayName("Tournaments");
data.setIsInsert(false);
intent.putExtra(packageName + "data", data);
intent.putExtra(packageName + "url", urlTournaments);
startActivity(intent);
}
});
}
}
|
Java
|
UTF-8
| 13,738 | 1.75 | 2 |
[] |
no_license
|
package com.example.myapplication.activity;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import com.example.myapplication.SwipeDismissListViewTouchListener;
import com.example.myapplication.connectserver.ConnectServer;
import com.example.myapplication.JsonPass;
import com.example.myapplication.connectserver.SetMakeRequest;
import com.example.myapplication.listview.ListViewSetItem;
import com.example.myapplication.listview.ListViewSetWordItem;
import com.example.myapplication.listview.ListViewWordAdapter;
import com.example.myapplication.listview.ListViewWordItem;
import com.example.myapplication.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import static com.example.myapplication.MainActivity.homeBar;
import static com.example.myapplication.MainActivity.loginId;
import static com.example.myapplication.MainActivity.urlFileUpload;
import static com.example.myapplication.MainActivity.urlSetMake;
public class MakeSetActivity extends AppCompatActivity {
private final int REQ_CODE_SELECT_IMAGE = 100;
private String img_path = new String();
private Bitmap image_bitmap_copy = null;
private Bitmap image_bitmap = null;
private String imageName = null;
private int imgPos;
private ArrayList<ListViewSetWordItem> listSetWordItem;
ListViewWordAdapter adapter;
ImageButton wordAddBtn;
ImageButton makeSetBtn;
EditText setName;
private int num;
private String setRes, set_name, set_no;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_set);
///////////////////
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.permitDiskReads()
.permitDiskWrites()
.permitNetwork().build());
//////////////////
num = 0;
View homeActionBar = getLayoutInflater().inflate(R.layout.actionbar_makeset, null);
homeBar = getSupportActionBar();
homeBar.setCustomView(homeActionBar);
homeBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME |
ActionBar.DISPLAY_SHOW_CUSTOM);
ListView listview;
// Adapter 생성
adapter = new ListViewWordAdapter(this);
setName = findViewById(R.id.editSetName);
// 리스트뷰 참조 및 Adapter달기
listview = (ListView) findViewById(R.id.wordListView);
listview.setItemsCanFocus(true);
listview.setAdapter(adapter);
Intent intent = getIntent();
if (intent != null) {
Log.d("Intent", "intent is " + intent.getStringExtra("set_name"));
set_no = intent.getStringExtra("set_no");
set_name = intent.getStringExtra("set_name");
listSetWordItem = (ArrayList<ListViewSetWordItem>) intent.getSerializableExtra("itemlist");
setName.setText(set_name);
if (listSetWordItem != null) {
for (int i = 0; i < listSetWordItem.size(); i++) {
adapter.addItem(listSetWordItem.get(i).getWordA(), listSetWordItem.get(i).getWordB(), num,
listSetWordItem.get(i).getHint());
adapter.notifyDataSetChanged();
num++;
}
}
}
if(listSetWordItem == null) {
//처음 2개 단어리스트만 추가
for (int i = 0; i < 2; i++) {
adapter.addItem("", "", num, "");
adapter.notifyDataSetChanged();
num++;
}
Log.d("Intent", "intent is null");
}
SwipeDismissListViewTouchListener touchListener =
new SwipeDismissListViewTouchListener(listview,
new SwipeDismissListViewTouchListener.DismissCallbacks() {
@Override
public boolean canDismiss(int position) {
return true;
}
@Override
public void onDismiss(ListView listView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
adapter.remove(position);
}
adapter.notifyDataSetChanged();
}
});
listview.setOnTouchListener(touchListener);
listview.setOnScrollListener(touchListener.makeScrollListener());
// (+) 버튼 클릭시 word리스트 동적 추가
wordAddBtn = findViewById(R.id.wordAddBtn);
wordAddBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
adapter.addItem("", "", num, "");
adapter.notifyDataSetChanged();
num++;
}
});
// ㄴ 버튼 클릭시 word리스트 받아서 세트 만들기
makeSetBtn = findViewById(R.id.makeSetBtn);
makeSetBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//setName = findViewById(R.id.editSetName);
String name = setName.getText().toString();
ArrayList<ListViewWordItem> totalSetList = (ArrayList) adapter.getSetList();
boolean result = true;
if (name.equals("")) {
//name이 비어있다.
Toast.makeText(getApplicationContext(), "제목을 입력해주세요", Toast.LENGTH_SHORT).show();
} else if (!name.equals("")) {
for (int i = 0; i < totalSetList.size(); i++) {
//word가 비어있다.
if (totalSetList.get(i).getWordA().equals("") || totalSetList.get(i).getWordB().equals("")) {
Toast.makeText(getApplicationContext(), "단어를 모두 입력해주세요", Toast.LENGTH_SHORT).show();
result = false;
}
}
if (result == true) {
JsonPass j = new JsonPass();
JSONObject jsonSet = j.jsonSetPass(totalSetList, name, loginId);
ConnectServer connectServer = new ConnectServer();
setRes = connectServer.setMakeRequest(urlSetMake, jsonSet);
for (int i = 0; i < totalSetList.size(); i++) {
if (totalSetList.get(i).getImgPath() != null) {
Log.d("MakeSetActivity", "imgName is " + totalSetList.get(i).getImgName());
connectServer.DoFileUpload(urlFileUpload, totalSetList.get(i).getImgPath());
}
}
//res는 성공하면 set_no 실패하면 x (제목이 겹친다.)
if (!setRes.equals("x")) {
int no = Integer.parseInt(setRes.trim());
Log.d("makeSet", "set_no is " + no);
Intent intent = new Intent(getApplicationContext(), SetInfoActivity.class);
intent.putExtra("set_no", no);
intent.putExtra("set_name", name);
intent.putExtra("owner_id", loginId);
intent.putExtra("user_id", loginId);
intent.putExtra("word_cnt", "단어");
startActivity(intent);
finish();
} else if (setRes.equals("x")) {
Toast.makeText(getApplicationContext(), "제목이 중복되었습니다", Toast.LENGTH_SHORT).show();
}
}
}
}
});
}//onCreat 끝
public void cameraON(int position) {
Log.d("BUTTON", "BUTTON CLICK " + position);
this.imgPos = position;
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(MediaStore.Images.Media.CONTENT_TYPE);
intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQ_CODE_SELECT_IMAGE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Toast.makeText(getBaseContext(), "resultCode : " + data, Toast.LENGTH_SHORT).show();
if (requestCode == REQ_CODE_SELECT_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
try {
img_path = getImagePathToUri(data.getData()); //이미지의 URI를 얻어 경로값으로 반환.
Toast.makeText(getBaseContext(), "img_path : " + img_path, Toast.LENGTH_SHORT).show();
//이미지를 비트맵형식으로 반환
image_bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
// 각도 받아서 변경하기
try{
if (image_bitmap != null) {
ExifInterface ei = new ExifInterface(img_path);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
Bitmap rotatedBitmap = null;
switch(orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotatedBitmap = rotateImage(image_bitmap, 90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotatedBitmap = rotateImage(image_bitmap, 180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotatedBitmap = rotateImage(image_bitmap, 270);
break;
case ExifInterface.ORIENTATION_NORMAL:
default:
rotatedBitmap = image_bitmap;
}
image_bitmap = rotatedBitmap;
}
}
catch(IOException e){
}
////
//사용자 단말기의 width , height 값 반환
int reWidth = (int) (getWindowManager().getDefaultDisplay().getWidth());
int reHeight = (int) (getWindowManager().getDefaultDisplay().getHeight());
//image_bitmap 으로 받아온 이미지의 사이즈를 임의적으로 조절함. width: 400 , height: 300
image_bitmap_copy = Bitmap.createScaledBitmap(image_bitmap, 300, 310, true);
//ImageView image = (ImageView) findViewById(R.id.imageView); //이미지를 띄울 위젯 ID값
//image.setImageBitmap(image_bitmap_copy);
adapter.setItem(imgPos, image_bitmap_copy, img_path, imageName);
adapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}//end of onActivityResult()
public static Bitmap rotateImage(Bitmap source, float angle) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(),
matrix, true);
}
public String getImagePathToUri(Uri data) {
//사용자가 선택한 이미지의 정보를 받아옴
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(data, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
//이미지의 경로 값
String imgPath = cursor.getString(column_index);
Log.d("test", imgPath);
//이미지의 이름 값
String imgName = imgPath.substring(imgPath.lastIndexOf("/") + 1);
Toast.makeText(this, "이미지 이름 : " + imgName, Toast.LENGTH_SHORT).show();
imageName = imgName;
return imgPath;
}//end of getImagePathToUri()
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Log.d("kkk", "goodgood");
finish();
}
return (super.onOptionsItemSelected(item));
}
}
|
Java
|
UTF-8
| 2,499 | 2.40625 | 2 |
[] |
no_license
|
package com.example.sampleandroidanimationsandtransitions;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class CardFlipActivity extends AppCompatActivity {
private boolean mIsShowingBack;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_flip);
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.add(R.id.frame_cardflip_container, new CardFrontFragment())
.commit();
}
findViewById(R.id.frame_cardflip_container).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
flipCard();
}
});
}
private void flipCard() {
if (mIsShowingBack) {
getSupportFragmentManager().popBackStack();
mIsShowingBack = false;
return;
}
mIsShowingBack = true;
getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(
R.animator.animator_card_flip_right_in,
R.animator.animator_card_flip_right_out,
R.animator.animator_card_flip_left_in,
R.animator.animator_card_flip_left_out)
.replace(R.id.frame_cardflip_container, new CardBackFragment())
.addToBackStack(null)
.commit();
}
public static class CardFrontFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_card_front, container, false);
}
}
public static class CardBackFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_card_back, container, false);
}
}
}
|
C++
|
UTF-8
| 1,428 | 3.03125 | 3 |
[] |
no_license
|
#pragma once
#include "geometry.hpp"
#include <cmath>
Vec3::Vec3(double x, double y, double z): coefs{x,y,z}{ };
double dot(const Vec3 &a, const Vec3 &b){
double result = 0.0;
for (size_t i=0;i<3;i++){
result += a.coefs[i]*b.coefs[i];
}
return result;
};
QuaternionRotation::QuaternionRotation (double qi,double qj, double qk, double qr) : qi(qi),qj(qj),qk(qk),qr(qr){}
QuaternionRotation QuaternionRotation:: from_ypr(double yaw, double pitch, double roll){
double cy = std::cos(yaw * 0.5);
double sy = std::sin(yaw * 0.5);
double cp = std::cos(pitch * 0.5);
double sp = std::sin(pitch * 0.5);
double cr = std::cos(roll * 0.5);
double sr = std::sin(roll * 0.5);
return QuaternionRotation{
cy * cp * sr - sy * sp * cr,
sy * cp * sr + cy * sp * cr,
sy * cp * cr - cy * sp * sr,
cy * cp * cr + sy * sp * sr,
};
}
QuaternionRotation QuaternionRotation::conjugate() const{
return QuaternionRotation{-qi,-qj,-qk,+qr};
}
Vec3 QuaternionRotation::rotate(const Vec3 v) const {
double s = std::sqrt(qi*qi+qj*qj+qk*qk+qr*qr);
double x = v.coefs[0];
double y = v.coefs[1];
double z = v.coefs[2];
Vec3 result {
(1-2*s*(qj*qj+qk*qk))*x + 2*s*(qi*qj-qk*qr)*y + 2*s*(qi*qk+qj*qr)*z,
2*s*(qi*qj + qk *qr) *x + (1-2*s*(qi*qi+qk*qk))*y + (2*s*(qj*qk-qi*qr))*z,
2*s*(qi*qk-qj*qr) * x + 2*s*(qj*qk + qi*qr) * y + (1-2*s*(qi*qi+qj*qj))*z
};
return result;
}
|
PHP
|
UTF-8
| 15,627 | 2.84375 | 3 |
[] |
no_license
|
<?php
require_once('../inc/init.inc.php');
//Si l'internaute n'est pas admin ou pas connecté il n'a rien à faire sur cette page, on le redirige vers la page connexion
if(!connecteAdmin())
{
header('Location:' . URL . 'connexion.php' );
}
//----------------------SUPPRESSION SALLE
if (isset($_GET['action']) && $_GET['action'] == 'suppression')
{
//requete de suppression préparé
$supp = $bdd->prepare("DELETE FROM salle WHERE id_salle = :id_salle");
$supp->bindValue(':id_salle',$_GET['id_salle'], PDO::PARAM_INT);
// on envoie l'id_produit récupéré dans l'URL dans le marqueur :id_produit
$supp->execute();
$_GET['action'] = 'affichage' ;
$validsupp = "<p class='col-md-6 p-3 rounded bg-success mx-auto text-white text-center'>Le produit <strong>ID $_GET[id_salle]</strong> a bien été supprimé </p>";
}
if($_POST)
{
extract($_POST);
//echo'<pre>';print_r($_FILES); echo '</pre>';
$photoBdd ='';
if(isset($_GET['action']) && $_GET['action'] == 'modification')
{
// si on souhaite conserver le même photo en cas de modification, on affecte la valeur du champ type hidden, c'est a dire l'url de la photo actuelle en bdd
$photoBdd = $photo_actuelle;
}
$errorUpload = '';
//Si l'internaute a uploader une image, on entre dans le if
if(!empty($_FILES['photo']['name']))
{
//on définit une liste d'éxtension de fichier autorisé
$listExt = array(1 => 'jpg', 2 => 'jpeg', 3=>'png');
//SplFileinfo() : classe prédéfinie pour le traitement des fichiers uploadé
$fichier = new SplFileInfo($_FILES['photo']['name']);
// on stock l'extension du fichier dans êxt grace à la méthode getExtension qui permet de récupérer l'extension de l'image
$ext = strtolower($fichier->getExtension());
//echo $ext. '<hr>';
//array_search(): fonction prédéfinie permettant de trouver à quel position d'une élément dans un tableau ARRAY, à quel indice se trouve un élément dans un tableau ARRAY
$positionExt = array_search($ext, $listExt);
//echo $positionExt. '<hr>';
//var_dump(positionEXT)
//si l'extension n'est pas trouvé dans un tableau ARRAY, on envoie un message d'erreur
if($positionExt == false)
{
$errorUpload .='<p class="font-italic text-danger">Type de fichier non autorisé</p>';
}
else{
// on renomme l'image avec la référence concaténé avec le nom du fichier
// on remplace les espaces par des tirets dans la référence (str_replace())
$nomphoto = str_replace(' ',' ',$titre) . '-' . $_FILES['photo']['name'];
//echo $nomphoto . '<hr>';
//definition URL de l'image stockée en BDD
$photoBdd = URL . "photo/$nomphoto";
//echo $photoBdd . '<hr>';
//chemin physique du dossier ou l'image est stocké
$photoDossier = RACINE_SITE . "photo/$nomphoto";
//echo $photoDossier . '<hr>';
//copy() : fonction prédéfinie permettant de copier l'image dans le bon dossier
//2 parametre : le nom temporaire de l'image et le chemin physique complet de l'image
copy($_FILES['photo']['tmp_name'], $photoDossier);
}
}
elseif(isset($_GET['action']) && $_GET['action'] == 'ajout' && empty($_FILES['photo']['name']))
{
$errorUpload .= '<p class="font-italic text-danger">Merci d\'uploader une image </p>';
$error = true;
}
if (!isset($error))
{
if(isset($_GET['action']) && $_GET['action'] == 'ajout')
{
//requete d'insertion ENREGISTREMENT SALLE
$insert = $bdd->prepare("INSERT INTO salle (titre, description, photo, pays, ville, adresse, cp, capacite, categorie) VALUES (:titre, :description, :photo, :pays, :ville, :adresse, :cp, :capacite, :categorie)");
$_GET['action'] = 'affichage'; // Redéfini l'indice action en affichage pour qu'aprés modification du produit on revienne a l'affichage des produits
$validInsert = '<p class="col-md-6 p-3 rounded bg-success mx-auto text-white text-center">La salle <strong>' . $titre . '</strong> à bien été enregistré </p>';
}
else{
//requete d'update MODIFICATION SALLE
$insert = $bdd->prepare("UPDATE salle SET titre =:titre , description =:description , photo=:photo , pays=:pays , ville=:ville , adresse=:adresse , cp =:cp , capacite =:capacite , categorie=:categorie WHERE id_salle=:id_salle");
$insert->bindValue(':id_salle',$_GET['id_salle'], PDO::PARAM_INT);
$_GET['action'] = 'affichage';
$validUpdate = '<p class="col-md-6 p-3 rounded bg-success mx-auto text-white text-center">Le produit <strong>' . $titre . '</strong> à bien été modifié </p>';
}
}
$insert->bindValue(':titre',$titre, PDO::PARAM_STR);
$insert->bindValue(':description', $description, PDO::PARAM_STR);
$insert->bindValue(':photo',$photoBdd, PDO::PARAM_STR);
$insert->bindValue(':pays', $pays, PDO::PARAM_STR);
$insert->bindValue(':ville', $ville, PDO::PARAM_STR);
$insert->bindValue(':adresse', $adresse, PDO::PARAM_STR);
$insert->bindValue(':cp', $cp, PDO::PARAM_INT);
$insert->bindValue(':capacite', $capacite, PDO::PARAM_INT);
$insert->bindValue(':categorie', $categorie, PDO::PARAM_STR);
$insert->execute();
//echo '<pre>'; var_dump($_POST) ;echo'</pre>';
}
require_once('../inc/header.inc.php');
?>
<!-- AFFICHAGE LIENS MENU GESTION SALLE -->
<div><p class="col-md-4 offset-md-4 bg-secondary text-center rounded text-white mt-2 p-3">BACKOFFICE</p></div>
<div><a href="?action=affichage" class="col-md-4 offset-md-4 btn btn-info p-2 mb-1 mt-3">AFFICHAGE DES SALLES</a></div>
<div><a href="?action=ajout" class="col-md-4 offset-md-4 btn btn-info p-2 my-1">AJOUTER UNE SALLE</a></div>
<!--001 Si l'indice 'action' est définit dans l'URL et a pour valeur 'affichage', alors on entre dans la condition et on execute le code de l'affichage des produits, on entre dans le IF seulement dans le cas ou l'on a cliqué sur le lien 'AFFICHAGE DES PRODUITS' (ci dessus) -->
<?php if(isset($_GET['action']) && $_GET['action'] == 'affichage'): ?>
<!--Requete de selection salle-->
<?php $data = $bdd ->query("SELECT * FROM salle ORDER BY id_salle"); ?>
<!--------------- AFFICHAGE SALLE--------------------->
<?php if(isset($validsupp)) echo $validsupp ?>
<h3 class="display-4 text-center mt-2">Les salles</h3>
<?php
if(isset($validDelete)) echo $validDelete;
if(isset($validInsert)) echo $validInsert;
if(isset($validUpdate)) echo $validUpdate;
?>
<div class="container col-12 overflow-auto">
<table id="opentable" class="table table-striped table-bordered text-center" style="width:100%">
<thead>
<tr>
<?php
//columnCount() : méthode PDOStatement qui retourne le nombre de colonne selectionné dans la requete SELECT
for ($i = 0; $i < $data->columnCount(); $i++):
//getColumnMeta() : permet de recolter les informations liés aux champs/colonne de la table (primary key, not null, nom du champs..)
$colonne = $data->getColumnMeta($i)
?>
<th><?= $colonne['name'] // on va crocheter à l'indice 'name' afin d'afficher chaque nom de colonne dans les entetes du tableau?></th>
<?php endfor; ?>
<th>Edit</th>
<th>Supp</th>
</tr>
</thead>
<tbody>
<!--On associe la méthode fetch à l'objet PDOStatement, ce qui retourne un ARRAY d'un produit par tour de boucle WHILE-->
<?php while($products = $data->fetch(PDO::FETCH_ASSOC)): ?>
<tr>
<!--La boucle foreach passe en revue chaque tableau ARRAY de chaque produits-->
<?php foreach($products as $key => $value): ?>
<!--Si l'indice du tableau est 'photo' on envoi l'URL de l'image dans l'attribut 'src' de la balise 'img' afin d'afficher l'image et pas l'URL de l'image-->
<?php if($key == 'photo'): ?>
<td>
<a data-fancybox="<?= $value ?>" href="<?= $value ?>">
<img src="<?= $value ?>" alt="" style="width : 100px;">
</a>
</td>
<?php else: //sinon on affiche chaque donnée normalement dans des cellules <td>?>
<td><?= $value ?></td>
<?php endif; ?>
<?php endforeach; ?>
<!--On créer 2liens 'modification' et 'suppression' pour chaque produits en envoyant l'ID du produit dans l'URL-->
<td><a href="?action=modification&id_salle=<?=$products['id_salle']?>" class="btn btn-dark"> Modifier</a></td>
<td><a href="?action=suppression&id_salle=<?=$products['id_salle']?>" class="btn btn-danger"> Supprimer</a></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
<!------------------FIN AFFICHAGE SALLE------------------->
<!--Balise de fermeture de la condition d'affichage 001-->
<?php endif; ?>
<!--Condition d'affichage du formulaire 002 la valeur "ajout" est defini dans les liens AFFICHAGE
si il y a action et ajout dans L'URL on lance le formulaire OU si dans l'url il y a action et modification on lance le meme formulaire-->
<?php if(isset($_GET['action']) && ($_GET['action'] == 'ajout' || $_GET['action'] == 'modification')):
if(isset($_GET['id_salle']))
{
$data = $bdd->prepare("SELECT * FROM salle WHERE id_salle = :id_salle");
$data->bindValue(':id_salle', $_GET['id_salle'], PDO::PARAM_INT);
$data->execute();
$produitactuel = $data->fetch(PDO::FETCH_ASSOC);
foreach($produitactuel as $key => $value)
{
$$key = (isset($produitactuel["$key"])) ? $produitactuel["$key"] : '';
}
}
?>
<div class="container col-6 mt-4 mb-4 justify-content-center border rounded p-2">
<!---Formulaire salle --->
<h3 class="display-4 text-center mt-2"><?= ucfirst($_GET['action']) ?> Salles</h3>
<form action="#" method="POST" enctype="multipart/form-data" style="margin-top:35px; margin-bottom:35px;">
<?php if (isset($validInsert)) echo $validInsert ?>
<!-- TITRE DE LA SALLE-->
<div class="form-group">
<label style="margin-top:20px" for="titre" >Titre</label>
<input type="text" class="form-control" id="titre" placeholder="titre" name="titre" minlength=2 value="<?php if(isset($titre)) echo ("$titre") ?> ">
</div>
<!-- DESCRIPTION DE LA SALLE -->
<div class="form-group">
<label style="margin-top:20px" for="description">Description :</label>
<input type="text-area" class="form-control" id="description" placeholder="description" name="description" minlength=2 value="<?php if(isset($description)) echo ("$description") ?> ">
</div>
<!--PHOTO DE LA SALLE -->
<div class="form-group" style="margin-top:20px">
<label for="photo" style="margin-top:20px">Photo:</label>
<input type="file" id="photo" name="photo" accept="image/png, image/jpeg">
<?php if(isset($errorUpload)) echo $errorUpload ?>
</div>
<?php if(isset($photo) && !empty($photo)): ?>
<div class="text-center">
<em>Vous pouvez uploader une nouvelle photo si vous souhaitez la changer<em><br>
<img src="<?= $photo?>" alt="<?= $titre ?>" class=" col-md-3 mx-auto">
</div>
<?php endif; ?>
<input type="hidden" name="photo_actuelle" value="<?php if(isset($photo)) echo $photo?>">
<!-- PAYS-->
<div class="form-group">
<label for="pays" style="margin-top:20px">Pays</label>
<select id="pays" name="pays" class="form-control">
<option value="france" <?php if(isset($taille) && $taille == "france") echo 'selected'?>>france</option>
<option value="angleterre" <?php if(isset($taille) && $taille == "angleterre") echo 'selected'?>> angleterre</option>
<option value="espagne" <?php if(isset($taille) && $taille == "espagne") echo 'selected'?>> espagne</option>
<option value="allemagne" <?php if(isset($taille) && $taille == "allemagne") echo 'selected'?>> allemagne</option>
</select>
</div>
<!--VILLE -->
<div class="form-group">
<label for="ville" style="margin-top:20px">Ville</label>
<select id="ville" name="ville" class="form-control">
<option value="paris" <?php if(isset($taille) && $taille == "paris") echo 'selected'?>>paris</option>
<option value="marseille" <?php if(isset($taille) && $taille == "marseille") echo 'selected'?>> marseille</option>
<option value="londre" <?php if(isset($taille) && $taille == "londre") echo 'selected'?>> londre</option>
<option value="manchester" <?php if(isset($taille) && $taille == "manchester") echo 'selected'?>> manchester</option>
<option value="madrid" <?php if(isset($taille) && $taille == "madrid") echo 'selected'?>>madrid</option>
<option value="barcelonne" <?php if(isset($taille) && $taille == "barcelonne") echo 'selected'?>> barcelonne</option>
<option value="berlin" <?php if(isset($taille) && $taille == "berlin") echo 'selected'?>> berlin</option>
<option value="francfort" <?php if(isset($taille) && $taille == "francfort") echo 'selected'?>> francfort</option>
</select>
</div>
<!-- ADRESSE DE LA SALLE-->
<div class="form-group">
<label style="margin-top:20px" for="adresse" >adresse</label>
<input type="text" class="form-control" id="adresse" placeholder="adresse" name="adresse" minlength=2 value="<?php if(isset($adresse)) echo ("$adresse") ?> ">
</div>
<!-- CP DE LA SALLE-->
<div class="form-group">
<label style="margin-top:20px" for="cp" >Code postal</label>
<input type="number" class="form-control" id="cp" placeholder="cp" name="cp" minlength=5 maxlength=5 value="<?php if(isset($cp)) echo ("$cp") ?> ">
</div>
<!-- CAPACITE DE LA SALLE-->
<div class="form-group">
<label style="margin-top:20px" for="capacite" >capacite</label>
<input type="number" class="form-control" id="capacite" placeholder="capacite" name="capacite" minlength=1 value="<?php if(isset($capacite)) echo ("$capacite") ?> ">
</div>
<!--CATEGORIE DE LA SALLE-->
<div class="form-group">
<label for="categorie" style="margin-top:20px">categorie</label>
<select id="categorie" name="categorie" class="form-control" value="NULL">
<option value="réunion" <?php if(isset($categorie) && $categorie == 'réunion') echo 'selected'?>>réunion</option>
<option value="bureau" <?php if(isset($categorie) && $categorie == 'bureau') echo 'selected'?>>bureau</option>
<option value="formation" <?php if(isset($categorie) && $categorie == 'formation') echo 'selected'?>>formation</option>
</select>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary" style="margin:5px 0px 0px 0px"><?= ucfirst($_GET['action']) ?> Salle</button>
</div>
</form>
</div>
</main>
<?php
//fin de la condition d'affichage du formulaire 002
endif;
require_once('../inc/footer.inc.php');
|
Java
|
UTF-8
| 3,085 | 2.40625 | 2 |
[] |
no_license
|
package com.xingcloud.dataproxy.membase.test.config;
import org.w3c.dom.Node;
import com.xingcloud.dataproxy.membase.test.util.XMLUtil;
public class PoolConfig {
private int initConnect;
private int minConnect;
private int maxConnect;
private long idleTime;
private long maintSleep;
public PoolConfig(){
this.initConnect = DefaultConfig.DEFUALT_POOL_INIT_CONN;
this.minConnect = DefaultConfig.DEFAULT_POOL_MIN_CONN;
this.maxConnect = DefaultConfig.DEFAULT_POOL_MAX_CONN;
this.idleTime = DefaultConfig.DEFAULT_POOL_IDLE_TIME;
this.maintSleep = DefaultConfig.DEFAULT_POOL_MAINT_SLEEP;
}
public PoolConfig(int initConnect, int minConnect, int maxConnect, long idleTime, long maintSleep){
this.initConnect = initConnect;
this.minConnect = minConnect;
this.maxConnect = maxConnect;
this.idleTime = idleTime;
this.maintSleep = maintSleep;
}
public PoolConfig(Node xmlNode) throws ConfigException{
this();
parseInitConnect(xmlNode);
parseMinConnect(xmlNode);
parseMaxConnect(xmlNode);
parseIdleTime(xmlNode);
parseMaintSleep(xmlNode);
}
public int getInitConnect() {
return initConnect;
}
public int getMinConnect() {
return minConnect;
}
public int getMaxConnect() {
return maxConnect;
}
public long getIdleTime() {
return idleTime;
}
public long getMaintSleep() {
return maintSleep;
}
private void parseInitConnect(Node xmlNode) throws ConfigException{
String initConnect = XMLUtil.getNodeAttribute(xmlNode, "init_conn");
if(initConnect != null){
try{
this.initConnect = Integer.parseInt(initConnect);
} catch(NumberFormatException e){
throw new ConfigException("pool init_conn value must be a number");
}
}
}
private void parseMinConnect(Node xmlNode) throws ConfigException{
String minConnect = XMLUtil.getNodeAttribute(xmlNode, "min_conn");
if(minConnect != null){
try{
this.minConnect = Integer.parseInt(minConnect);
} catch(NumberFormatException e){
throw new ConfigException("pool min_conn value must be a number");
}
}
}
private void parseMaxConnect(Node xmlNode) throws ConfigException{
String maxConnect = XMLUtil.getNodeAttribute(xmlNode, "max_conn");
if(maxConnect != null){
try{
this.maxConnect = Integer.parseInt(maxConnect);
} catch(NumberFormatException e){
throw new ConfigException("pool max_conn value must be a number");
}
}
}
private void parseIdleTime(Node xmlNode) throws ConfigException{
String idleTime = XMLUtil.getNodeAttribute(xmlNode, "idle_time");
if(idleTime != null){
try{
this.idleTime = Long.parseLong(idleTime);
} catch(NumberFormatException e){
throw new ConfigException("pool idle_time value must be a number");
}
}
}
private void parseMaintSleep(Node xmlNode) throws ConfigException{
String maintSleep = XMLUtil.getNodeAttribute(xmlNode, "maint_sleep");
if(maintSleep != null){
try{
this.maintSleep = Long.parseLong(maintSleep);
} catch(NumberFormatException e){
throw new ConfigException("pool maint_sleep value must be a number");
}
}
}
}
|
Java
|
UTF-8
| 475 | 1.734375 | 2 |
[] |
no_license
|
package orar.dlfragmentvalidator.HornALCHOIF;
import java.util.Set;
import org.semanticweb.owlapi.model.OWLAxiom;
import orar.dlfragmentvalidator.TBoxValidator;
public class HornALCHOIF_TBox_Validator extends TBoxValidator {
public HornALCHOIF_TBox_Validator(Set<OWLAxiom> inputTBoxAxioms) {
super(inputTBoxAxioms);
}
@Override
public void initAxiomValidator() {
this.axiomValidator = new HornALCHOIF_AxiomValidator();
this.dlfrangment = "hornALCHOIF";
}
}
|
Java
|
UTF-8
| 2,817 | 2.421875 | 2 |
[] |
no_license
|
/**
* 版权所有, 允风文化
* Author: 允风文化 项目开发组
* copyright: 2012
*/
package com.yf.system.base.passenger;
import java.sql.SQLException;
import java.util.*;
import com.yf.system.base.util.PageInfo;
public class PassengerComponent implements IPassengerComponent{
private IPassengerManager passengerManager;
public IPassengerManager getPassengerManager() {
return passengerManager;
}
public void setPassengerManager(IPassengerManager passengerManager) {
this.passengerManager = passengerManager;
}
/**
* 创建 乘机人表
* @param id
* @return deleted count
*/
public Passenger createPassenger(Passenger passenger) throws SQLException{
return passengerManager.createPassenger(passenger);
}
/**
* 删除 乘机人表
* @param id
* @return deleted count
*/
public int deletePassenger(long id){
return passengerManager.deletePassenger(id);
}
/**
* 修改 乘机人表
* @param id
* @return updated count
*/
public int updatePassenger(Passenger passenger){
return passengerManager.updatePassenger(passenger);
}
/**
* 修改 乘机人表但忽略空值
* @param id
* @return
*/
public int updatePassengerIgnoreNull(Passenger passenger){
return passengerManager.updatePassengerIgnoreNull(passenger);
}
/**
* 查找 乘机人表
* @param where
* @param orderby
* @param limit
* @param offset
* @return
*/
public List findAllPassenger(String where, String orderby,int limit,int offset){
return passengerManager.findAllPassenger(where, orderby,limit,offset);
}
/**
* 查找 乘机人表
* @param id
* @return
*/
public Passenger findPassenger(long id){
return passengerManager.findPassenger(id);
}
/**
* 查找 乘机人表 by language
* @param id
* @return
*/
public Passenger findPassengerbylanguage(long id,Integer language){
return passengerManager.findPassengerbylanguage(id,language);
}
/**
* 查找 乘机人表
* @param where
* @param orderby
* @param pageinfo
* @return
*/
public List findAllPassenger(String where, String orderby,PageInfo pageinfo){
return passengerManager.findAllPassenger(where, orderby,pageinfo);
}
/**
* 根据Sql查找乘机人表
* @param sql
* @param limit
* @param offset
* @return
*/
public List findAllPassenger(String sql,int limit,int offset){
return passengerManager.findAllPassenger(sql,limit,offset);
}
/**
* 执行Sql 乘机人表
* @param sql
* @return updated count
*/
public int excutePassengerBySql(String sql){
return passengerManager.excutePassengerBySql(sql);
}
/**
* 执行Sql
* @param sql
* @return count
*/
public int countPassengerBySql(String sql){
return passengerManager.countPassengerBySql(sql);
}
}
|
JavaScript
|
UTF-8
| 7,712 | 2.96875 | 3 |
[] |
no_license
|
var debug = false;
if (debug === true){
var css = document.createElement("style");
css.type = "text/css";
css.innerHTML = '#bgCanvas {opacity: 0 !important;}';
document.body.appendChild(css);
// Autoreload for the most tedious parts
// setTimeout(function(){
// window.location.reload(1);
// }, 5000);
}
// Static dimensions for all canvai
var canvasWidth = 600;
var canvasHeight = 500
var dead = 0; // controls when the game ends
// Backgroud for easy testing
var canvasBG = document.createElement("canvas");
canvasBG.id = "bgCanvas";
canvasBG.width = canvasWidth;
canvasBG.height = canvasHeight;
document.getElementById('target').appendChild(canvasBG);
// Create P1 Canvas
var canvasP1 = document.createElement("canvas");
canvasP1.width = canvasWidth;
canvasP1.height = canvasHeight;
document.getElementById('target').appendChild(canvasP1);
// Create P2 Canvas
var canvasP2 = document.createElement("canvas");
canvasP2.width = canvasWidth;
canvasP2.height = canvasHeight;
document.getElementById('target').appendChild(canvasP2);
// Create Projectile Canvas
var canvasProjectile = document.createElement("canvas");
canvasProjectile.width = canvasWidth;
canvasProjectile.height = canvasHeight;
document.getElementById('target').appendChild(canvasProjectile);
// // Create Debris Canvas
// var canvasDebris1 = document.createElement("canvas");
// canvasDebris1.width = canvasWidth;
// canvasDebris1.height = canvasHeight;
// document.getElementById('target').appendChild(canvasDebris1);
// // Create Debris Canvas
// var canvasDebris2 = document.createElement("canvas");
// canvasDebris2.width = canvasWidth;
// canvasDebris2.height = canvasHeight;
// document.getElementById('target').appendChild(canvasDebris2);
// // Create Debris Canvas
// var canvasDebris3 = document.createElement("canvas");
// canvasDebris3.width = canvasWidth;
// canvasDebris3.height = canvasHeight;
// document.getElementById('target').appendChild(canvasDebris3);
// Create Timer Canvas
var canvasTimer = document.createElement("canvas");
canvasTimer.width = canvasWidth;
canvasTimer.height = canvasHeight;
document.getElementById('target').appendChild(canvasTimer);
var LAZORS = []; // will be populated by Player class
// Create Timer
var GameTimer = new Timer(canvasTimer);
// Create Players
var P1 = new Zero(canvasP1, "Zero", 1000, 10, 10, 2, LAZORS);
var P2 = new GreenZero(canvasP2, "Green Zero", 1000, (canvasWidth - 100), (canvasHeight - 100), 2, LAZORS);
//var Rock1 = new Debris(canvasDebris1, 7);
//var Rock2 = new Debris(canvasDebris2, 50);
//var Rock3 = new Debris(canvasDebris3, 75);
// objects are stored here as references XD
var PLAYERS = [P1, P2];
var DEBRIS = []; //= [Rock1, Rock2, Rock3];
var DEBRIS_CANVAS = [];
createDebris(3);
var DebrisCollision = new CollisionCalculator(PLAYERS, DEBRIS);
var LazorCollision = new CollisionCalculator(PLAYERS, LAZORS);
function createDebris(count) {
DEBRIS = [];
DEBRIS_CANVAS = [];
for (var i = 0; i < count; i++) {
var speed = Math.random() * 150;
DEBRIS_CANVAS[i] = document.createElement("canvas");
DEBRIS_CANVAS[i].width = canvasWidth;
DEBRIS_CANVAS[i].height = canvasHeight;
document.getElementById('target').appendChild(DEBRIS_CANVAS[i]);
DEBRIS[i] = new Debris(DEBRIS_CANVAS[i], speed);
}
}
var keysDown = {};
addEventListener("keydown", function (e) {
// ignore press and repeat effect
if (!keysDown[e.keyCode]){
keysDown[e.keyCode] = true;
console.log(e.keyCode);
// reset counter to prevent sticking
for (var i = 0, len = PLAYERS.length; i < len; i++) {
PLAYERS[i].resetAnimation();
}
}
// kill default action for arrow keys and spacebar
switch(e.keyCode){
case 37: case 39: case 38: case 40: // Arrow keys
case 32: e.preventDefault(); break; // Space
default: break; // do not block other keys
}
}, false);
addEventListener("keyup", function (e) {
// ignore press and repeat effect
if(keysDown[e.keyCode]){
delete keysDown[e.keyCode];
// reset counter to prevent sticking
for (var i = 0, len = PLAYERS.length; i < len; i++) {
PLAYERS[i].resetAnimation();
}
}
}, false);
var handleInput = function() {
// Stop moving all players
for (var i = 0, len = PLAYERS.length; i < len; i++) {
// By commenting out this line we get a completely differnt game
PLAYERS[i].moveNone();
}
// Player1 Movement
if (32 in keysDown)
P1.fire();
if (65 in keysDown)
P1.moveLeft();
if (87 in keysDown)
P1.moveUp();
if (68 in keysDown)
P1.moveRight();
if (83 in keysDown)
P1.moveDown();
if (!(65 in keysDown || 87 in keysDown || 68 in keysDown || 83 in keysDown || 32 in keysDown)){
P1.moveIdle();
}
// Player2 Movement
if (96 in keysDown || 190 in keysDown)
P2.fire();
if (37 in keysDown)
P2.moveLeft();
if (38 in keysDown)
P2.moveUp();
if (39 in keysDown)
P2.moveRight();
if (40 in keysDown)
P2.moveDown();
if (!(37 in keysDown || 38 in keysDown || 39 in keysDown || 40 in keysDown || 96 in keysDown || 190 in keysDown)){
P2.moveIdle();
}
}
var updateHealth = function () {
if(P1.health <= 0){
P1.health = 0;
endgame(2);
// P1.die();
// P2.pose();
}
if(P2.health <= 0){
P2.health = 0;
endgame(1);
// P2.die();
// P1.pose();
}
// need a better function that autogenerates stuff
document.getElementById("health1").innerHTML = P1.health;
document.getElementById("health2").innerHTML = P2.health;
}
var update = function (elapsed) {
// Move
for (var i = 0, len = PLAYERS.length; i < len; i++) {
PLAYERS[i].update(elapsed);
}
};
var render = function () {
// Draw all players xD
for (var i = 0, len = PLAYERS.length; i < len; i++) {
PLAYERS[i].draw();
}
// P2.draw();
};
// Main game loop
var main = function () {
if(dead === 0){
// Update clock
GameTimer.update();
// Calculate time since last frame
var now = Date.now();
var delta = (now - last);
last = now;
// Handle any user input
handleInput();
// Update game objects
update(delta);
// Render to the screen
render();
// Ping rock to sync up animations
for (var i = 0, len = DEBRIS.length; i < len; i++) {
DEBRIS[i].ping(delta);
}
if(DebrisCollision.calculate()){
// collison detected run update health routine!!
updateHealth();
}
// clean up lazors
for (var j = 0, len = LAZORS.length; j < len; j++) {
if(LAZORS[j].done === 1){
LAZORS.splice(j, 1);
break;
}
}
if(LazorCollision.calculate()){
// collison detected run update health routine!!
updateHealth();
}
// console.log(P2);
// console.log(keysDown);
requestAnimationFrame(main);
}
};
// Create ENd Canvas
var canvasEnd = document.createElement("canvas");
canvasEnd.width = canvasWidth;
canvasEnd.height = canvasHeight;
document.getElementById('target').appendChild(canvasEnd);
var endgame = function(player){
canvas = canvasEnd;
ctx = canvasEnd.getContext("2d");
dead = 1;
ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
ctx.font = "30px Comic Sans MS";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.fillText("GAME OVER, PLAYER " + player + " WON" , canvas.width/2, canvas.height/2);
setTimeout(function(){
window.location.reload(1);
}, 3000);
}
// One time initializations
updateHealth();
// Start the main game loop!
var last = Date.now();
// setInterval(main, 1);
main();
|
C
|
UTF-8
| 617 | 2.671875 | 3 |
[
"LicenseRef-scancode-public-domain"
] |
permissive
|
// # htab_iterator_next.c
// # Řešení IJC-DU2, 25.4.2019
// # Autor: xhajek48 (Karel Hajek), FIT VUT
// # Přeloženo: gcc 8.2.1
#include "htab.h"
#include "htab_structs.h"
htab_iterator_t htab_iterator_next(htab_iterator_t it){
// if it points to the last element of index
if(it.ptr->next == NULL){
for(size_t i = it.idx + 1; i < it.t->arr_size; i++){
if(it.t->arr[i] != NULL){
it.ptr = it.t->arr[i];
it.idx = i;
return it;
}
}
return htab_end(it.t);
}
else{
it.ptr = it.ptr->next;
return it;
}
}
|
PHP
|
UTF-8
| 3,408 | 3.015625 | 3 |
[] |
no_license
|
<?php
class question
{
private $id, $owneremail, $ownderid, $createdate, $title, $body, $skills, $score, $downvoted_ids, $upvoted_ids;
public function __construct($id, $owneremail, $ownderid, $createdate, $title, $body, $skills, $score, $downvoted_ids, $upvoted_ids)
{
$this->id = $id;
$this->owneremail = $owneremail;
$this->ownderid = $ownderid;
$this->createdate = $createdate;
$this->title = $title;
$this->body = $body;
$this->skills = $skills;
$this->score = $score;
$this->downvoted_ids = $downvoted_ids;
$this->upvoted_ids = $upvoted_ids;
}
/**
* @return mixed
*/
public function getDownvotedIds()
{
if($this->downvoted_ids != null){
return explode(',',$this->downvoted_ids );
}
else{
return [];
}
}
/**
* @param mixed $downvoted_ids
*/
public function setDownvotedIds($downvoted_ids)
{
$this->downvoted_ids = implode(',',$downvoted_ids);
}
/**
* @return mixed
*/
public function getUpvotedIds()
{
if($this->upvoted_ids != null){
return explode(',',$this->upvoted_ids );
}
else{
return [];
}
}
/**
* @param mixed $upvoted_ids
*/
public function setUpvotedIds($upvoted_ids)
{
$this->upvoted_ids = implode(',',$upvoted_ids);
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getOwneremail()
{
return $this->owneremail;
}
/**
* @param mixed $owneremail
*/
public function setOwneremail($owneremail)
{
$this->owneremail = $owneremail;
}
/**
* @return mixed
*/
public function getCreatedate()
{
return $this->createdate;
}
/**
* @param mixed $createdate
*/
public function setCreatedate($createdate)
{
$this->createdate = $createdate;
}
/**
* @return mixed
*/
public function getTitle()
{
return $this->title;
}
/**
* @param mixed $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* @return mixed
*/
public function getBody()
{
return $this->body;
}
/**
* @param mixed $body
*/
public function setBody($body)
{
$this->body = $body;
}
/**
* @return mixed
*/
public function getSkills()
{
return $this->skills;
}
/**
* @param mixed $skills
*/
public function setSkills($skills)
{
$this->skills = $skills;
}
/**
* @return mixed
*/
public function getScore()
{
return $this->score;
}
/**
* @param mixed $score
*/
public function setScore($score)
{
$this->score = $score;
}
/**
* @return mixed
*/
public function getOwnerid()
{
return $this->ownderid;
}
/**
* @param mixed $ownderid
*/
public function setOwnderid($ownderid)
{
$this->ownderid = $ownderid;
}
}
|
Markdown
|
UTF-8
| 16,736 | 2.921875 | 3 |
[] |
no_license
|
>文章收录在公众号:**bigsai** 更多精彩干货敬请关注!
### 前言
说起八皇后问题,它是一道回溯算法类的经典问题,也**可能**是我们大部分人在上数据结构或者算法课上遇到过的最难的一道题……

第一次遇到它的时候应该是大一下或者大二这个期间,这个时间对啥都懵懵懂懂,啥都想学却发现好像啥都挺难的,八皇后同样把那个时候的我阻拦在外,我记得很清楚当时大二初我们学业导师给我们开班会时候讲到的一句话很清晰:"如果没有认真的学习算法他怎么可能解出八皇后的代码呢"。
确实,那个时候的我搞不懂递归,回溯也没听过,连Java的集合都没用明白,毫无逻辑可言,八皇后对我来说确实就是无从下手。
但今天,我可以吊打八皇后了,和你们一起白银万两,佳丽三十。
### 浅谈递归
对于递归算法,我觉得**掌握递归是入门数据结构与算法的关键**,因为后面学习很多操作涉及到递归,例如链表的一些操作、树的遍历和一些操作、图的dfs、快排、归并排序等等。

递归的实质还是借助栈实现一些操作,利用递归能够完成的操作使用栈都能够完成,并且利用栈的话可以很好的控制停止,效率更高(递归是一个来回的过程回来的时候需要特判)。
递归实现和栈实现操作的区别,递归对我们来说更简洁巧妙,并且用多了会发现很多问题的处理上递归的思考方式更偏向人的思考方式,而栈的话就是老老实实用计算机(数据结构特性)的思维去思考问题。这个你可以参考二叉树的遍历方式递归和非递归版本,复杂性一目了然。
从递归算法的特征上来看,递归算法的问题都是**父问题可以用过一定关系转化为子问题**。即从后往前推导的过程,一般通过一个参数来表示当前的层级。
而递归的主要特点如下:
- 自己调用自己
- 递归通常不在意具体操作,只关心初始条件和上下层的变化关系。
- 递归函数需要有临界停止点,即递归不能无限制的执行下去。通常这个点为必须经过的一个数。
- 递归可以被栈替代。有些递归可以优化。比如遇到重复性的可以借助空间内存记录而减少递归的次数。

而通常递归算法的一个流程大致为:
```
定义递归算法及参数
- 停止递归算法条件
- (可存在)其他逻辑
- 递归调用(参数需要改变)
- (可存在)其他逻辑
```
如果还是不理解的话就要看**我的另一篇文章**了:[数据结构与算法—递归算法(从阶乘、斐波那契到汉诺塔的递归图解)](https://blog.csdn.net/qq_40693171/article/details/99685384),写的是真的好!
### 回溯算法
谈完递归,你可能明白有这么一种方法可以使用,但你可能感觉单单的递归和八皇后还是很难扯上关系,是的没错,所以我来讲回溯算法了。
这里插个小插曲。前天(真的前天)有个舍友我们宿舍一起聊天的时候谈到回溯算法,他说`回shuo(朔)`算法,我们差异的纠正了一下是`回su(素)`算法,他竟然读错了四年……不知道路过的你们有没有读错的。

咱们言归正传,算法界中,有五大常用算法:贪心算法、分治算法、动态规划算法、**回溯算法**、分支界限算法。咱们回溯算法就是五大之一,因为回溯算法能够解决很多实际的问题,尽管很多时候复杂度可能不太小,但大部分情况都能得到一个不错的结果。
对于回溯法的定义,百度百科是这么定义的:
>回溯算法实际上一个**类似枚举的搜索尝试过程**,主要是在搜索尝试过程中寻找问题的解,当发现已不满足求解条件时,就“回溯”返回,尝试别的路径。回溯法是一种选优搜索法,按选优条件向前搜索,以达到目标。但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,这种走不通就退回再走的技术为回溯法,而满足回溯条件的某个状态的点称为“回溯点”。许多复杂的,规模较大的问题都可以使用回溯法,**有“通用解题方法”的美称**。
对于回溯法,它的核心就是**试探和复原**。这个自动化的过程就是利用递归去执行,在递归函数执行前去修改尝试,满足条件后向下递归试探,试探完毕后需要将数值复原。**在这个试探的过程中找到我们所需要的一个或者所有解**。这个我们也俗称暴力。

啥?没听懂?好,那我就再讲讲,你应该知道深度优先搜索(dfs)吧?**其实回溯算法就是一种特殊的dfs**。之所以叫回溯,就是因为这类算法在运用递归都有个复原的过程,所以前面的操作就相当于试探一样。而这类算法一般常常配对一个或多个boolean类型的数组用来标记试探途中用过的点。
举个例子,我们知道回溯算法用来求所有数字的排列顺序。我们分析其中一个顺序。比如数列`6 8 9`这个序列的话,我们用来求它的排列顺序。
对于代码块来说,这可能很容易实现:
```java
import java.util.Arrays;
public class test {
public static void main(String[] args) {
int arr[]={6,8,9};//需要排列组合的数组
int val[]={0,0,0};//临时储存的数组
boolean jud[] = new boolean[arr.length];// 判断是否被用
dfs(arr,val, jud, 0,"");//用一个字符串长度更直观看结果
}
private static void dfs(int[] arr, int val[],boolean[] jud, int index,String s) {
System.out.println(s+Arrays.toString(val));
if (index == arr.length){ }//停止递归条件
else{
for (int i = 0; i < arr.length; i++) {
if (!jud[i]) {//当前不能用的
int team=val[index];
val[index] = arr[i];
jud[i] = true;// 下层不能在用
dfs(arr, val, jud, index + 1,s+" _ ");
jud[i] = false;// 还原
val[index]=team;
}
}
}
}
}
```
而执行的结果为:

这里再配张图理解:

而通常回溯算法的一个流程大致为:
```
定义回溯算法及参数
- (符合条件)跳出
- (不符合)不跳出:
- - 遍历需要操作的列表&&该元素可操作&&可以继续试探
- - - 标记该元素已使用以及其他操作
- - - 递归调用(参数改变)
- - - 清除该元素标记以及其他操作
```
也就是在使用数组进行回溯的时候,使用过的时候需要标记子递归不能再使用防止死循环,而当回来的时候需要解封该位置,以便该编号位置被其他兄弟使用之后这个数值在后面能够再次使用!而如果使用List或者StringBuilder等动态空间用来进行回溯的时候记得同样的复原,删了要记得增,减了要记得加。搞明白这些,我想回溯算法也应该难不倒你了吧。
### 八皇后问题
掌握了回溯算法的关键,八皇后问题多思考就可以想的出来了。前面的讲解都是为了解决八皇后问题做铺垫。首先,我们认真的看下八皇后问题描述。
八皇后问题(英文:Eight queens),是由国际西洋棋棋手马克斯·贝瑟尔于1848年提出的问题,是回溯算法的典型案例。
>问题表述为:在8×8格的国际象棋上摆放8个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法。高斯认为有76种方案。1854年在柏林的象棋杂志上不同的作者发表了40种不同的解,**后来有人用图论的方法解出92种结果**。如果经过±90度、±180度旋转,和对角线对称变换的摆法看成一类,共有42类。计算机发明后,有多种计算机语言可以编程解决此问题。

我们该怎么思考这种问题呢?也就是从何入手呢?
- 从限制条件入手
八皇后问题有以下限制条件:
- 8 x 8的方格
- 每行一个,**共八行**(0-7)
- 每列一个,**共八列**(0-7)
- 每左斜杠一个,**共十五左斜杠**(0-14)
- 每右斜杠一个,**共十五右斜杠**(0-14)
当看到这些限制条件,肯定想到这么多限制条件**需要判断**。判断的话当然就是**借助boolean数组啦**。还是一维的8个大小,所以我们首先用4个boolean数组用来判断各自的条件是否被满足。
表示这个图的话我们可以使用一个int类型数组表示,0表示没有,1表示有皇后。
那么如何去设计这个算法呢?这个**并不是每个格子都有数字**,所以在进行回溯的时候不应该每个格子每个格子进行向下递归(**同行互斥**),也就是递归到当前层的时候,循环遍历该层的八种情况进行试探(每个都试探),如果不满足条件的就不操作而被终止掉,但该行每个满足条件的需要递归的时候需**要进入到下一行**。
当然你需要提前知道当前位置横纵坐标怎们知道对应的boolean位置(位置从0号开始计算)。例如位置p(x,y)中对应的位置为:
- hang[] : `x` 每一行就是对应的i。
- lie[] : `y` 每一列就是对应的j。
- zuoxie[] : `x+y` 规定顺序为左上到右下
- youxie[] : `x+(7-y)` 规定顺序为右上到左下(个人习惯)

好啦,该算法的实现代码为:
```java
import java.util.Arrays;
public class EightQueens {
static int allnum=0;
public static void main(String[] args) {
boolean hang[]=new boolean[8];//行
boolean lie[]=new boolean[8];//列
boolean zuoxie[]=new boolean[15];//左斜杠
boolean youxie[]=new boolean[15];//右斜杠
int map[][]=new int[8][8];//地图
dfs(0,hang,lie,zuoxie,youxie,map);//进行下去
}
private static void dfs(int hindex, boolean[] hang, boolean[] lie, boolean[] zuoxie, boolean[] youxie, int[][] map) {
if(hindex==8){
allnum++;
printmap(map);//输出map
}
else{
//hindex为行 i为具体的某一列
for(int i=0;i<8;i++)
{
if(!hang[hindex]&&!lie[i]&&!zuoxie[hindex+i]&&!youxie[hindex+(7-i)])
{
hang[hindex]=true;//试探
lie[i]=true;
zuoxie[hindex+i]=true;
youxie[hindex+(7-i)]=true;
map[hindex][i]=1;
dfs(hindex+1,hang,lie,zuoxie,youxie,map);//dfs
hang[hindex]=false;//还原
lie[i]=false;
zuoxie[hindex+i]=false;
youxie[hindex+(7-i)]=false;
map[hindex][i]=0;
}
}
}
}
//输出地图
private static void printmap(int[][] map) {
System.out.println("第"+allnum+"个排列为");
for(int a[]:map)
{
System.out.println(Arrays.toString(a));
}
}
}
```
跑一边就知道到底有多少种皇后,最终是92种皇后排列方式,不得不说能用数学方法接出来的是真的牛叉。

### 八皇后变种
此时我想八皇后问题已经搞得明明白白了,但是智慧的人们总是想出各种方法变化题目想难到我们,这种八皇后问题有很多变种,例如**n皇后,数独等问题**。
这里就简单讲讲两数独问题的变种。
力扣36 有效的数独

像这种题需要考虑和八皇后还是很像,改成9*9,只不过在具体处理需要考虑`横`、`竖`和`3x3小方格`。
当然这题比较简单,还有一题就比较麻烦了 **力扣37解数独**。


这一题有难度的就是需要我们每个位置都有数据都要去试探。
这种二维的回溯需要考虑一些问题,我们对于每一行每一行考虑。 每一行已经预有一些数据事先标记,在从开始试探放值,满足条件后向下递归试探。一直到结束如果都满足那么就可以结束返回数组值。
这里的话有两点需要注意的在这里提一下:
- 用二维两个参数进行递归回溯判断起来谁加谁减比较麻烦,所以我们用一个参数index用它来计算横纵坐标进行转换,这样就减少二维递归的一些麻烦。
- 回溯是一个来回的过程,在回来的过程正常情况需要将数据改回去,但是如果已经知道结果就没必要再该回去可以直接停止放置回溯造成值的修改(这里我用了一个isfinish的boolean类型进行判断)。
代码可以参考为:

### 结语
好啦,不知道这个专题结束之后能否能够掌握这个八皇后的回溯算法以及思想,能否理清递归,回溯,深搜以及八皇后为关系?
总的来说
- 递归更注重一种方式,自己调用自己。
- 回溯更注重试探和复原,这个过程一般借助递归。
- dfs深度优先搜素,一般用栈或者递归去实现,如果用递归可能会复原也可能不复原数据,所以回溯是深搜的一种。
- 八皇后是经典回溯算法解决的问题,你说深度优先搜素其实也没问题,但回溯更能精准的描述算法特征。
好啦,不说啦,我bigsai去领取佳丽30和白银万两啦!(不错的话记得一键三联,微信搜索**bigsai**,回复**bigsai** 下次迎娶美杜莎女王!)

|
Python
|
UTF-8
| 134 | 2.9375 | 3 |
[] |
no_license
|
names = ['john','moses','janet','mary']
emails = ['me@gmail.com','moses@gmail.com','ja@gmail.com','yahoo']
for i,j in zip(names,emails):
print(i,j)
|
Java
|
UTF-8
| 10,524 | 2.4375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.qouteall.immersive_portals.render;
import com.qouteall.immersive_portals.CGlobal;
import com.qouteall.immersive_portals.CHelper;
import com.qouteall.immersive_portals.my_util.BoxPredicate;
import com.qouteall.immersive_portals.portal.Portal;
import com.qouteall.immersive_portals.render.context_management.PortalRendering;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.MinecraftClient;
import net.minecraft.util.math.Box;
import net.minecraft.util.math.Vec3d;
import javax.annotation.Nullable;
import java.util.Comparator;
@Environment(EnvType.CLIENT)
public class FrustumCuller {
private BoxPredicate canDetermineInvisibleFunc;
public FrustumCuller() {
}
public void update(double cameraX, double cameraY, double cameraZ) {
canDetermineInvisibleFunc = getCanDetermineInvisibleFunc(cameraX, cameraY, cameraZ);
}
public boolean canDetermineInvisible(
double minX, double minY, double minZ, double maxX, double maxY, double maxZ
) {
return canDetermineInvisibleFunc.test(
minX, minY, minZ, maxX, maxY, maxZ
);
}
private BoxPredicate getCanDetermineInvisibleFunc(
double cameraX,
double cameraY,
double cameraZ
) {
if (!CGlobal.doUseAdvancedFrustumCulling) {
return BoxPredicate.nonePredicate;
}
if (PortalRendering.isRendering()) {
return PortalRendering.getRenderingPortal().getInnerFrustumCullingFunc(cameraX, cameraY, cameraZ);
}
else {
if (!CGlobal.useSuperAdvancedFrustumCulling) {
return BoxPredicate.nonePredicate;
}
Portal portal = getCurrentNearestVisibleCullablePortal();
if (portal != null) {
Vec3d portalOrigin = portal.getOriginPos();
Vec3d portalOriginInLocalCoordinate = portalOrigin.add(
-cameraX, -cameraY, -cameraZ
);
final Vec3d[] outerFrustumCullingVertices = portal.getOuterFrustumCullingVertices();
if (outerFrustumCullingVertices == null) {
return BoxPredicate.nonePredicate;
}
Vec3d[] downLeftUpRightPlaneNormals = getDownLeftUpRightPlaneNormals(
portalOriginInLocalCoordinate,
outerFrustumCullingVertices
);
Vec3d downPlane = downLeftUpRightPlaneNormals[0];
Vec3d leftPlane = downLeftUpRightPlaneNormals[1];
Vec3d upPlane = downLeftUpRightPlaneNormals[2];
Vec3d rightPlane = downLeftUpRightPlaneNormals[3];
Vec3d nearPlanePosInLocalCoordinate = portalOriginInLocalCoordinate;
Vec3d nearPlaneNormal = portal.getNormal().multiply(-1);
return
(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) -> {
boolean isBehindNearPlane = testBoxTwoVertices(
minX, minY, minZ, maxX, maxY, maxZ,
nearPlaneNormal.x, nearPlaneNormal.y, nearPlaneNormal.z,
nearPlanePosInLocalCoordinate.x,
nearPlanePosInLocalCoordinate.y,
nearPlanePosInLocalCoordinate.z
) == BatchTestResult.all_true;
if (!isBehindNearPlane) {
return false;
}
boolean fullyInFrustum = isFullyInFrustum(
minX, minY, minZ, maxX, maxY, maxZ,
leftPlane, rightPlane, upPlane, downPlane
);
return fullyInFrustum;
};
}
else {
return BoxPredicate.nonePredicate;
}
}
}
public static Vec3d[] getDownLeftUpRightPlaneNormals(
Vec3d portalOriginInLocalCoordinate,
Vec3d[] fourVertices
) {
Vec3d[] relativeVertices = {
fourVertices[0].add(portalOriginInLocalCoordinate),
fourVertices[1].add(portalOriginInLocalCoordinate),
fourVertices[2].add(portalOriginInLocalCoordinate),
fourVertices[3].add(portalOriginInLocalCoordinate)
};
//3 2
//1 0
return new Vec3d[]{
relativeVertices[0].crossProduct(relativeVertices[1]),
relativeVertices[1].crossProduct(relativeVertices[3]),
relativeVertices[3].crossProduct(relativeVertices[2]),
relativeVertices[2].crossProduct(relativeVertices[0])
};
}
public static enum BatchTestResult {
all_true,
all_false,
both
}
public static BatchTestResult testBoxTwoVertices(
double minX, double minY, double minZ,
double maxX, double maxY, double maxZ,
double planeNormalX, double planeNormalY, double planeNormalZ,
double planePosX, double planePosY, double planePosZ
) {
double p1x;
double p1y;
double p1z;
double p2x;
double p2y;
double p2z;
if (planeNormalX > 0) {
p1x = minX;
p2x = maxX;
}
else {
p1x = maxX;
p2x = minX;
}
if (planeNormalY > 0) {
p1y = minY;
p2y = maxY;
}
else {
p1y = maxY;
p2y = minY;
}
if (planeNormalZ > 0) {
p1z = minZ;
p2z = maxZ;
}
else {
p1z = maxZ;
p2z = minZ;
}
boolean r1 = isInFrontOf(
p1x - planePosX, p1y - planePosY, p1z - planePosZ,
planeNormalX, planeNormalY, planeNormalZ
);
boolean r2 = isInFrontOf(
p2x - planePosX, p2y - planePosY, p2z - planePosZ,
planeNormalX, planeNormalY, planeNormalZ
);
if (r1 && r2) {
return BatchTestResult.all_true;
}
if ((!r1) && (!r2)) {
return BatchTestResult.all_false;
}
return BatchTestResult.both;
}
public static BatchTestResult testBoxTwoVertices(
double minX, double minY, double minZ,
double maxX, double maxY, double maxZ,
Vec3d planeNormal
) {
return testBoxTwoVertices(
minX, minY, minZ, maxX, maxY, maxZ,
planeNormal.x, planeNormal.y, planeNormal.z,
0, 0, 0
);
}
private static boolean isInFrontOf(double x, double y, double z, Vec3d planeNormal) {
return x * planeNormal.x + y * planeNormal.y + z * planeNormal.z >= 0;
}
private static boolean isInFrontOf(
double x, double y, double z,
double planeNormalX, double planeNormalY, double planeNormalZ
) {
return x * planeNormalX + y * planeNormalY + z * planeNormalZ >= 0;
}
public static boolean isFullyOutsideFrustum(
double minX, double minY, double minZ, double maxX, double maxY, double maxZ,
Vec3d leftPlane,
Vec3d rightPlane,
Vec3d upPlane,
Vec3d downPlane
) {
BatchTestResult left = testBoxTwoVertices(
minX, minY, minZ, maxX, maxY, maxZ, leftPlane
);
BatchTestResult right = testBoxTwoVertices(
minX, minY, minZ, maxX, maxY, maxZ, rightPlane
);
if (left == BatchTestResult.all_false && right == BatchTestResult.all_true) {
return true;
}
if (left == BatchTestResult.all_true && right == BatchTestResult.all_false) {
return true;
}
BatchTestResult up = testBoxTwoVertices(
minX, minY, minZ, maxX, maxY, maxZ, upPlane
);
BatchTestResult down = testBoxTwoVertices(
minX, minY, minZ, maxX, maxY, maxZ, downPlane
);
if (up == BatchTestResult.all_false && down == BatchTestResult.all_true) {
return true;
}
if (up == BatchTestResult.all_true && down == BatchTestResult.all_false) {
return true;
}
return false;
}
private static boolean isFullyInFrustum(
double minX, double minY, double minZ, double maxX, double maxY, double maxZ,
Vec3d leftPlane,
Vec3d rightPlane,
Vec3d upPlane,
Vec3d downPlane
) {
return testBoxTwoVertices(minX, minY, minZ, maxX, maxY, maxZ, leftPlane)
== BatchTestResult.all_true
&& testBoxTwoVertices(minX, minY, minZ, maxX, maxY, maxZ, rightPlane)
== BatchTestResult.all_true
&& testBoxTwoVertices(minX, minY, minZ, maxX, maxY, maxZ, upPlane)
== BatchTestResult.all_true
&& testBoxTwoVertices(minX, minY, minZ, maxX, maxY, maxZ, downPlane)
== BatchTestResult.all_true;
}
@Nullable
private static Portal getCurrentNearestVisibleCullablePortal() {
if (TransformationManager.isIsometricView) {
return null;
}
Vec3d cameraPos = MinecraftClient.getInstance().gameRenderer.getCamera().getPos();
return CHelper.getClientNearbyPortals(16).filter(
portal -> portal.isInFrontOfPortal(cameraPos)
).filter(
Portal::canDoOuterFrustumCulling
).min(
Comparator.comparingDouble(portal -> portal.getDistanceToNearestPointInPortal(cameraPos))
).orElse(null);
}
public static boolean isTouchingInsideContentArea(Portal renderingPortal, Box boundingBox) {
Vec3d planeNormal = renderingPortal.getContentDirection();
Vec3d planePos = renderingPortal.getDestPos();
BatchTestResult batchTestResult = testBoxTwoVertices(
boundingBox.minX, boundingBox.minY, boundingBox.minZ,
boundingBox.maxX, boundingBox.maxY, boundingBox.maxZ,
planeNormal.x, planeNormal.y, planeNormal.z,
planePos.x, planePos.y, planePos.z
);
return batchTestResult != BatchTestResult.all_false;
}
}
|
Markdown
|
UTF-8
| 1,600 | 2.875 | 3 |
[] |
no_license
|
MINIMEALS README
PROJECT SUMMARY: A web app that allows parents to log and review the meals their toddler is eating, after seeing several posts online by parents bemoaning the lack of a program that does this. The resulting project is the start of a response to this problem, with the intention that it provides a quick and easy way for a user to log meals that theirchild is eating, as well as how much they've eaten and their enjoyment.
TECHNOLOGIES USED
-Flask/Python
-Bootstrap
-HTML
-CSS
MY LEARNING
-Databases - this is my first relational database created from scratch, and uses several different tables to allow a list of dishes and ingredients that can be used by users collectively, with the intention that the database becomes more comprehensive with more users
-Bootstrap - I haven't used this library before
-Passing vraiables to HTML/Jinja - I was particulary stuck on incrporating the results from two separate tables in a loop (meals and dishes on the 'review page;), but found I could achieve the desired effect by zipping the sqlite3.row objects together
NEXT STEPS
There are plenty of further developments and functionality I can add to minimeals, auch as:
-Improved date formatting
-Exploring more streamlined ways to add meals and dishes
-Customisable review filters (e.g. finding ingredientd the child likes to eat)
-Introducing algorithms which can try to identify common ingredients that may be influencing the child's behaviour that the parent may not be aware of
-A 'contact us' page that allows an email to be set through a form
-An 'about' page
|
C++
|
UTF-8
| 1,361 | 2.65625 | 3 |
[] |
no_license
|
#include <Wire.h>
#include "Adafruit_TCS34725.h"
/* Example code for the Adafruit TCS34725 breakout library */
#define LED 7
/* Connect SCL to analog 5
Connect SDA to analog 4
Connect VDD to 3.3V DC
Connect GROUND to common ground */
/* Initialise with specific int time and gain values */
Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_700MS, TCS34725_GAIN_1X);
uint16_t r, g, b, c;
void initColourSensor(void) {
if (tcs.begin()) {
Serial.println("Connected to Colorimeter");
} else {
Serial.println("No TCS34725 found ... check your connections and restart");
while (1);
}
}
void takeColour(void) {
digitalWrite(LED, HIGH);
tcs.getRawData(&r, &g, &b, &c);
Serial.print("R: "); Serial.print(r, DEC); Serial.print(" ");
Serial.print("G: "); Serial.print(g, DEC); Serial.print(" ");
Serial.print("B: "); Serial.print(b, DEC); Serial.print(" ");
Serial.print("C: "); Serial.print(c, DEC); Serial.print(" ");
Serial.println(" ");
digitalWrite(LED, LOW);
}
uint16_t getNitrate(void) {
return (uint16_t) (368 - 35 * log(b));
}
uint16_t getAmmonia(void) {
}
void setup(void) {
pinMode(LED, OUTPUT);
Serial.begin(9600);
initColourSensor();
}
void loop(void) {
if (Serial.available() > 0) {
char cmd = Serial.read();
if (cmd == 'c') {
takeColour();
}
}
}
|
Python
|
UTF-8
| 287 | 3.75 | 4 |
[] |
no_license
|
'''
filter函数
过滤函数 对一组数据进行过滤,符合条件的数据会生成一个新的列表并返回
'''
def isEven(n):
return n%2 == 0
list1 = [i for i in range(10)]
print("list1=", list1)
rst = filter(isEven, list1)
print(rst)
print([i for i in rst])
|
Python
|
UTF-8
| 409 | 3.03125 | 3 |
[] |
no_license
|
class Instruction():
def __init__(self, instruction, message, line):
self.instruction = instruction
self.message = message
self.line = line
def getMessage(self):
return self.message
def setLine(self, l):
self.line = l
def getLine(self):
return self.line
def getInstruction(self):
return self.instruction
|
Python
|
UTF-8
| 1,054 | 2.609375 | 3 |
[
"Apache-2.0"
] |
permissive
|
import mmap
import numpy as np
import pandas as pd
import sys
file_path = sys.argv[1]
out_file_path = sys.argv[2]
memory_map = sys.argv[3] == "True"
with open(file_path, 'rb') as my_file:
if memory_map:
my_file = mmap.mmap(my_file.fileno(), 0, prot=mmap.PROT_READ)
with open(out_file_path, 'wb') as out_file:
header_items = my_file.readline().rstrip(b"\n").split(b"\t")
column_indices = range(0, len(header_items), 100)
column_names = [header_items[i].decode() for i in column_indices]
# NOTE: Specifying the dtype of each column makes it somewhat faster, especially for very wide files.
column_type_dict = {}
for column_name in column_names:
if column_name.startswith("Numeric"):
column_type_dict[column_name] = np.float64
else:
column_type_dict[column_name] = "str"
df = pd.read_csv(file_path, sep="\t", header=0, usecols=column_names, dtype=column_type_dict, memory_map=memory_map, na_filter=False)
df.to_csv(out_file_path, sep="\t", header=True, index=False, float_format='%.8f')
|
Java
|
UTF-8
| 2,681 | 2.640625 | 3 |
[] |
no_license
|
package com.hazelcast.samples.serialization.hazelcast.airlines;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.StreamSerializer;
import com.hazelcast.samples.serialization.hazelcast.airlines.util.Constants;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* <p>A serializer for {@link V5Flight} objects.
* </p>
* <p>Use Esoteric Software's <a href="https://github.com/EsotericSoftware/kryo">Kryo</a>
* which takes a byte stream.</p>
* <p>This code could easily be made more generic. Although it deals with {@link V5Flight}
* it does not mention the fields etc
* </p>
*/
@Slf4j
public class V5FlightSerializer implements StreamSerializer<V5Flight> {
/**
* <p>"<i>Register</i>" the class so Kryo can figure out how to efficently
* serialize it.
* </p>
*/
private static final ThreadLocal<Kryo> KRYO_THREAD_LOCAL = new ThreadLocal<Kryo>() {
@Override
protected Kryo initialValue() {
Kryo kryo = new Kryo();
kryo.register(V5Flight.class);
return kryo;
}
};
/**
* <p>Serialization : Hand Kryo the output stream and the object and leave it to do
* it.
* </p>
*/
@Override
public void write(ObjectDataOutput objectDataOutput, V5Flight v5Flight) throws IOException {
Kryo kryo = KRYO_THREAD_LOCAL.get();
Output output = new Output((OutputStream) objectDataOutput);
kryo.writeObject(output, v5Flight);
output.flush();
log.trace("Serialize {}", v5Flight.getClass().getSimpleName());
}
/**
* <p>Deserialization : Give Kryo the input stream and ask it to read in an object
* of the right type.
* </p>
*/
@Override
public V5Flight read(ObjectDataInput objectDataInput) throws IOException {
InputStream inputStream = (InputStream) objectDataInput;
Input input = new Input(inputStream);
Kryo kryo = KRYO_THREAD_LOCAL.get();
log.trace("De-serialize {}", V5Flight.class.getSimpleName());
return kryo.readObject(input, V5Flight.class);
}
/**
* <p>The id of the object being serialized/deserialized.
* </p>
*/
@Override
public int getTypeId() {
return Constants.V5FLIGHT_ID;
}
/**
* <p>Not used, but called when the process shuts down.
* </p>
*/
@Override
public void destroy() {
}
}
|
Python
|
UTF-8
| 563 | 3.421875 | 3 |
[] |
no_license
|
import requests
import time
url = "https://animechan.vercel.app/api/random"
print("\nWellcome to anime quote generator")
time.sleep(0.3)
print("Type 'quit' or 'exit' to exit")
while (True):
generate = input("\nPress [Enter] to generate quote \n")
if generate == 'quit' or generate == 'exit':
print("Thanks for use this tool :)")
time.sleep(0.5)
exit()
else:
quote = requests.get(url).json()['quote']
chara = requests.get(url).json()['character']
print("\n")
print(quote + "\n" + "- " + chara)
|
Python
|
UTF-8
| 2,590 | 3.0625 | 3 |
[] |
no_license
|
import os
import re
import MySQLdb
dir_to_scan = '/home/yura/test'
filetype_to_scan = 'txt'
'Get content of directory'
# TODO add directories scan recursively
def dir_content(scan_dir):
if os.path.exists(scan_dir) and os.path.isdir(scan_dir):
os.chdir(scan_dir)
return os.listdir(scan_dir)
# print(dir_content(dir_to_scan))
def select_needed_files(file_list, needed_type):
'''Get list of needed files'''
res = []
for file in file_list:
if os.path.exists(dir_to_scan + '/' + file) \
and os.path.isfile(dir_to_scan + '/' + file) \
and file.split('.')[1] == needed_type:
res.append(file)
return res
# print(select_needed_files(['test3.txt', 'test2.txt', 'dir', 'test1.txt'], 'txt'))
def parse_file(path):
'''Return dictionary or questions and answers'''
# file = open('/home/junior/test/needed/cheat_sheet.txt')
file = open(path)
lines = file.readlines()
res = {}
questions = []
answers = []
for line in lines:
if line[0].isupper():
questions.append(line.rstrip())
if re.match(r'[ \t]', line):
answers.append(re.sub(r'(^[ \t]+|[ \t]+(?=:))', '', line.rstrip(), flags=re.M))
if len(questions) == len(answers):
res = dict(zip(questions, answers))
else:
print('Number of questions not equals to number of answers')
return res
# print(parse_file())
# Iterate dictionary
# fcards = parse_file()
# for q, a in fcards.items():
# print(q)
# print(a)
def write_to_db(data):
db = MySQLdb.connect(host='localhost',
user='root',
passwd='',
db='')
cur = db.cursor()
# INSERT INTO `cheat_sheet`(`question`, `number`) VALUES ('sdfsd1234','qwerqwe56743')
# sql = "INSERT INTO `cheat_sheet`(`question`, `number`) VALUES ('sdfsd1234','qwerqwe56743')"
# sql = "insert into city VALUES(null, '%s', '%s')" % \
# (question, answer)
for q, a in data.items():
# sql = "insert into cheat_sheet VALUES(null, '%s', '%s')" % (q, a)
# cur.execute(sql)
# escaping values before insert
sql = "INSERT INTO cheat_sheet (question, answer) VALUES (%s, %s)"
cur.execute(sql, (q, a))
db.commit() # call commit() method to save
db.close()
print('Fin!')
'''RUN'''
file_list = dir_content(dir_to_scan)
needed_file = select_needed_files(file_list, filetype_to_scan)
data = parse_file(dir_to_scan + '/' + needed_file[0])
# print(data)
write_to_db(data)
|
Java
|
UTF-8
| 587 | 2.921875 | 3 |
[] |
no_license
|
package aniket12;
import java.util.Scanner;
public class Nosum {
public static void main(String[] args) {
System.out.println("Enter the number :");
Scanner sc=new Scanner(System.in);
int num = sc.nextInt();
int r=0,sum=0;
while(num>0 || sum>=10)
{
if (num==0) {
num=sum;
sum=0;
}
r=num%10;
sum=sum+r;
num=num/10;
}
System.out.println(sum);
}
}
|
Shell
|
UTF-8
| 181 | 2.953125 | 3 |
[] |
no_license
|
#!/bin/bash
rt=$(ps -p "$1" -o etime | tail -1 | tr -d ' ')
mem=$(sudo pmap -x "$1" | tail -1 | grep -oE '[0-9]+' | head -1)
echo "Running time : $rt"
echo "Memory : $mem kB"
|
Python
|
UTF-8
| 235 | 4.375 | 4 |
[] |
no_license
|
animals = ['dog', 'cat', 'horse', 'cow', 'sheep']
for animal in animals:
print(animal)
print(f"\n")
for animal in animals:
print(f"A {animal} has four legs\n")
print(f"You can eat all these animals, except a {animals[1]}")
|
C++
|
UTF-8
| 1,623 | 4.40625 | 4 |
[] |
no_license
|
/*
Given n multiple digit numbers, return the maximum number
possible to obtain by aligning the given numbers in some order
A greedy strategy which works for the single digit problem
does not work in this case. A simple trick used here is to
convert numbers to strings and compare them digit by digit
(thus the concept of being larger than something has a different
meaning in the context of this algorithm)
Input: integer n where 1 <= n <= 100 followed by
n digits separated by spaces
Output: largest number possible formed by combination of input
numbers
*/
#include <algorithm>
#include <sstream>
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
using std::vector;
using std::string;
// Key part of the program. Compares integers digit
// by digit rather than standard greater than.
bool is_greater_than_or_equal(string n1, string n2) {
string a = n1 + n2;
string b = n2 + n1;
for (int i = 0; i < a.length(); i++) {
if (a[i] > b[i]) {
return true;
} else if (a[i] < b[i]) {
return false;
}
}
return false;
}
string largest_number(vector<string> a) {
std::stringstream ret;
for (size_t i = 0; i < a.size(); i++) {
ret << a[i];
}
string result;
ret >> result;
return result;
}
int main() {
// Number of ints to input
int n;
std::cin >> n;
vector<string> a(n);
// Input numbers as strings
for (size_t i = 0; i < a.size(); i++) {
std::cin >> a[i];
}
std::sort(a.begin(), a.end(), is_greater_than_or_equal);
std::cout << largest_number(a);
std::cout << std::endl;
return 0;
}
|
Markdown
|
UTF-8
| 4,010 | 2.75 | 3 |
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: Provision a Wi-Fi profile via a website
description: Allow your users to download a profile from a website, and provision it.
ms.topic: article
ms.date: 01/22/2020
---
# Provision a Wi-Fi profile via a website
The workflow described in this topic was introduced in Windows 10, version 2004. This topic shows how to configure a website so that a user can provision a profile for a Passpoint network (or for a normal network) prior to moving into range of the corresponding Wi-Fi access points. An example scenario is that of a user who might be planning to visit an airport or a conference for the first time, and they want to prepare in advance by downloading and provisioning a profile at home.
As a developer, you enable the workflow by providing an XML profile, and configuring a website. Your users can then provision a Wi-Fi profile by downloading it from your website via a web browser. On the user's device, the Wi-Fi profile is then provisioned by using URI activation and the Windows **Settings** app.
This workflow supersedes the mechanism in Internet Explorer for provisioning Wi-Fi profiles, which relies on Microsoft-specific JavaScript APIs. This new workflow is expected to work with all major browsers.
## The workflow in more detail
You can activate this workflow from a hyperlink that includes as an argument the download URI of the provisioning XML document.
```xml
ms-settings:wifi-provisioning?uri={download_uri}
```
For example, the following HTML markup gives a link to install the profile(s) that are found in a hypothetical document `http://contoso.com/ProvisioningDoc.xml`.
```html
<a href="ms-settings:wifi-provisioning?uri=http://contoso.com/ProvisioningDoc.xml">Install</a>
```
Your XML must adhere to the provisioning schema (see [Account provisioning](/windows-hardware/drivers/mobilebroadband/account-provisioning)). Your XML must also include one or more [WLANProfile](./wlan-profileschema-wlanprofile-element.md) elements. Each profile will be displayed in the **Add** dialog described next.
When the user clicks your HTML link, the installation workflow is invoked in the **Settings** app. Your provisioning XML document is downloaded by the **Settings** app. Once it's downloaded, information about the profiles, signature, and signer are displayed (provided that the document adheres to the schema).

The **Add** button in the dialog in the **Settings** app is enabled only if the provisioning file is signed and trusted.
## In your web page, determine whether this workflow is supported
There is no way in JavaScript to determine the exact build version of Windows. But if your user is using the Microsoft Edge web browser, then you can determine the version of Edge by inspecting the value of the `User-agent` HTTP header. If the version is greater than or equal to `18.nnnnn`, then the workflow is supported.
## Examples of provisioning XML profiles
These exemplify two common [Passpoint](/windows-hardware/drivers/mobilebroadband/hotspot-20) provisioning use cases, using PEAP or TTLS with username and password credentials. These XML files have been signed with a valid test certificate and can be installed to see the provisioning flow end-to-end.
### Passpoint profile using PEAP/EAP-MSCHAPv2
* [Download sample XML](https://winpptest.com/samples/PasspointWebProvisioningSamplePEAP.xml)
* [Install sample profile](ms-settings:wifi-provisioning?uri=https://winpptest.com/samples/PasspointWebProvisioningSamplePEAP.xml)
### Passpoint profile using TTLS/EAP-MSCHAPv2
* [Download sample XML](https://winpptest.com/samples/PasspointWebProvisioningSampleTTLS.xml)
* [Install sample profile](ms-settings:wifi-provisioning?uri=https://winpptest.com/samples/PasspointWebProvisioningSampleTTLS.xml)
## Related topics
* [Account provisioning](/windows-hardware/drivers/mobilebroadband/account-provisioning)
* [WLANProfile element](./wlan-profileschema-wlanprofile-element.md)
|
Markdown
|
UTF-8
| 4,368 | 3.078125 | 3 |
[
"MIT"
] |
permissive
|
# Units
[](https://www.npmjs.com/package/units)
[](https://www.npmjs.com/package/units)
Simple, module-like dependency injection system with two-step initialization and definable namespaces for application modules, plugins, and extensions.
## Example
```js
const Units = require('units');
const units = new Units();
class Controller {
constructor() {
this.db = undefined;
}
init({ db }) {
// getting components we're depended on
this.db = db;
}
}
units.add({
controller: new Controller()
})
units.init(); // calls init() function of every unit internally
```
## Unit
Unit is a simple interface
```js
class Controller {
constructor() {
this.db = undefined;
}
init({ 'db.mysql': db }) {
this.db = db;
}
}
```
### Interface methods and properties
#### init()
Initialize all the units.
#### initRequired = true
The unit with this property will be initialized when required.
#### instance / instance()
The property or function, If present it will be called when a unit is required and returned instead of unit class itself.
## Units
`Units` is a single class that manages all the structure. The root `Units` contains all the units. Child units can be added as in this example:
```js
// this is our root unit set
const units = new Units({
resources: {
user: {
api: new Api(),
controller: new Controller()
},
post: {
api: new Api(),
controller: new Controller()
}
}
});
```
This will create units `resources` as a container, `user`, `post` with units `api` and `controller`. From `resources.post.api` you have access to all units:
```js
class Api {
init({ controller, 'user.controller': user }) {
this.ctrl = controller;
this.user = user;
}
}
```
## Methods
### constructor(units)
If `units` present passes it to `add` method.
#### add()
Adds units or units sets. You can add a plain object, not Units, and it will create Units automatically. Examples:
```js
units.add({ user: {
api: new Api(),
controller: new Controller()
}})
//or
units.add({ user: () => ({
api: new Api(),
controller: new Controller()
})})
```
#### expose(obj)
like `add(obj)`, but `init` will not be called on this unit (so, a unit may omit `init` implementation), used to expose constant or any object without `init` method as a unit. If you want to expose an object when you use the `add` method you can add the `@expose` property to the object you want to expose. Example:
```js
const units = new Units({
constants: {
'@expose': true,
a: 'a',
b: 'b'
}
})
```
#### extend(obj)
Like expose but if unit exist just extends it with `obj`. If you want to extend an object when you use `add` method you can add `@extend` property to the object you want to expose. Example:
```js
const units = new Units({
constants: {
'@expose': true,
a: 'a',
b: 'b'
}
});
units.add({
constants: {
'@extend': true,
c: 'c'
}
})
```
### join(units)
Adds all the units from `units` to self, without any extra magic
### alias(aliasKey, srcKey)
Sets the alias `aliasKey` for unit `srcKey`
### isEmpty()
Returns `true` if unit does not have child units. Otherwise returns `false`.
### has(key)
Returns `true` if units exist under the `key`. Otherwise returns `false`.
### get(key)
Gets unit under `key` specified, tries parent if no unit found and parent is present. If `key` omitted and units instance has representation returns it.
### require(key)
Calls `get` internally and returns a result if not null, otherwise, throws an error
### match(regexp, function)
Calls the `function` for every unit name that matches `regexp`. The first argument in the function is always the matched unit. All others are matches from the regexp.
```js
//example from matter-in-motion lib
units
.get('resources')
.match('^(.*)\.api$', (unit, name) => console.log(name));
```
### forEach(function)
Calls the 'function' for every unit.
```js
units.forEach((unit, name) => console.log(name));
```
### init()
Calls `init` method on all added units
## Iterable
```js
for (let key of units) {
console.log(key); // will print all units keys from this unit set
}
```
License MIT
|
Python
|
UTF-8
| 4,212 | 2.953125 | 3 |
[
"Unlicense"
] |
permissive
|
"""
Create a standalone Dockerfile that pulls the recipes from Github.
This script concatenates Dockerfile_base and Dockerfile_fenics and replaces the
ADD command with a 'git clone'. Furthermore, it updates the environment
variables that specify which version of FEniCS to build.
This script requires Python 3.
Usage examples:
>> python create_dockerfile.py --branch master
>> python create_dockerfile.py --branch 1.6.0
This will create a Dockerfile. Build it with:
> docker build -t fenics Dockerfile .
"""
import argparse
import os
import re
import sys
def parseCommandLine():
"""
Parse program arguments.
"""
# Create the parser.
parser = argparse.ArgumentParser(
description=('Create standalone Dockerfiles for '
'individual FEniCS versions'),
formatter_class=argparse.RawTextHelpFormatter)
# Shorthand.
padd = parser.add_argument
# Add the command line options.
padd('--branch', metavar='tag/branch', type=str, default='master',
help='Tag/branch of FEniCS repository to use (default=master)')
padd('--test', action='store_true', default=False,
help='Run the tests during build (default=off)')
# Run the parser.
param = parser.parse_args()
# Determine the Git branch/tag and the corresponding version tag assigned
# to the Anaconda packages that will be created.
if param.branch == 'master':
pkg_version = '1.7.0dev'
elif param.branch == '1.6.0':
pkg_version = param.branch
else:
print('Unsupported branch <{}>'.format(param.branch))
sys.exit(1)
param.pkg_version = pkg_version
return param
def stripHeader(lines: list):
# Verify that exactly one line starts with 'MAINTAINER'.
tmp = [idx for idx, line in enumerate(lines)
if line.startswith('MAINTAINER')]
assert len(tmp) == 1
idx = tmp[0]
# Drop all lines prior to the MAINTAINER line.
return lines[idx + 1:]
def main():
# Parse command line for package version information.
param = parseCommandLine()
# Define the names of the input/output Dockerfile.
fname_base = '../Dockerfile_base'
fname_fenics = '../Dockerfile'
fname_out = 'Dockerfile_{}'.format(param.branch)
# Read the Docker files.
docker_base = open(fname_base, 'r').readlines()
docker_fenics = open(fname_fenics, 'r').readlines()
# Strip the file headers.
docker_base = stripHeader(docker_base)
docker_fenics = stripHeader(docker_fenics)
# Define the header for the new Dockerfile.
header = [
'FROM continuumio/anaconda:latest\n'
'MAINTAINER Oliver Nagy <olitheolix@gmail.com>\n'
]
# Concatenate the header and the two old Docker files.
dockerfile = header + docker_base + docker_fenics
dockerfile = ''.join(dockerfile)
# Replace the ADD command with the correct clone command.
dockerfile = re.sub(
r'^ADD .*',
'RUN git clone https://github.com/olitheolix/fenics-recipes.git',
dockerfile,
flags=re.MULTILINE
)
# Set the correct value for FENICS_BRANCH.
dockerfile = re.sub(
r'^ENV FENICS_BRANCH .*',
'ENV FENICS_BRANCH "{branch}"'.format(branch=param.branch),
dockerfile,
flags=re.MULTILINE
)
# Set the correct value for FENICS_ANACONDA_PACKAGE_VERSION.
version = '\'"{}"\''.format(param.pkg_version)
dockerfile = re.sub(
r'^ENV FENICS_ANACONDA_PACKAGE_VERSION .*',
'ENV FENICS_ANACONDA_PACKAGE_VERSION {ver}'.format(ver=version),
dockerfile,
flags=re.MULTILINE
)
# Deactivate the tests. By default, the build commands in the Dockerfile
# use the '--no-test' flag. If the user wants to run the tests during build
# then we need to delete it.
if param.test is True:
dockerfile = dockerfile.replace(' --no-test', '')
# Write the Dockerfile and print basic build instructions.
open(fname_out, 'w').write(dockerfile)
print('Wrote build instructions to <{}>'.format(fname_out))
print('Build with eg: >> docker build -t fenics:{} -f {} .'
.format(param.branch, fname_out))
if __name__ == '__main__':
main()
|
Java
|
UTF-8
| 9,439 | 1.65625 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.aws.greengrass.lambdatransformer;
import com.amazon.aws.iot.greengrass.component.common.ComponentRecipe;
import com.amazon.aws.iot.greengrass.component.common.ComponentType;
import com.amazon.aws.iot.greengrass.component.common.DependencyProperties;
import com.amazon.aws.iot.greengrass.component.common.DependencyType;
import com.amazon.aws.iot.greengrass.component.common.Platform;
import com.amazon.aws.iot.greengrass.component.common.RecipeFormatVersion;
import com.aws.greengrass.deployment.templating.exceptions.RecipeTransformerException;
import com.aws.greengrass.lambdatransformer.common.models.DefaultConfiguration;
import com.aws.greengrass.lambdatransformer.common.models.LambdaRuntime;
import com.aws.greengrass.lambdatransformer.common.models.LambdaTemplateParams;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vdurmont.semver4j.Semver;
import org.hamcrest.CoreMatchers;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.aws.greengrass.lambdatransformer.common.Constants.LAMBDA_SETENV_ARN_PARAM_NAME;
import static com.aws.greengrass.lambdatransformer.common.Constants.LAMBDA_SETENV_HANDLER_PARAM_NAME;
import static com.aws.greengrass.lambdatransformer.common.Constants.LAMBDA_SETENV_LAMBDA_RUNTIME_PARAM_NAME;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class LambdaTransformerTest {
private static final ObjectMapper OBJECT_MAPPER =
new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
@Test
public void GIVEN_lambdaRequest_WHEN_create_component_from_lambda_no_dependencies_THEN_return_expected_values() throws Exception {
Map<String, Object> templateParams = new HashMap<String, Object>() {{
put("lambdaArn", TestData.LAMBDA_FUNCTION_ARN_1);
put("lambdaRuntime", LambdaRuntime.Python37);
put("lambdaHandler", TestData.LAMBDA_FUNCTION_HANDLER);
}};
LambdaTemplateParams params = TestData.LAMBDA_PARAMETERS_2
.platforms(Collections.singletonList(TestData.windows))
.build();
ComponentRecipe paramFile = ComponentRecipe.builder()
.recipeFormatVersion(RecipeFormatVersion.JAN_25_2020)
.componentName(TestData.COMPONENT_NAME_1)
.componentVersion(new Semver(TestData.COMPONENT_VERSION_STR_1))
.templateParameters(templateParams)
.build();
ComponentRecipe generated = new LambdaTransformer().transform(paramFile, params);
verifyGeneratedComponentRecipe(generated, TestData.COMPONENT_NAME_1, new Semver(TestData.COMPONENT_VERSION_STR_1), params);
}
@Test
public void GIVEN_lambdaRequest_WHEN_create_component_from_lambda_multiple_dependencies_THEN_return_expected_values() throws Exception {
DependencyProperties property1 = DependencyProperties.builder()
.dependencyType(DependencyType.SOFT)
.versionRequirement("<2.0.0")
.build();
DependencyProperties property2 = DependencyProperties.builder()
.dependencyType(DependencyType.HARD)
.versionRequirement(">1.0.0")
.build();
HashMap<String, DependencyProperties> dependencies = new HashMap<String, DependencyProperties>() {{
put("CUSTOMER_DEPENDENCY_1", property1);
put("CUSTOMER_DEPENDENCY_2", property2);
}};
Map<String, Object> templateParams = new HashMap<String, Object>() {{
put("lambdaArn", TestData.LAMBDA_FUNCTION_ARN_1);
put("lambdaRuntime", LambdaRuntime.Python37);
put("lambdaHandler", TestData.LAMBDA_FUNCTION_HANDLER);
}};
LambdaTemplateParams params = TestData.LAMBDA_PARAMETERS_2
.platforms(Collections.singletonList(TestData.all))
.componentDependencies(dependencies)
.build();
ComponentRecipe paramFile = ComponentRecipe.builder()
.recipeFormatVersion(RecipeFormatVersion.JAN_25_2020)
.componentName(TestData.COMPONENT_NAME_1)
.componentVersion(new Semver(TestData.COMPONENT_VERSION_STR_1))
.templateParameters(templateParams)
.build();
ComponentRecipe generated = new LambdaTransformer().transform(paramFile, params);
verifyGeneratedComponentRecipe(generated, TestData.COMPONENT_NAME_1, new Semver(TestData.COMPONENT_VERSION_STR_1), params);
}
@ParameterizedTest
@NullAndEmptySource
public void GIVEN_lambdaRequest_WHEN_create_component_from_lambda_with_empty_platform_THEN_throw_transformer_exception(List<Platform> platforms) {
Map<String, Object> templateParams = new HashMap<String, Object>() {{
put("lambdaArn", TestData.LAMBDA_FUNCTION_ARN_1);
put("lambdaRuntime", LambdaRuntime.Python37);
put("lambdaHandler", TestData.LAMBDA_FUNCTION_HANDLER);
}};
LambdaTemplateParams params = TestData.LAMBDA_PARAMETERS_2
.platforms(platforms)
.build();
ComponentRecipe paramFile = ComponentRecipe.builder()
.recipeFormatVersion(RecipeFormatVersion.JAN_25_2020)
.componentName(TestData.COMPONENT_NAME_1)
.componentVersion(new Semver(TestData.COMPONENT_VERSION_STR_1))
.templateParameters(templateParams)
.build();
final RecipeTransformerException ex = assertThrows(RecipeTransformerException.class,
() -> new LambdaTransformer().transform(paramFile, params)
);
assertThat(ex.getMessage(), CoreMatchers.containsString("At least one platform is expected to be set by caller"));
}
void verifyGeneratedComponentRecipe(ComponentRecipe recipe, String providedComponentName,
Semver providedComponentVerison, LambdaTemplateParams params) {
assertEquals(recipe.getComponentVersion(), providedComponentVerison);
assertEquals(recipe.getComponentName(), providedComponentName);
assertEquals(recipe.getComponentType(), ComponentType.LAMBDA);
assertEquals(recipe.getManifests().size(), 1);
// only 1 platform is ever given, so this is ok (for now)
assertEquals(recipe.getManifests().get(0).getPlatform(), params.getPlatforms().get(0));
assertEquals(recipe.getManifests().get(0).getArtifacts().size(), 1);
// manifests::lifecycle should be empty
assertEquals(recipe.getManifests().get(0).getLifecycle().size(), 0);
// top-level lifecycle tag contains all lifecycle info
Map<String, Object> lifecycleMap = recipe.getLifecycle();
Map<String, Object> startupMap = (Map<String, Object>) lifecycleMap.get("startup");
assertThat(startupMap, hasEntry("requiresPrivilege", true));
assertThat(startupMap, hasEntry(equalTo("script"), notNullValue()));
Map<String, Object> shutdownMap = (Map<String, Object>) lifecycleMap.get("shutdown");
assertThat(shutdownMap, hasEntry("requiresPrivilege", true));
assertThat(shutdownMap, hasEntry(equalTo("script"), notNullValue()));
assertEquals(recipe.getComponentDependencies().size(), params.getComponentDependencies().size());
assertNotNull(recipe.getComponentConfiguration().getDefaultConfiguration());
assertNotEquals(recipe.getComponentConfiguration().getDefaultConfiguration().size(), 0);
DefaultConfiguration configuration = OBJECT_MAPPER.convertValue(
recipe.getComponentConfiguration().getDefaultConfiguration(), DefaultConfiguration.class);
Map<String, String> setEnv = (Map<String, String>) recipe.getLifecycle().get("setenv");
assertEquals(setEnv.get(LAMBDA_SETENV_ARN_PARAM_NAME), params.getLambdaArn());
assertEquals(setEnv.get(LAMBDA_SETENV_HANDLER_PARAM_NAME), params.getLambdaHandler());
assertEquals(setEnv.get(LAMBDA_SETENV_LAMBDA_RUNTIME_PARAM_NAME), params.getLambdaRuntime().toString());
assertEquals(configuration.getContainerMode(), params.getContainerMode());
assertEquals(configuration.getInputPayloadEncodingType(), params.getInputPayloadEncodingType());
assertEquals(configuration.getTimeoutInSeconds(), params.getTimeoutInSeconds());
assertEquals(configuration.getMaxIdleTimeInSeconds(), params.getMaxIdleTimeInSeconds());
assertEquals(configuration.getMaxInstancesCount(), params.getMaxInstancesCount());
assertEquals(configuration.getMaxQueueSize(), params.getMaxQueueSize());
}
}
|
C#
|
UTF-8
| 963 | 2.765625 | 3 |
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
enum EquipType { hat, chest, gloves, pants, feet, mainHand, offHand, twoHand }
[CreateAssetMenu(fileName = "Equipment", menuName = "Items/Equipment", order = 2)]
public class Equipment : Item
{
[SerializeField]
private EquipType equipType;
[SerializeField]
private int stamina;
[SerializeField]
private int strength;
[SerializeField]
private int intellegence;
public override string GetDescription()
{
string stats = string.Empty;
if (intellegence > 0)
{
stats += string.Format("\n +{0} intellegence", intellegence);
}
if (strength > 0)
{
stats += string.Format("\n +{0} strength", strength);
}
if (stamina > 0)
{
stats += string.Format("\n +{0} stamina", stamina);
}
return base.GetDescription();
}
}
|
JavaScript
|
UTF-8
| 2,965 | 2.671875 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
import React from 'react';
import * as d3 from 'd3';
class RoleSelector extends React.Component { // eslint-disable-line react/prefer-stateless-function
constructor(props) {
super(props);
this.state = {
Top: true,
Jungle: true,
Middle: true,
ADC: true,
Support: true,
style: {
Top: $("<style type='text/css'>").appendTo('head'),
Jungle: $("<style type='text/css'>").appendTo('head'),
Middle: $("<style type='text/css'>").appendTo('head'),
ADC: $("<style type='text/css'>").appendTo('head'),
Support: $("<style type='text/css'>").appendTo('head'),
}
};
}
componentDidMount() {
d3.selectAll(".roleBox")
.style("color", ((d, i) => {
return this.props.color(i);
}));
}
filterRole(role) {
// The role filter use a really dumb idea
// We create a stylesheet in the head of our document with a rule that says if the element is hidden or visible
// We do that because we want to set the rule directly in our CSS and not on our inline element
// Because our data circles are reappended every time there is a zoom
// Otherwise we would need to make a function call every time our circle would get reappended
// Still this solution is dumb. I'm sorry dear god of programming.
const css = "." + role + " { visibility: " + (this.state[role] ? 'hidden' : 'visible') + "}";
this.state.style[role].html(css);
this.setState({
[role]: !this.state[role]
});
}
render() {
return (
<div id="roleCheck" style={{ width: 90, float: "left", marginTop: 40 }}>
<div className="roleBox">
<label htmlFor="topCheckbox">
<input type="checkbox" checked={this.state.Top} id="topCheckbox" value="Top" onChange={() => this.filterRole('Top')} /> Top
</label>
</div>
<div className="roleBox">
<label htmlFor="jungleCheckbox">
<input type="checkbox" checked={this.state.Jungle} id="jungleCheckbox" value="Jungle" onChange={() => this.filterRole('Jungle')} /> Jungle
</label>
</div>
<div className="roleBox">
<label htmlFor="middleCheckbox">
<input type="checkbox" checked={this.state.Middle} id="middleCheckbox" value="Middle" onChange={() => this.filterRole('Middle')} /> Middle
</label>
</div>
<div className="roleBox">
<label htmlFor="ADCCheckbox">
<input type="checkbox" checked={this.state.ADC} id="ADCCheckbox" value="ADC" onChange={() => this.filterRole('ADC')} /> ADC
</label>
</div>
<div className="roleBox">
<label htmlFor="supportCheckbox">
<input type="checkbox" checked={this.state.Support} id="supportCheckbox" value="Support" onChange={() => this.filterRole('Support')} /> Support
</label>
</div>
</div>
);
}
}
export default RoleSelector;
|
Markdown
|
UTF-8
| 7,293 | 3.1875 | 3 |
[] |
no_license
|
formX
=====
FormX is a Javascript-based mapping between XML content and web forms.
It consists of three parts, or rather two, and you're responsible for
the third. There is the formX object, which provides methods for
loading data from an XML file into a web form, a mapping file, the
spcification for which may be found below, and a web form, for which you
are completely responsible. FormX doesn't say anything about what it has
to look like, except that you have to use the same naming conventions
you use in the mapping. The goal of formX is to allow the development of
HTML forms capable of editing any reasonably data-oriented XML while
preserving the formatting of that XML without the overhead of using XForms.
## The formX object ##
The most important functions are
formX.populateForm()
and
formX.updateXML()
The first of these uses the mapping file stored in `formX.mapping` to
load data from the XML file stored in `formX.xml` into the an HTML form
in the current web page. The second pulls data out of the form and
writes it back into the XML, again using the mapping file to decide
where to put it.
## The mapping file ##
The mapping file is a javascript file looking something like:
var map = {
namespaces: {"#default": "http://www.tei-c.org/ns/1.0",
"t": "http://www.tei-c.org/ns/1.0"},
indent: " ",
elements: [
{xpath: "/t:TEI/t:teiHeader/t:fileDesc/t:titleStmt/t:title",
tpl: "<title>$title</title>"},
{xpath: "/t:TEI/t:teiHeader/t:fileDesc/t:titleStmt/t:author",
tpl: "<author>$author</author>"}]
models: { "http://www.tei-c.org/ns/1.0":
{titleStmt: ["title", "author"]}},
functions: {
// A list of function definitions that may be applied to data on
// its way out of the XML or on its way back in.
}}
### namespaces ###
A map of namespaces used in the source document. To set a default
namespace, add a member named "#default" and this namespace will be
returned whenever no prefix is used.
### indent ###
The amount of whitespace (spaces or tabs) by which child elements should
be indented.
### elements ###
Individual `elements` in formX are Javascript objects that may possess
the following members:
{name: "language",
xpath: "/t:TEI/t:teiHeader/t:fileDesc/t:sourceDesc/t:msDesc/t:msContents/t:msItem/t:textLang",
children: ["@mainLang", "@otherLangs", "."],
tpl: "<textLang mainLang=\"$mainLang\"[ otherLangs=\"$otherLangs\"]>$textLang</textLang>",
multi: false}
Only two of these, `xpath` and `tpl` are always required. `xpath` is
simply the XPath (using a namespace prefix defined in the mapping's
`namespaces` member) to the data you want in the XML file. `tpl` is a
template to be used when the XML is written back. Variables to be
substituted for values in the form are prefixed with a `$`. In the HTML
form, the `input`s or `textarea`s will be given names corresponding to
the variable names (prefixed by the map's prefix, so
<input name="your_prefix_textLang" type="text">
for the `$textLang` variable above. Optional
sections are surrounded by brackets, so the `otherLangs` attribute above
may be populated or not. Optional sections may nest, as we'll see below.
`children` contains an array of nodes relative to the XPath supplied in `xpath`,
given in the same order as the variables in the template. A `name` is
only needed when there is either a group of values that go together, as
above, or when there may be multiple values, so that form fields will
need to be duplicated. In this case, the HTML form must wrap such groups
or fields to be duplicated in a div or span with a @class attribute that
uses the value in the `name`. Finally, `multi`, if true, denotes an
`element` that may be duplicated.
### models ###
In order to know exactly where new elements should be inserted, formX
will sometimes need a simplified content model for the parent element.
This is a Javascript object where element names are mapped to ordered
lists of possible child elements. This is so that, given an XML document
where a parent element has a child already, and another child element of
a different type is to be inserted, formX will know whether to insert
the new element before or after the existing one.
### functions ###
Functions that may be called on either values extracted from the XML or
on values from the form. For example, in TEI, dates may be given in the
following way:
<date when="2012-05-08">May 8th, 2012</date>
with a `@when` (or `@notBefore`/`@notAfter`) attribute that uses an ISO
date format (YYYY-MM-DD with a minus sign before for BCE dates). But in
an HTML form, you might want to split out the year, month, and
day values in `@when` so that it's easier for a layperson to edit the
values, and so that they can ignore leading zeroes. Maybe you'd want to
give them a dropdown to choose between BCE and CE, and so on. You can
write functions that do this kind of pre- and post-processing on form
values. For example:
{name: "origDate",
xpath: "/t:TEI/t:teiHeader/t:fileDesc/t:sourceDesc/t:msDesc/t:history/t:origin/t:origDate",
children: [["@when","getYear"],["@when", "getMonth"], ["@when", "getDay"], ["@notBefore","getYear"],["@notBefore", "getMonth"], ["@notBefore", "getDay"], ["@notAfter","getYear"],["@notAfter", "getMonth"], ["@notAfter", "getDay"], "."],
tpl: "<origDate[ when=\"~pad('$year', 4)~{-~pad('$month', 2)~}{-~pad('$day',2)~}\"][ notBefore=\"~pad('$year1',4)~{-~pad('$month1',2)~}{-~pad('$day1',2)~}\" notAfter=\"~pad('$year2',4)~{-~pad('$month2',2)~}{-~pad('$day2',2)~}\"]>$origDate</origDate>"},
In the `children` property, you'll notice that instead of just relative
XPaths, we have an array containing an XPath and a function name, so
when the child corresponding to the `$year` variable (i.e. the `@when`
attribute) is retrieved, it will be piped through the `getYear()`
function defined in the `functions` section. This function pulls out
just the year from the full date.
In the origDate template, we see:
<origDate[ when=\"~pad('$year', 4)~{-~pad('$month', 2)~}{-~pad('$day',2)~}\"]
meaning that the `@when` attribute is optional, but if you have one, it
must have at least a year, followed by an optional month and day (there
are those nested options using curly braces). The value of `$year` is
piped through the `pad()` function, again defined in the `functions`
section, and this zero-pads the year from the form so that it is four
digits long. So the values in the form might be
Year: -99
Month: 8
Day: 7
But what would go into the XML would be "-0099-08-07". These functions
can also perform validation tasks.
## The HTML Form ##
Unlike XForms, formX has nothing at all to say about the construction of
the HTML form to be used in editing the XML, except that its fields'
`@name` attributes must correspond to variable names in the mapping, and
groups of fields and/or fields that may be duplicated must be enclosed by
an element bearing a `@class` attribute with a value corresponding to
the `name` of the `element` in the mapping. Apart from these naming
conventions, you are free to build the form in any way you see fit.
|
Markdown
|
UTF-8
| 761 | 2.578125 | 3 |
[] |
no_license
|
# e-commerce-website
This project deals with developing an e-commerce website for Online Product Sales.
It provides the user with a catalog of different products available for purchase in the store.
In order to facilitate online purchases, a shopping cart is provided to the user.
[](https://postimg.cc/dZdwqxcN)
[](https://postimg.cc/ctQGqtfV)
[](https://postimg.cc/Vr83qLxg)
|
Markdown
|
UTF-8
| 20,852 | 2.734375 | 3 |
[] |
no_license
|
---
title: MySQL
date: 2017-04-16T09:00:00.000Z
tags: null
---
# SQL:DDL,DML
## DDL:Data Defination Language `mysql> HELP Data Definition`
```
CREATE, ALTER, DROP
DATABASE, TABLE
INDEX, VIEW, USER
FUNCTION, FUNCTION UDF, PROCEDURE, TABLESPACE, TRIGGER, SERVER
```
## DML: Data Manipulation Language `mysql> HELP Data Manipulation`
```
INSERT/REPLACE, DELETE, SELECT, UPDATE
```
## 数据库:
> 对于MySQL而言,每个数据库(DATABASE)其实就是对应数据目录(datadir)下的一个目录(db_name),用于规定一个项目或者方案的集合,因此DATABASE也被称为SCHEMA;
```
CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name CHARACTER SET [=] charset_name COLLATE [=] collation_name
ALTER {DATABASE | SCHEMA} [db_name] CHARACTER SET [=] charset_name COLLATE [=] collation_name
DROP {DATABASE | SCHEMA} [IF EXISTS] db_name
```
<!-- more -->
### #
**示例:** 显示当前已存在的所有数据库;
```
MariaDB [(none)]> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| test |
+--------------------+
4 rows in set (0.00 sec)
```
**创建一个数据库 CREATE DATABASE;**
```
MariaDB [(none)]> CREATE DATABASE mydb;
Query OK, 1 row affected (0.00 sec)
```
如果要创建的数据库已存在,就会报错;如果此时是一个sql脚本的话执行到这里就中断了;
```
MariaDB [(none)]> CREATE DATABASE mydb;
ERROR 1007 (HY000): Can't create database 'mydb'; database exists
```
创建数据库时可以加上条件判断 IF NOT EXISTS ;这样只会出现警告,而不会报错中断操作;可以使用命令 SHOW WARNINGS 查看;
```
MariaDB [(none)]> CREATE DATABASE IF NOT EXISTS mydb;
Query OK, 1 row affected, 1 warning (0.00 sec)
MariaDB [(none)]> CREATE DATABASE IF NOT EXISTS mydb;
Query OK, 1 row affected, 1 warning (0.00 sec)
MariaDB [(none)]> SHOW WARNINGS;
+-------+------+-----------------------------------------------+
| Level | Code | Message |
+-------+------+-----------------------------------------------+
| Note | 1007 | Can't create database 'mydb'; database exists |
+-------+------+-----------------------------------------------+
1 row in set (0.00 sec)
```
创建数据库时可以指定默认字符集 CHARATER SET;
```
MariaDB [(none)]> CREATE DATABASE IF NOT EXISTS testdb CHARACTER SET utf8;
Query OK, 1 row affected (0.00 sec)
```
**如果要创建数据库时忘记指定字符集,可以使用ALTER DATABASE 修改;**
```
MariaDB [(none)]> ALTER DATABASE mydb CHARATER SET utf8;
Query OK, 1 row affected (0.00 sec)
```
**删除一个数据库 DROP DATABASE;**
```
MariaDB [(none)]> DROP DATABASE testdb;
Query OK, 0 rows affected (0.00 sec)
```
同样,如果要删除的数据库不存在,就会报错;可以加上条件判断IF EXISTS 以避免报错;
```
MariaDB [(none)]> DROP DATABASE testdb;
ERROR 1008 (HY000): Can't drop database 'testdb'; database doesn't exist
MariaDB [(none)]> DROP DATABASE IF EXISTS testdb;
Query OK, 0 rows affected, 1 warning (0.00 sec)
```
### #
## 表:
> 表名是否区分大小写取决于文件系统,强烈建议不要使用仅仅大小写不同的表名;
### CREATE:
#### 语法1
```
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
(create_definition,...)
[table_options]
[partition_options]
```
#### 语法2
```
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
[(create_definition,...)]
[table_options]
[partition_options]
select_statement
```
> 通过查询语句来创建表,直接将查询语句的结果插入到新创建的表中;只能复制字段名和类型,不能复制字段定义;
#### 语法3
```
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
{ LIKE old_tbl_name | (LIKE old_tbl_name) }
```
> 复制某存在的表的结构来创建新的空表;
#### 选项
```
create_definition:
col_name column_definition
```
```
column_definition:
data_type [NOT NULL | NULL] [DEFAULT default_value]
[AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]
[COMMENT 'string']
[COLUMN_FORMAT {FIXED|DYNAMIC|DEFAULT}]
```
```
table_options:
ENGINE [=] engine_name
```
查看支持的所有存储引擎: `mysql> SHOW ENGINES;` 查看指定表的存储引擎: `mysql> SHOW TABLE STATUS LIKE clause;` 查看使用指定存储引擎的表: `mysql> SHOW TABLE STATUS WHERE Engine='InnoDB'\G`
### DROP:
```
DROP [TEMPORARY] TABLE [IF EXISTS] tbl_name [, tbl_name];
```
### ALTER:
```
ALTER TABLE tbl_name
[alter_specification [, alter_specification] ...]
```
可修改内容:
```
* table_options
* 添加定义:ADD
- 字段、字段集合、索引、约束
* 修改字段:
- CHANGE [COLUMN] old_col_name new_col_name column_definition [FIRST|AFTER col_name]
- MODIFY [COLUMN] col_name column_definition [FIRST | AFTER col_name]
* 删除操作:DROP
- 字段、索引、约束
```
表重命名: `RENAME [TO|AS] new_tbl_name`
### 查看表结构定义:
```
DESC tbl_name;
```
### 查看表定义:
```
SHOW CREATE TABLE tbl_name
```
### 查看表属性信息:
```
SHOW TABLE STATUS [{FROM | IN} db_name] [LIKE 'pattern' | WHERE expr]
```
#### #
**示例:** **创建一张表**
```
CREATE TABLE tbl1;`
```
创建表tbl2,指定字段列数据类型、主键等信息;
```
MariaDB [(none)]> USE mydb;
Database changed
MariaDB [mydb]> CREATE TABLE tbl2(id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, name CHAR(20));
Query OK, 0 rows affected (0.00 sec)
MariaDB [mydb]> DESC tbl2;
+-------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------------------+------+-----+---------+----------------+
| id | tinyint(3) unsigned | NO | PRI | NULL | auto_increment |
| name | char(20) | YES | | NULL | |
+-------+---------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
```
创建表tbl3,单独指定主键
```
MariaDB [mydb]> CREATE TABLE tbl3(id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT, name CHAR(20), PRIMARY KEY(id));
Query OK, 0 rows affected (0.01 sec)
MariaDB [mydb]> DESC tbl3;
+-------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------------------+------+-----+---------+----------------+
| id | tinyint(3) unsigned | NO | PRI | NULL | auto_increment |
| name | char(20) | YES | | NULL | |
+-------+---------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
```
创建表tbl4,同时给指定字段创建索引;
```
MariaDB [mydb]> CREATE TABLE tbl4(id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT, name CHAR(20), age TINYINT UNSIGNED, PRIMARY KEY(id), index(name));
MariaDB [mydb]> DESC tbl4;
+-------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------------------+------+-----+---------+----------------+
| id | tinyint(3) unsigned | NO | PRI | NULL | auto_increment |
| name | char(20) | YES | MUL | NULL | |
| age | tinyint(3) unsigned | YES | | NULL | |
+-------+---------------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
```
查看表tbl4的索引信息;注意到,这里有两行,第一行是主键索引 PRIMARY 针对 id 字段,第二行是自定义索引 name 针对 name 字段;由于自定义的索引未指定索引名,因此默认索引名与字段名一样;
```
MariaDB [mydb]> SHOW INDEXES FROM tbl4;
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| tbl4 | 0 | PRIMARY | 1 | id | A | 0 | NULL | NULL | | BTREE | | |
| tbl4 | 1 | name | 1 | name | A | 0 | NULL | NULL | YES | BTREE | | |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
2 rows in set (0.00 sec)
MariaDB [mydb]> SHOW INDEXES FROM tbl4\G
*************************** 1\. row ***************************
Table: tbl4
Non_unique: 0
Key_name: PRIMARY
Seq_in_index: 1
Column_name: id
Collation: A
Cardinality: 0
Sub_part: NULL
Packed: NULL
Null:
Index_type: BTREE
Comment:
Index_comment:
*************************** 2\. row ***************************
Table: tbl4
Non_unique: 1
Key_name: name
Seq_in_index: 1
Column_name: name
Collation: A
Cardinality: 0
Sub_part: NULL
Packed: NULL
Null: YES
Index_type: BTREE
Comment:
Index_comment:
2 rows in set (0.00 sec)
```
查看表的索引信息;
```
MariaDB [mydb]> show table status;
+------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+-----------------+----------+----------------+---------+
| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment |
+------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+-----------------+----------+----------------+---------+
| tbl2 | InnoDB | 10 | Compact | 0 | 0 | 16384 | 0 | 0 | 9437184 | 1 | 2017-06-03 22:24:47 | NULL | NULL | utf8_general_ci | NULL | | |
| tbl3 | InnoDB | 10 | Compact | 0 | 0 | 16384 | 0 | 0 | 9437184 | 1 | 2017-06-03 22:29:15 | NULL | NULL | utf8_general_ci | NULL | | |
| tbl4 | InnoDB | 10 | Compact | 0 | 0 | 16384 | 0 | 16384 | 9437184 | 1 | 2017-06-03 22:51:45 | NULL | NULL | utf8_general_ci | NULL | | |
+------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+-----------------+----------+----------------+---------+
3 rows in set (0.00 sec)
MariaDB [mydb]> SHOW TABLE STATUS\G
*************************** 1\. row ***************************
Name: tbl2
Engine: InnoDB
Version: 10
Row_format: Compact
Rows: 0
Avg_row_length: 0
Data_length: 16384
Max_data_length: 0
Index_length: 0
Data_free: 9437184
Auto_increment: 1
Create_time: 2017-06-03 22:24:47
Update_time: NULL
Check_time: NULL
Collation: utf8_general_ci
Checksum: NULL
Create_options:
Comment:
*************************** 2\. row ***************************
Name: tbl3
Engine: InnoDB
Version: 10
Row_format: Compact
Rows: 0
Avg_row_length: 0
Data_length: 16384
Max_data_length: 0
Index_length: 0
Data_free: 9437184
Auto_increment: 1
Create_time: 2017-06-03 22:29:15
Update_time: NULL
Check_time: NULL
Collation: utf8_general_ci
Checksum: NULL
Create_options:
Comment:
*************************** 3\. row ***************************
Name: tbl4
Engine: InnoDB
Version: 10
Row_format: Compact
Rows: 0
Avg_row_length: 0
Data_length: 16384
Max_data_length: 0
Index_length: 16384
Data_free: 9437184
Auto_increment: 1
Create_time: 2017-06-03 22:51:45
Update_time: NULL
Check_time: NULL
Collation: utf8_general_ci
Checksum: NULL
Create_options:
Comment:
3 rows in set (0.01 sec)
MariaDB [mydb]> SHOW TABLE STATUS LIKE 'tbl4'\G
*************************** 1\. row ***************************
Name: tbl4
Engine: InnoDB
Version: 10
Row_format: Compact
Rows: 0
Avg_row_length: 0
Data_length: 16384
Max_data_length: 0
Index_length: 16384
Data_free: 9437184
Auto_increment: 1
Create_time: 2017-06-03 22:51:45
Update_time: NULL
Check_time: NULL
Collation: utf8_general_ci
Checksum: NULL
Create_options:
Comment:
1 row in set (0.00 sec)
```
创建表tbl5,表选项 table_options 指定存储引擎 ENGINE ;
```
MariaDB [mydb]> CREATE TABLE tbl5(id INT) ENGINE MyISAM;
Query OK, 0 rows affected (0.00 sec)
MariaDB [mydb]> DESC tbl5;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
1 row in set (0.01 sec)
MariaDB [mydb]> SHOW TABLE STATUS WHERE ENGINE='MyISAM'\G
*************************** 1\. row ***************************
Name: tbl5
Engine: MyISAM
Version: 10
Row_format: Fixed
Rows: 0
Avg_row_length: 0
Data_length: 0
Max_data_length: 1970324836974591
Index_length: 1024
Data_free: 0
Auto_increment: NULL
Create_time: 2017-06-03 23:26:08
Update_time: 2017-06-03 23:26:08
Check_time: NULL
Collation: utf8_general_ci
Checksum: NULL
Create_options:
Comment:
1 row in set (0.00 sec)
```
使用SELECT语句查询获取的数据创建表tbl6;
```
MariaDB [mydb]> CREATE TABLE tbl6 SELECT Host,User,Password From mysql.user;
Query OK, 8 rows affected (0.02 sec)
Records: 8 Duplicates: 0 Warnings: 0
MariaDB [mydb]> DESC tbl6;
+----------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+----------+------+-----+---------+-------+
| Host | char(60) | NO | | | |
| User | char(16) | NO | | | |
| Password | char(41) | NO | | | |
+----------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)
MariaDB [mydb]> SELECT * FROM tbl6;
+-----------+------+-------------------------------------------+
| Host | User | Password |
+-----------+------+-------------------------------------------+
| localhost | root | |
| centos7 | root | |
| 127.0.0.1 | root | |
| ::1 | root | |
| localhost | | |
| centos7 | | |
| % | test | *00E247AC5F9AF26AE0194B41E1E769DEE1429A29 |
| localhost | test | *00E247AC5F9AF26AE0194B41E1E769DEE1429A29 |
+-----------+------+-------------------------------------------+
8 rows in set (0.00 sec)
```
复制表结构;
```
MariaDB [mydb]> CREATE TABLE tbl7 like mysql.user;
Query OK, 0 rows affected (0.02 sec)
MariaDB [mydb]> DESC tbl7;
+------------------------+-----------------------------------+------+-----+----------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------------------+-----------------------------------+------+-----+----------+-------+
| Host | char(60) | NO | PRI | | |
| User | char(80) | NO | PRI | | |
| Password | char(41) | NO | | | |
| Select_priv | enum('N','Y') | NO | | N | |
| Insert_priv | enum('N','Y') | NO | | N | |
| Update_priv | enum('N','Y') | NO | | N | |
| Delete_priv | enum('N','Y') | NO | | N | |
| Create_priv | enum('N','Y') | NO | | N | |
| Drop_priv | enum('N','Y') | NO | | N | |
| Reload_priv | enum('N','Y') | NO | | N | |
| Shutdown_priv | enum('N','Y') | NO | | N | |
| Process_priv | enum('N','Y') | NO | | N | |
| File_priv | enum('N','Y') | NO | | N | |
| Grant_priv | enum('N','Y') | NO | | N | |
| References_priv | enum('N','Y') | NO | | N | |
| Index_priv | enum('N','Y') | NO | | N | |
| Alter_priv | enum('N','Y') | NO | | N | |
| Show_db_priv | enum('N','Y') | NO | | N | |
| Super_priv | enum('N','Y') | NO | | N | |
| Create_tmp_table_priv | enum('N','Y') | NO | | N | |
| Lock_tables_priv | enum('N','Y') | NO | | N | |
| Execute_priv | enum('N','Y') | NO | | N | |
| Repl_slave_priv | enum('N','Y') | NO | | N | |
| Repl_client_priv | enum('N','Y') | NO | | N | |
| Create_view_priv | enum('N','Y') | NO | | N | |
| Show_view_priv | enum('N','Y') | NO | | N | |
| Create_routine_priv | enum('N','Y') | NO | | N | |
| Alter_routine_priv | enum('N','Y') | NO | | N | |
| Create_user_priv | enum('N','Y') | NO | | N | |
| Event_priv | enum('N','Y') | NO | | N | |
| Trigger_priv | enum('N','Y') | NO | | N | |
| Create_tablespace_priv | enum('N','Y') | NO | | N | |
| ssl_type | enum('','ANY','X509','SPECIFIED') | NO | | | |
| ssl_cipher | blob | NO | | NULL | |
| x509_issuer | blob | NO | | NULL | |
| x509_subject | blob | NO | | NULL | |
| max_questions | int(11) unsigned | NO | | 0 | |
| max_updates | int(11) unsigned | NO | | 0 | |
| max_connections | int(11) unsigned | NO | | 0 | |
| max_user_connections | int(11) | NO | | 0 | |
| plugin | char(64) | NO | | | |
| authentication_string | text | NO | | NULL | |
| password_expired | enum('N','Y') | NO | | N | |
| is_role | enum('N','Y') | NO | | N | |
| default_role | char(80) | NO | | | |
| max_statement_time | decimal(12,6) | NO | | 0.000000 | |
+------------------------+-----------------------------------+------+-----+----------+-------+
46 rows in set (0.02 sec)
```
#### #
|
Java
|
UTF-8
| 57 | 1.546875 | 2 |
[] |
no_license
|
package com.company;
public interface Comparable<U> {
}
|
C++
|
UTF-8
| 552 | 2.671875 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
struct Stu{
string id;
int test;
int fin;
};
Stu ps[1500];
int main()
{
int nS;
cin >> nS;
for(int i = 0; i < nS; i++)
{
cin >> ps[i].id >> ps[i].test >> ps[i].fin;
}
int nQ;
cin >> nQ;
for(int i = 0; i < nQ; i++)
{
int num;
cin >> num;
for(int j = 0; j < nS; j++)
{
if(ps[j].test == num)
{
cout << ps[j].id << " " << ps[j].fin << endl;
}
}
}
return 0;
}
|
Python
|
UTF-8
| 704 | 3.109375 | 3 |
[] |
no_license
|
testcases = [
("Adjacent C++ style comments",
'''\
// foo
// bar\
'''),
("Adjacent C style comments",
'''\
/* foo *//* bar */\
'''),
("Nonterminated comments",
'''\
/*
'''),
("Nonterminated comments",
'''\
/* foo *\
'''),
("Everything",
'''
// c++ style comment
a = b + c;
d = 1 / 234 * foo - 2. + .2 + 2.2;
if what /* c style comment */what;
for a1 == b2 a1 != b2;
while a1 < b2 a1 > b2;
a1 <= b2;
a1 >= b2;
'''),
("id",
'''
foo
'''),
("Nonterminated comment",
'''\
// foo
/*hello*\
'''),
("2 id",
'''\
a b
'''),
("int float",
'''\
1. .1 1.2 12.34
1 12 123
'''),
("id = floats, ints",
'''\
a = 1. .1 1.2 12.34;
1 12 123
'''
),
("logical operators",
'''\
<<=!=>>==
'''
),
("",
'''\
'''
),
]
|
C++
|
GB18030
| 1,110 | 3 | 3 |
[] |
no_license
|
/*!
* Licensed under the MIT License.See License for details.
* Copyright (c) 2018 콭ĴϺ.
* All rights reserved.
*
* \file defer.hpp
* \author 콭ĴϺ
* \date 2017
*
* ģʵgolangdefer塣ںǰִһЩ
*
*/
#ifndef __DAXIA_DEFER_HPP
#define __DAXIA_DEFER_HPP
#include <stack>
#include <functional>
#define deferinit() daxia::DeferStack deferStack;
#define defer deferStack<<[&]()
#define return(...) while (true)\
{\
auto f = deferStack.Pop();\
if(f)\
{\
f();\
}\
else\
{\
break;\
}\
}\
return __VA_ARGS__;
namespace daxia
{
class DeferStack
{
public:
typedef std::function<void()> deferFun;
public:
DeferStack(){}
~DeferStack(){}
public:
void Push(deferFun fun)
{
funstack_.push(fun);
}
deferFun Pop()
{
deferFun fun;
if (!funstack_.empty())
{
fun = funstack_.top();
funstack_.pop();
}
return fun;
}
void operator <<(deferFun fun)
{
Push(fun);
}
private:
std::stack<deferFun> funstack_;
};
}
#endif // !__DAXIA_DEFER_HPP
|
Markdown
|
UTF-8
| 2,171 | 3.71875 | 4 |
[] |
no_license
|
#### Lowest Common Ancestor
source: [HackerRank](https://www.hackerrank.com/topics/lowest-common-ancestor),
#### Naive Approach $O(N)$:
```cpp
#define mx_nodes 100
bool visited[mx_nodes];
int parent[mx_nodes];
vector<int> tree[mx_nodes];
int root_node = 0;
/*GetParents() function traverses the tree and computes the parent array such that
The pre-order traversal begins by calling GetParents(root_node,-1) */
void GetParents(int node , int par){
for(int i = 0 ; i < (int) tree[node].size() ; ++i){
/*As this is a pre-order traversal of the tree the parent of the current node has already been processed, Thus it should not be processed again*/
if(tree[node][i] != par){
parent[tree[node][i]] = node ;
GetParents(tree[node][i] , node) ;
}
}
}
/*Computes the LCA of nodes u and v . */
int LCA(int u , int v){
GetParents(root_node, -1);
/*traverse from node u uptil root node and mark the vertices encountered along the path */
int lca ;
while(1){
visited[u] = true;
if(u == root_node) break;
u = parent[u];
}
/*Now traverse from node v and keep going up untill we dont hit a node that is in the path of node u to root node*/
while(1){
if(visited[v]){
/*Intersection of paths found at this node.*/
lca = v; break ;
}
v = parent[v] ;
}
return lca ;
}
int main() {
int n; cin >> n;
for (int i = 0, x, y; i < n-1; ++i) { cin >> x >> y; tree[x].push_back(y); }
cout << LCA(4, 6) << endl;
}
```
Now the parents of all the nodes can be computed without calling the `GetParents(root_node, -1)` function simply like this, if there's no extra condition:
```cpp
for (int i = 0, x, y; i < n-1; ++i) {
cin >> x >> y;
tree[x].push_back(y);
parent[y] = x;
}
```
> Time Complexity: $O(h)$ where $h$ is the maximum distance of the root from a leaf. In case the tree is very **unbalanced** such that every node of the tree has exactly one child, the structure of the tree becomes linear and hence $h = N$ where $N$ is the number of nodes in the tree, making the algorithm $O(N)$.
|
Java
|
UTF-8
| 178 | 1.742188 | 2 |
[
"MIT"
] |
permissive
|
package pl.pawel.linkshell.model.enums.strategy;
/**
* Created by pawellinkshell on 11.02.2018.
*/
public enum DecisionStrategyType {
PLAYER_LIVE,
PLAYER_AI_DEFAULT
}
|
Markdown
|
UTF-8
| 3,658 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
# Shell Script Tools
> Repository for some useful shell scripts which I've done to solve problems or make things...
---
**Table of Contents**
- [install_flash_player.sh](#install_flash_player)
- [kdialog_progbar_helper](#kdialog_progbar_helper)
- [cowsay_and_whatthecommit.sh](#cowsay_and_whatthecommit)
- [fix_icc_profile_bug.sh](#fix_icc_profile_bug)
- [safe_rm](#safe_rm)
---
## install_flash_player
Script to install Adobe Flash Player in GNU/Linux machines with Mozilla Firefox. It finds the latest plugin version and downloads the tarball direct from Adobe web site.
**Requires:**
* curl
* wget
**Usage:** `sudo ./install_flash_player.sh`
---
## kdialog_progbar_helper
This script is a helper to simplify the creation and update of KDialog progress bar with d-bus.
**Requires:**
* kdialog
* d-bus
**Usage:** `source ./kdialog_progbar_helper`
#### To see the help
Call the function `kdialog_progbar_help`
#### Creating a dialog with cancel button
`progress_bar_create "<Title>" "<Text>" true`
It returns a string with the d-bus instance
#### Updating the bar to 20%
`progress_bar_update "${instance}" 20`
#### Checking if it was canceled
`progress_bar_was_canceled ${instance}`
#### Closing progress bar
`progress_bar_exit ${instance}`
#### Running tests
There is a test to create a dialog with a cancel button. To run it, call the function `test01`
---
## cowsay_and_whatthecommit
This script uses two very funny web sites to display the Cowsay (based o the cowsay cli program by Tony Monroe) and random commit messages. The result is basically a cow saying a funny commit message.
**Requires:**
* curl
**Usage:** `./cowsay_and_whatthecommit.sh`
#### APIs
http://cowsay.morecode.org (by Jesse Chan-Norris <http://jcn.me>)
http://whatthecommit.com (by Nick Gerakines <https://github.com/ngerakines/commitment>)
#### Result
```
$ ./cowsay_and_whatthecommit.sh
_______________________________________
/ fixed some minor stuff, might need some \
\ additional work. /
---------------------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
```
---
## fix_icc_profile_bug
This script is a workaround to prevent some pictures to be displayed with wrong colors.
Source forum that this fix was suggested: https://bugs.launchpad.net/ubuntu/+source/eog/+bug/938751
Put this file in startup folder in your graphical environment. Since I use KDE I put the script to start with KDE in $HOME/.kde/Autostart.
#### What it runs
`xprop -root -remove _ICC_PROFILE`
---
## safe_rm
This script prevents accidental deletions by sending files to Trash.
If `gvfs-trash` command is available in the system, it will be used, otherwise, a folder called `.trash` will be created inside `${HOME}` directory and the files will be moved to there.
The best way to use this function is to source it in `.bashrc` file.
**WARNING:** This approach doesn't work with `sudo` command or when using different user accounts.
**Requires:**
* rm
**Optional:**
* gvfs-trash
**Usage:** `source safe_rm`
#### Result with gvfs-trash
```
$ rm folder*
--- safe rm (gvfs 1.22.2) ---
File(s) [folder1 folder2 folder3 folder4] sent to trash.
------------------------------
```
#### Result without gvfs-trash
```
$ rm folder*
--- safe rm ---
“folder1” -> “/home/user/.trash/folder1.1472009967”
“folder2” -> “/home/user/.trash/folder2.1472009967”
“folder3” -> “/home/user/.trash/folder3.1472009968”
“folder4” -> “/home/user/.trash/folder4.1472009968”
Trash size: 20K /home/user/.trash
---------------
```
---
|
Python
|
UTF-8
| 873 | 3.03125 | 3 |
[] |
no_license
|
# https://leetcode.com/problems/minimum-path-sum/
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
maxRows = len(grid)-1
maxCols = len(grid[0])-1
for i in range(maxRows, -1, -1):
for j in range(maxCols, -1,-1):
# current coords is bottom row, disregard last index
if i == maxRows and j < maxCols:
grid[i][j] = grid[i][j+1] + grid[i][j]
# current coords is middle rows and not last column
elif i < maxRows and j < maxCols:
grid[i][j] = min(grid[i+1][j],grid[i][j+1]) + grid[i][j]
# current coords is middle rows and last column
elif i < maxRows and j == maxCols:
grid[i][j] = grid[i+1][j] + grid[i][j]
return grid[0][0]
|
PHP
|
UTF-8
| 908 | 2.65625 | 3 |
[] |
no_license
|
<?php
function set_status($msg, $flag='info') {
return '<div class="message '.$flag.'">'.$msg.'</div>';
}
function convert_4digits($num) {
$ctr = 0;
$str = "";
while($ctr < 4) {
$str = $num%10 . $str;
$num /= 10;
$ctr++;
}
return $str;
}
function get_today() {
return date('Y-m-d');
}
function add_days($date, $days) {
$date=date_create($date);
date_add($date,date_interval_create_from_date_string($days." days"));
return date_format($date,"Y-m-d");
}
function get_date_diff($from_date,$to_date) {
$diff = date_diff(date_create($to_date),date_create($from_date));
if($diff->invert > 0)
return $diff->days*-1;
return $diff->days;
}
function page_not_found() {
header("Location:/m140163cs/olm/404.php");
}
function days_first_run() {
}
function check_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
|
Java
|
UTF-8
| 5,377 | 3.328125 | 3 |
[] |
no_license
|
/**
* @FileName : case_01
* @author : wang.xiaolong
* @Date : 2017年7月31日
* @Description : 文件操作
* @check
* 【A】
* 八、buf值
*/
package case_01;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author wang.xiaolong
*
*/
public class OpFile {
/**
* 八、获取文件大小 getFileName()
*
* file.length() 获取文件大小方法 file.isFile()、file.exists()判断文件是否存在方法
*
* @param fileName
* @return
*
*/
// private static long getFileSize(String fileName) {
// // TODO Auto-generated method stub
// File file = new File(fileName);
// if (!file.isFile() || !file.exists()) {
// return -1;
// } else {
// return file.length();
// }
//
// }
public static void main(String[] args) throws IOException {
String fileName = "newFile.txt";
String copyFile = "fromCopy.txt";
/*
* 一、写入文件
*/
// BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
// bw.write("hello world");
// bw.close();
// System.out.println("ok");
/*
* 二、读文件 调用readLine()方法
*/
// BufferedReader br = new BufferedReader(new FileReader(fileName));
// String str;
// while ((str = br.readLine()) != null) {
// System.out.println(str);
// }
/*
* 三、删除文件 调用File的delete()方法
*/
// File file = new File("test.txt");
// if(file.delete()){
// System.out.println(file.getName()+"删除成功");
// }
// else{
// System.out.println("删除失败");
// }
/*
* 四、将文件内容复制到另一个文件
*/
// InputStream is = new FileInputStream(new File(fileName));
// OutputStream os = new FileOutputStream(new File(newFile));
// byte[] buf = new byte[1024];
// int len;
// //buf值怎么来的??
// while ((len = is.read(buf)) > 0) {
// os.write(buf);
// }
// is.close();
// os.close();
// BufferedReader br = new BufferedReader(new FileReader(newFile));
// String str;
// while ((str = br.readLine()) != null) {
// System.out.println(str);
// }
/*
* 五、向文件中追加数据
*/
// BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
// bw.write("hello world\nhello kitty\n");
// bw.close();
// /*
// * public FileWriter(File file, boolean append)
// *
// * append:
// * true,则将字节写入文件末尾处
// * false,则写入文件开始处
// * 默认是false
// */
//
// bw = new BufferedWriter(new FileWriter(fileName, true));
// bw.write("hello moto");
// bw.close();
// BufferedReader br = new BufferedReader(new FileReader(fileName));
// String str;
// while ((str = br.readLine()) != null) {
// System.out.println(str);
// }
/*
* 六、创建临时文件 createTempFile() 创建临时文件方法 deleteOnExit() 删除临时文件方法
*/
// File temp = File.createTempFile("pattern", ".suffix");
// temp.deleteOnExit();
// BufferedWriter out = new BufferedWriter(new FileWriter(temp));
// out.write("hello world");
// System.out.println("临时文件已创建:");
// out.close();
/*
* 七、修改文件最后的修改日期 lastModified() 获取最后修改日期 setLastModified() 修改最后修改日期
*/
// File file = new File(fileName);
// // file.createNewFile();
// Date fileTime = new Date(file.lastModified());
// // String sdf = new
// SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(fileTime);
// System.out.println(fileTime);
// // System.out.println(sdf);
// file.setLastModified(System.currentTimeMillis());
// fileTime = new Date(file.lastModified());
// System.out.println(fileTime);
/*
* 八、获取文件大小
*/
// long size = getFileSize(fileName);
// System.out.println(fileName+"的大小为:"+size+" bytes");
/*
* 九、文件重命名 oldFile.renameTo(newFile)
*/
// File oldFile = new File(fileName);
// File newFile = new File("newFile.txt");
// if(oldFile.renameTo(newFile)){
// System.out.println("rename success");
// }
// else{
// System.out.println("rename failure");
// }
/*
* 十、设置文件为只读 setReadOnly() canWrite() - 验证是否为只读
*/
// File file = new File("newFile.txt");
// System.out.println(file.setReadOnly());
// System.out.println(file.canWrite());
// BufferedWriter bw = new BufferedWriter(new FileWriter("newFile.txt",
// true));
// bw.write("end");
/*
* 十一、判断文件是否存在 file.exists()
*/
// File file = new File(fileName);
// System.out.println(file.exists());
/*
* 十二、判断两个文件路径名是否一致 compareTo() 一致返回0
*/
// File file1 = new File(fileName);
// File file2 = new File(copyFile);
// if(file1.compareTo(file2) == 0){
// System.out.println("一致");
// }else{
// System.out.println("不一致");
// }
}
}
|
Python
|
UTF-8
| 462 | 2.515625 | 3 |
[] |
no_license
|
from selenium import webdriver
import page
class BaseDriver:
driver=None
def get_driver(self):
if self.driver is None:
self.driver=webdriver.Chrome()
self.driver.maximize_window()
self.driver.get(page.URL)
return self.driver
def driver_quit(self):
if self.driver:
self.driver.quit()
self.driver=None
if __name__ == '__main__':
BaseDriver().get_driver()
|
Python
|
UTF-8
| 1,368 | 2.875 | 3 |
[] |
no_license
|
import cv2
import numpy as np
import glob
import matplotlib.pyplot as plt
import random
imgs = glob.glob('96DM/*.png')
def rotate_image(image, angle):
image_center = tuple(np.array(image.shape[1::-1]) / 2)
rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)
result = cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR,borderMode=cv2.BORDER_CONSTANT,borderValue=(255,255,255))
return result
def add_border(image,percent):
row,col = image.shape[:2]
mean = cv2.mean(image[row-2:row,0:col])[0]
return cv2.copyMakeBorder(image, top=int(row*percent),
bottom=int(row*percent), left=int(col*percent),
right = int(col*percent), borderType=cv2.BORDER_CONSTANT,value=[mean,mean,mean])
img = cv2.imread('imgs/printer_iphone.jpg')
cv2.imshow('image',img)
len(imgs)
imgs
rows = []
for r in range(8):
cols = []
for c in range(12):
img = cv2.imread(imgs[r*12+c])
img = add_border(img,0.33)
deg = random.random()*360
imgr = rotate_image(img,deg)
cols.append(imgr)
rows.append(cv2.hconcat(cols))
plate = cv2.vconcat(rows)
cv2.imwrite('plate.jpg',plate)
i1 = cv2.imread(imgs[0])
i1 = add_border(i1,0.5)
r1 = rotate_image(i1,23)
plt.imshow(i1)
plt.imshow(r1)
plt.show()
cv2.imwrite('rotate.jpg',r1)
cv2.vconcat()
cv2.hconcat()
imgs
|
Ruby
|
UTF-8
| 668 | 2.5625 | 3 |
[] |
no_license
|
class PainSeverityService
def self.analyze(submission)
new(submission).perform
end
def initialize(submission)
@submission = submission
end
def perform
set_pain_severity
end
private
def set_pain_severity
pain_severity = if @submission.current_pain_answer.value > 30
# => Notify the user 1 hour from now asking to follow up with the pain
Delayed::Job.enqueue(Workers::UserNotifier.new(@submission.user.id, "Hey recruit. You reported pain an hour ago. Tell us how you are doing now!"), run_at: 1.hour.from_now)
:moderate
else
:mild
end
@submission.update(pain_severity: pain_severity)
end
end
|
JavaScript
|
UTF-8
| 557 | 2.609375 | 3 |
[] |
no_license
|
function getDetail(id) {
window.location.href = `/product/${id}`;
}
function addToCart(id) {
fetch('/cart', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
productId: id,
}),
})
.then((response) => response.json())
.then((data) => {
window.location.href = `/cart`;
});
}
function editProduct(id) {
console.log('editProduct', id);
window.location.href = `/admin/edit-product/${id}`;
}
function removeProduct(id) {
console.log('removeProduct', id);
}
|
Python
|
UTF-8
| 19,841 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
from prawcore.exceptions import RequestException, ResponseException, InvalidToken
import pickle as cPickle
import threading
import datetime
import operator
import sqlite3
import config
import praw
import time
import re
class bot:
# defined variables
def __init__(self):
self.reddit = praw.Reddit(client_id = config.id, client_secret = config.secret, password = config.password, user_agent = config.user_agent, username = config.username)
self.subreddit = self.reddit.subreddit(str(config.sub))
self.db_conn = self.initiate_database()
###########################################################################
# Section 1
# This section contains database actions
# Function 1.1; initiate database tables
# Function 1.2; insert new comment row in database
# Function 1.3; update votes column in comment row
# Function 1.4; remove row from comment database
###########################################################################
# initiates database
def initiate_database(self):
try:
conn = sqlite3.connect('insane.db', check_same_thread=False)
conn.execute(
'''
CREATE TABLE IF NOT EXISTS COMMENTS (
COMMENT_ID VARCHAR(20) PRIMARY KEY,
VOTES_DICT BLOB,
SUB_CREATED FLOAT,
EXPLANATION STRING
);'''
)
return conn
print('Connected to SQLITE database ' + sqlite3.version)
except sqlite3.Error as e:
print('Failed to connect to database')
print(e)
# insert new comment row in COMMENT database
def insert_in_db(self, comment_id, votes={}):
try:
vote_data = cPickle.dumps(votes, cPickle.HIGHEST_PROTOCOL)
params = (str(comment_id), sqlite3.Binary(vote_data), comment_id.submission.created_utc, 'False')
self.db_conn.execute("INSERT INTO COMMENTS (COMMENT_ID,VOTES_DICT,SUB_CREATED,EXPLANATION) VALUES (?,:data,?,?)", params)
self.db_conn.commit()
except sqlite3.Error as e:
print('Failed to create row')
print(e)
# update votes dict in COMMENT database row
def update_in_db(self, comment_id, votes={}):
try:
vote_data = cPickle.dumps(votes, cPickle.HIGHEST_PROTOCOL)
params = (sqlite3.Binary(vote_data), str(comment_id))
self.db_conn.execute("UPDATE COMMENTS SET VOTES_DICT = :data WHERE COMMENTS.COMMENT_ID=?", params)
self.db_conn.commit()
except sqlite3.Error as e:
print('Failed to update row')
print(e)
# update explanation boolean in COMMENT database row
def update_explan_db(self, comment_id, bot_cm):
try:
params = (str(comment_id), str(bot_cm))
self.db_conn.execute("UPDATE COMMENTS SET EXPLANATION = ? WHERE COMMENTS.COMMENT_ID=?", params)
self.db_conn.commit()
except sqlite3.Error as e:
print('Failed to update row')
print(e)
# remove row from COMMENT database
def remove_from_db(self, comment_id):
try:
cr = self.db_conn.cursor()
cr.execute("DELETE FROM COMMENTS WHERE COMMENTS.COMMENT_ID='%s'" %str(comment_id))
self.db_conn.commit()
except sqlite3.Error as e:
print('Failed to remove row')
print(e)
###########################################################################
# Section 2
# This section contains user actions
# Function 2.1; report submission
# Function 2.2; removes comment
# Function 2.3; removes submission
# Function 2.4; comments on submission
# Function 2.5; updates comment
# Function 2.6; locks comment
# Function 2.7; last update comment
# Function 2.8; deletes own comment
###########################################################################
# reports submission
def report_submission(self, submission, message):
try:
self.reddit.submission(submission).report(message)
except Exception as e:
print(e.response.content)
pass
# removes comment
def remove_comment(self, comment):
try:
self.reddit.comment(str(comment)).mod.remove()
except Exception as e:
print(e.response.content)
pass
# remove submission
def remove_submission(self, submission):
try:
self.reddit.submission(submission).mod.remove()
self.reddit.submission(submission).mod.send_removal_message('Your submission was removed because the voting system deemed it: fake')
except Exception as e:
print(e.response.content)
pass
# comments on submission
def comment(self, submission):
try:
cm = submission.reply(config.initial_comment + '\n\n Hey OP, if you provide further information in a comment, make sure to start your comment with !explanation.')
cm.mod.distinguish(sticky=True)
self.insert_in_db(cm)
except Exception as e:
print(e)
pass
# updates comment
def update_comment(self, comment_id, insane, notinsane, fake, explan):
if explan == 'False':
try:
#self.reddit.comment(str(comment_id)).edit(config.initial_comment + "\n\n # Votes \n\n| Insane | Not insane | Fake |\n| --- | --- | --- |\n| {0} | {1} | {2} |".format(insane, notinsane, fake) + config.footer)
self.reddit.comment(str(comment_id)).edit(config.initial_comment + "\n\n # Votes \n\n| Insane | Not insane | Fake |\n| --- | --- | --- |\n| {0} | {1} | {2} |".format(insane, notinsane, fake) + '\n\n Hey OP, if you provide further information in a comment, make sure to start your comment with !explanation. \n' + config.footer)
except Exception as e:
print(e)
pass
else:
try:
foot = "\n\n\n\n\n\nOP has provided further information [in this comment]({0}).".format(explan)
self.reddit.comment(str(comment_id)).edit(config.initial_comment + "\n\n # Votes \n\n| Insane | Not insane | Fake |\n| --- | --- | --- |\n| {0} | {1} | {2} |".format(insane, notinsane, fake) + foot)
#self.reddit.comment(str(comment_id)).edit(config.initial_comment + "\n\n # Votes \n\n| Insane | Not insane | Fake |\n| --- | --- | --- |\n| {0} | {1} | {2} |".format(insane, notinsane, fake) + '\n\n Hey OP, if you provide further information in a comment, make sure to start your comment with !explanation. \n' + config.footer)
except Exception as e:
print(e)
pass
# locks comment
def lock_comment(self, comment_id):
try:
self.reddit.comment(str(comment_id)).mod.lock()
except Exception as e:
print(e)
pass
# last update comment
def last_update_comment(self, comment_id, insane, notinsane, fake, explan):
insane = int(insane)
notinsane = int(notinsane)
fake = int(fake)
if insane > notinsane and insane > fake:
winner = 'insane'
winner_count = str(insane)
elif fake > notinsane and fake > insane:
winner = 'fake'
winner_count = str(fake)
elif notinsane > insane and notinsane > fake:
winner = 'not insane'
winner_count = str(notinsane)
else:
winner = 'insane'
winner_count = str(insane)
if explan == 'False':
try:
self.reddit.comment(str(comment_id)).edit(config.final_comment + winner + " with " + str(winner_count) + " votes \n\n # Votes \n\n| Insane | Not insane | Fake |\n| --- | --- | --- |\n| {0} | {1} | {2} |".format(insane, notinsane, fake) + config.footer)
except Exception as e:
print(e)
pass
else:
try:
foot = "\n\n\n\n\n\nOP has provided further information [in this comment]({0}).".format(explan)
self.reddit.comment(str(comment_id)).edit(config.final_comment + winner + " with " + str(winner_count) + " votes \n\n # Votes \n\n| Insane | Not insane | Fake |\n| --- | --- | --- |\n| {0} | {1} | {2} |".format(insane, notinsane, fake) + foot)
except Exception as e:
print(e)
pass
# update submission flair with removed flair
def removed_flair(self, submission):
try:
self.reddit.submission(submission).mod.flair(text='Removed; Fake through voting',css_class='removedvote')
except Exception as e:
print(e)
pass
# delete own comment
def delete_own_comment(self, comment):
try:
self.reddit.comment(comment).delete()
except Exception as e:
print(e.response.content)
pass
###########################################################################
# Section 3
# This section contains legitimacy checks and random functions
# Function 3.1; regex to check for votes
# Function 3.2; act on votes
###########################################################################
# checks if a vote is legit
def legit_vote(self, body):
low_body = body.lower()
if re.match("i\s*n\s*s\s*a\s*n\s*e", low_body):
return 'insane'
elif re.match("\s*n\s*o\s*t\s*i\s*n\s*s\s*a\s*n\s*e", low_body):
return 'not insane'
elif re.match("\s*f\s*a\s*k\s*e", low_body):
return 'fake'
else:
return None
# act on votes
def act_on_votes(self, insane, notinsane, fake, submission):
insane = int(insane)
notinsane = int(notinsane)
fake = int(fake)
if insane > notinsane and insane > fake:
maxi = 'insane'
elif fake > notinsane and fake > insane:
maxi = 'fake'
elif notinsane > insane and notinsane > fake:
maxi = 'not insane'
else:
maxi = 'insane'
#if maxi == 'insane':
#self.report_submission(submission, "Submission deemed 'insane' through voting. Please flair it properly.")
if maxi == 'not insane':
self.report_submission(submission, "Submission deemed 'not insane' through voting.")
elif maxi == 'fake':
self.removed_flair(submission)
self.report_submission(submission, 'Please review this submission. It was removed because it was deemed fake through the voting system.')
self.remove_submission(submission)
###########################################################################
# Section 4
# This section contains bot commands
# Function 4.1; removes submission
# Function 4.2; locks submission
# Function 4.3; comments on submission
# Function 4.4; parses !comment command
# Function 4.5; parses !lock command
# Function 4.6; parses !remove command
# Function 4.7; parses !hotlines command
###########################################################################
# takes submission id, removes submission
def remove_sm(self, submission_id, reason):
try:
submission = self.reddit.submission(str(submission_id))
submission.mod.remove()
submission.mod.send_removal_message(message = reason,
title = 'Submission removed',
type = config.removal_type)
except Exception as e:
print(e)
pass
# takes submission id, locks submission
def sm_lock(self, submission_id):
try:
self.reddit.submission(str(submission_id)).mod.lock()
except Exception as e:
print(e)
pass
# takes submission id, comments on submission
def comment_comm(self, submission_id, reason):
try:
cm = self.reddit.submission(str(submission_id)).reply(reason)
cm.mod.distinguish(how='yes', sticky=True)
except Exception as e:
print(e)
pass
# parses comment for ~!lock~ command
def lock_parse(self, body, cm_id, sm_id):
reason = body[6:]
self.remove_comment(cm_id)
self.sm_lock(sm_id)
self.comment_comm(sm_id, reason)
# parses comment for ~!comment~ command
def comment_parse(self, body, cm_id, sm_id):
reason = body[9:]
self.remove_comment(cm_id)
self.comment_comm(sm_id, reason)
# parses comment for ~!remove~ command
def remove_parse(self, body, cm_id, sm_id):
reason = body[8:]
self.remove_comment(cm_id)
self.remove_sm(sm_id, reason)
# sticky comment with suicide and abuse support lines
def hotline_parse(self, body, cm_id, sm_id):
reason = config.hotline
self.remove_comment(cm_id)
self.comment_comm(sm_id, reason)
###########################################################################
# Section 5
# This section contains threading actions
# Function 5.1; submission stream
# Function 5.2; database evaluation
# Function 5.3; threading
###########################################################################
# submission stream
def submissions(self):
for submission in self.subreddit.stream.submissions(skip_existing=True):
try:
self.comment(submission)
except InvalidToken:
print("Encountered Invalid Token error, resetting PRAW")
time.sleep(10)
self.reddit = None
self.reddit = praw.Reddit(username = config.username,
password = config.password,
client_id = config.id,
client_secret = config.secret,
user_agent = config.user_agent)
self.subreddit = self.reddit.subreddit(str(config.sub))
except RequestException as e:
print(e)
print("Request problem, will retry\n")
time.sleep(10)
except ResponseException as e:
print(e)
print("Server problem, will retry\n")
time.sleep(60)
except Exception as e:
print(e)
# evaluates comments in database
def evaluation(self):
while True:
try:
cursor = self.db_conn.execute("SELECT * FROM COMMENTS")
for i in cursor.fetchall():
votes = cPickle.loads(i[1])
comment = self.reddit.comment(str(i[0]))
explan = i[3]
if time.time() - comment.created_utc > 60*60*config.maxtime:
self.remove_from_db(comment.id)
insane = sum(value == 'insane' for value in votes.values())
notinsane = sum(value == 'not insane' for value in votes.values())
fake = sum(value == 'fake' for value in votes.values())
total = insane + notinsane + fake
self.last_update_comment(str(comment.id), str(insane), str(notinsane), str(fake), str(explan))
self.lock_comment(str(comment.id))
self.act_on_votes(str(insane), str(notinsane), str(fake), comment.submission.id)
else:
comment.reply_sort = 'new'
comment = comment.refresh()
replies = comment.replies
for reply in replies:
try:
if reply.parent().author.name == config.username:
if reply.author.name not in votes.keys():
legit = self.legit_vote(reply.body)
if legit != None:
try:
votes.update({reply.author.name:legit})
reply.upvote()
self.remove_comment(reply)
except Exception as e:
print(e)
else:
pass
else:
pass
else:
pass
except Exception as e:
print(e)
self.update_in_db(str(comment.id), votes)
insane = sum(value == 'insane' for value in votes.values())
notinsane = sum(value == 'not insane' for value in votes.values())
fake = sum(value == 'fake' for value in votes.values())
self.update_comment(str(comment.id), str(insane), str(notinsane), str(fake), str(explan))
minute = datetime.datetime.now().minute
if minute > 30:
minute = minute - 30
time.sleep(60*(30-minute))
except InvalidToken:
print("Encountered Invalid Token error, resetting PRAW")
time.sleep(10)
self.reddit = None
self.reddit = praw.Reddit(username = config.username,
password = config.password,
client_id = config.id,
client_secret = config.secret,
user_agent = config.user_agent)
self.subreddit = self.reddit.subreddit(str(config.sub))
except RequestException as e:
print(e)
print("Request problem, will retry\n")
time.sleep(10)
except ResponseException as e:
print(e)
print("Server problem, will retry\n")
time.sleep(60)
except Exception as e:
print(e)
# runs bot commands when command is detected
def commands(self):
while True:
try:
mod_team = [x for x in self.subreddit.moderator()]
for comment in self.subreddit.stream.comments(skip_existing=True):
if comment.body[:8] == '!disable':
try:
if comment.author.name in mod_team:
self.remove_from_db(comment.parent_id[3:])
self.delete_own_comment(comment.parent_id[3:])
else:
pass
except Exception as e:
print(e)
pass
elif comment.body[:12] == '!explanation':
try:
if comment.author.name == comment.submission.author.name:
sm = comment.submission
sm.comment_sort = 'new'
cms = sm.comments.list()
bot_cm = False
for cm in cms:
try:
if cm.author.name == config.username:
bot_cm = cm.id
break
else:
continue
except Exception as e:
print(e)
pass
if bot_cm != False:
self.update_explan_db(comment.permalink, bot_cm)
cursor = self.db_conn.cursor().execute("SELECT * FROM COMMENTS WHERE COMMENTS.COMMENT_ID='%s'" %str(bot_cm))
i = cursor.fetchone()
votes = cPickle.loads(i[1])
comment = self.reddit.comment(str(i[0]))
explan = i[3]
comment.reply_sort = 'new'
comment = comment.refresh()
replies = comment.replies
for reply in replies:
try:
if reply.parent().author.name == config.username:
if reply.author.name not in votes.keys():
legit = self.legit_vote(reply.body)
if legit != None:
try:
votes.update({reply.author.name:legit})
reply.upvote()
self.remove_comment(reply)
except Exception as e:
print(e)
else:
pass
else:
pass
else:
pass
except Exception as e:
print(e)
self.update_in_db(str(bot_cm), votes)
insane = sum(value == 'insane' for value in votes.values())
notinsane = sum(value == 'not insane' for value in votes.values())
fake = sum(value == 'fake' for value in votes.values())
self.update_comment(str(comment.id), str(insane), str(notinsane), str(fake), str(explan))
else:
comment.reply('Could not sticky explanation. Apologies for the inconvenience.' + config.footer)
else:
pass
except Exception as e:
print(e)
pass
elif comment.body[:5] == '!lock':
try:
if comment.author.name in mod_team:
self.lock_parse(comment.body, comment.id, comment.submission.id)
else:
pass
except Exception as e:
print(e)
pass
elif comment.body[:8] == '!comment':
try:
if comment.author.name in mod_team:
self.comment_parse(comment.body, comment.id, comment.submission.id)
else:
pass
except Exception as e:
print(e)
pass
elif comment.body[:7] == '!remove':
try:
if comment.author.name in mod_team:
self.remove_parse(comment.body, comment.id, comment.submission.id)
else:
pass
except Exception as e:
print(e)
pass
elif comment.body[:8] == '!hotline':
try:
if comment.author.name in mod_team:
self.hotline_parse(comment.body, comment.id, comment.submission.id)
else:
pass
except Exception as e:
print(e)
pass
except InvalidToken:
print("Encountered Invalid Token error, resetting PRAW")
time.sleep(10)
self.reddit = None
self.reddit = praw.Reddit(username = config.username,
password = config.password,
client_id = config.id,
client_secret = config.secret,
user_agent = config.user_agent)
self.subreddit = self.reddit.subreddit(str(config.sub))
except RequestException as e:
print(e)
print("Request problem, will retry\n")
time.sleep(10)
except ResponseException as e:
print(e)
print("Server problem, will retry\n")
time.sleep(60)
except Exception as e:
print(e)
# threading to execute functions in parallel
def threading(self):
a = threading.Thread(target=self.submissions, name='Thread-a', daemon=True)
b = threading.Thread(target=self.evaluation, name='Thread-b', daemon=True)
c = threading.Thread(target=self.commands, name='Thread-c', daemon=True)
a.start()
b.start()
c.start()
a.join()
b.join()
c.join()
if __name__ == '__main__':
bot().threading()
|
C++
|
UTF-8
| 1,402 | 3.46875 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <algorithm>
struct Socks
{
int shortSock;
int longSock;
};
bool CheckIsValid(int n, int k);
bool CompareTwoSocks(Socks first, Socks second);
int main()
{
//Implementation 1
int n;
int k;
std::cin >> n >> k;
if (CheckIsValid(n, k) == true)
{
int len;
std::vector<int> lengthOfSocks;
for (int i = 0; i < n; i++)
{
std::cin >> len;
if (len >= 1)
{
lengthOfSocks.push_back(len);
}
}
std::vector<Socks> allSocks;
Socks s;
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
s.shortSock = lengthOfSocks[i];
s.longSock = lengthOfSocks[j];
allSocks.push_back(s);
}
}
std::sort(allSocks.begin(), allSocks.end(), CompareTwoSocks);
std::cout << allSocks[k - 1].shortSock << " " << allSocks[k - 1].longSock << std::endl;
}
return 0;
}
bool CheckIsValid(int n, int k)
{
if (n >= 3 && n <= 1000)
{
if (k >= 1 && k <= n * (n - 1) / 2)
{
return true;
}
}
return false;
}
bool CompareTwoSocks(Socks first, Socks second)
{
if ((first.longSock - first.shortSock) < (second.longSock - second.shortSock))
{
return true;
}
else if ((first.longSock - first.shortSock) == (second.longSock - second.shortSock))
{
if (first.shortSock < second.shortSock)
{
return true;
}
}
return false;
}
|
Java
|
UTF-8
| 329 | 2.546875 | 3 |
[] |
no_license
|
package wsdemo;
import javax.jws.WebMethod;
import javax.jws.WebService;
@WebService
public class Employee {
@WebMethod
public String greet(String message) {
return message;
}
@WebMethod
public double calculateSalary(double salary) {
return salary;
}
@WebMethod
public int calculateLeaves() {
return 9;
}
}
|
C++
|
UTF-8
| 1,285 | 3.4375 | 3 |
[] |
no_license
|
//
// main.cpp
// Week6Prog6
//
// Created by James Lawson on 10/16/18.
// Copyright © 2018 James Lawson. All rights reserved.
//
#include <iostream>
#include <string>
#include<cmath>
using namespace std;
template <class B>
class box {
private:
B depth;
B width;
B height;
public:
B getWidth(void){
return width;
}
void setWidth(B inWidth){
width = inWidth;
}
void setHeight(B inHeight){
height = inHeight;
}
B getHeight(void){
return height;
}
B getDepth(void){
return depth;
}
void setDepth(B inDepth){
height = inDepth;
}
B calcArea(){
B area = pow(2, height) * 6;
return area;
}
B calcVolume(){
B volume = pow(3, height);
return volume;
}
};
int main(){
box<int> B1;
B1.setWidth(2);
B1.setDepth(3);
B1.setHeight(4);
cout << "Height: " << B1.getHeight() << endl;
cout << "Area: " << B1.calcArea() << endl;
cout << "Volume: " << B1.calcVolume() << endl;
box<int> B2;
B2.setWidth(3);
B2.setHeight(4);
cout << "Depth: " << B2.getDepth() << endl;
cout << "Area: " << B2.calcArea() << endl;
cout << "Volume: " << B2.calcVolume() << endl;
return 0;
}
|
PHP
|
UTF-8
| 4,955 | 2.90625 | 3 |
[] |
no_license
|
<?php
/*
* This file is part of the BFOSBrasilBundle package.
*
* (c) Paulo Ribeiro <paulo@duocriativa.com.br>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace BFOS\BrasilBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
class CpfcnpjValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
if (!$constraint->aceitar) {
throw new ConstraintDefinitionException('É necessário definer a opção "aceitar" da restrição.');
}
if (!in_array($constraint->aceitar, array('cpf', 'cnpj', 'cpfcnpj'))) {
throw new ConstraintDefinitionException('A opção "aceitar" pode conter apenas os valores "cpf", "cnpj" ou "cpfcnpj".');
}
if (null === $value) {
return true;
}
switch ($constraint->aceitar) {
case 'cnpj':
if (!$this->checkCNPJ($value, $constraint->aceitar_formatado)) {
$this->context->addViolation($constraint->message_cnpj, array('{{ value }}' => $value));
return false;
}
break;
case 'cpf':
if (!$this->checkCPF($value, $constraint->aceitar_formatado)) {
$this->context->addViolation($constraint->message_cpf, array('{{ value }}' => $value));
return false;
}
break;
case 'cpfcnpj':
default:
if (!($this->checkCPF($value, $constraint->aceitar_formatado) || $this->checkCNPJ($value, $constraint->aceitar_formatado))) {
$this->context->addViolation($constraint->message_cpfcnpj, array('{{ value }}' => $value));
return false;
}
break;
}
return true;
}
/**
* checkCPF
* Baseado em http://www.vivaolinux.com.br/script/Validacao-de-CPF-e-CNPJ/
* Algoritmo em http://www.geradorcpf.com/algoritmo_do_cpf.htm
* @param $cpf string
* @return bool
* @author Rafael Goulart <rafaelgou@rgou.net>
* Retirado do plugin do SF1 brFormExtraPlugin
*/
protected function checkCPF($cpf, $aceitar_formatado)
{
// Limpando caracteres especiais
if ($aceitar_formatado) {
$cpf = $this->valueClean($cpf);
}
// Quantidade mínima de caracteres ou erro
if (strlen($cpf) <> 11) return false;
// Primeiro dígito
$soma = 0;
for ($i = 0; $i < 9; $i++) {
$soma += ((10 - $i) * $cpf[$i]);
}
$d1 = 11 - ($soma % 11);
if ($d1 >= 10) $d1 = 0;
// Segundo Dígito
$soma = 0;
for ($i = 0; $i < 10; $i++) {
$soma += ((11 - $i) * $cpf[$i]);
}
$d2 = 11 - ($soma % 11);
if ($d2 >= 10) $d2 = 0;
if ($d1 == $cpf[9] && $d2 == $cpf[10]) {
return true;
} else {
return false;
}
}
/**
* checkCNPJ
* Baseado em http://www.vivaolinux.com.br/script/Validacao-de-CPF-e-CNPJ/
* Algoritmo em http://www.geradorcnpj.com/algoritmo_do_cnpj.htm
* @param $cnpj string
* @return bool
* @author Rafael Goulart <rafaelgou@rgou.net>
* Retirado do plugin do SF1 brFormExtraPlugin
*/
protected function checkCNPJ($cnpj, $aceitar_formatado)
{
if ($aceitar_formatado) {
$cnpj = $this->valueClean($cnpj);
}
if (strlen($cnpj) <> 14) return false;
// Primeiro dígito
$multiplicadores = array(5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2);
$soma = 0;
for ($i = 0; $i <= 11; $i++) {
$soma += $multiplicadores[$i] * $cnpj[$i];
}
$d1 = 11 - ($soma % 11);
if ($d1 >= 10) $d1 = 0;
// Segundo dígito
$multiplicadores = array(6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2);
$soma = 0;
for ($i = 0; $i <= 12; $i++) {
$soma += $multiplicadores[$i] * $cnpj[$i];
}
$d2 = 11 - ($soma % 11);
if ($d2 >= 10) $d2 = 0;
if ($cnpj[12] == $d1 && $cnpj[13] == $d2) {
return true;
} else {
return false;
}
}
/**
* valueClean
* Retira caracteres especiais
* @param $value string
* @return mixed|string
* @author Rafael Goulart <rafaelgou@rgou.net>
* Retirado do plugin do SF1 brFormExtraPlugin
*/
protected function valueClean($value)
{
$value = str_replace(array(')', '(', '/', '.', '-', ' '), '', $value);
if (strlen($value) == 15) {
$value = substr($value, 1, 15);
}
return $value;
}
}
|
Markdown
|
UTF-8
| 1,801 | 3.25 | 3 |
[
"MIT"
] |
permissive
|
# batch-run-cmd
## 1 Introduction
See `https://github.com/linzhi2013/batch-run-cmd`.
This is a Python3 package which will read command lines from an input file,
and run each line of command one by one, and check their exit status.
More importantly, if one command fails, you can just jump to next command
(`-e` option). Furthermore, you can check for the existences of result files
(`-E` option).
## 2 Installation
with `pip`
$ pip install batch-run-cmd
There will be a command `batch_run_cmd` created under the same directory as your `pip` command.
## 3 Usage
run `batch_run_cmd`
$ batch_run_cmd
usage: batch_run_cmd [-h] [-f <file>] [-e <int> [<int> ...]] [-E <str>]
To run command line by line, and check each exit status.
Then optionally check for the existences of result files.
Each line format:
echo "Hello world" && echo "Where are you?" ;Result-files: /path/to/resultfile1 /path/to/resultfile2
Internally, each line will be split by ";Result-files:" delimiter,
and the part before ";Result-files:" will be treated as a shell command,
the part after ";Result-files:" will be regardeds as result files.
Multiple result files are allowed, seperated by blank space(s).
See https://github.com/linzhi2013/batch-run-cmd for more details.
optional arguments:
-h, --help show this help message and exit
-f <file> commands in a file.
-e <int> [<int> ...] continue On Return Code for a shell command. [[0]]
-E <str> continue On: 'a': all files must exist; 'e': at least
one file must exist; 'o': omitted, i.e. do not check
for existences of files [o]
## 4 Citation
Currently I have no plan to publish `batch-run-cmd`.
|
Java
|
UTF-8
| 426 | 2.75 | 3 |
[] |
no_license
|
package com.rutgers.pm2;
public class MainFile {
public static void main(String[] args)
{
InsertionSort test = new InsertionSort();
test.push(10);
test.push(4);
test.push(14);
test.push(9);
test.push(3);
System.out.println("Linked test start");
test.printlist(test.head);
test.InsertionSort(test.head);
System.out.println("\nLinked test After Sorting");
test.printlist(test.head);
}
}
|
C++
|
UTF-8
| 209 | 2.8125 | 3 |
[] |
no_license
|
#include<iostream>
using namespace std;
int main(){
int n;
int count=1;
cin>>n;
for(int i=2;i<=n/2;i++){
if(n%i==0){
count++;
}
}
cout<<count<<endl;
}
|
Java
|
UTF-8
| 273 | 2.25 | 2 |
[] |
no_license
|
package com.app.util.exception;
/**
* common interface for various exception handler implementation.
* can be wrapper, logged or thrown back.
* @author ramkumarsundarajan
*
*/
public interface ExceptionHandler {
public void handle(Exception e,String message);
}
|
C#
|
UTF-8
| 4,928 | 2.625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SMX.Maths;
namespace SimplePang
{
public static class Game
{
public static RendererBase mRenderer;
public static InputBase mInput;
public static int mCurrentLevelIdx;
/// <summary>
/// Stopwatch used to measure time
/// </summary>
private static System.Diagnostics.Stopwatch mStopwatch = new System.Diagnostics.Stopwatch();
/// <summary>
/// Assembly name, to be used across the game to load embedded resources
/// </summary>
public static string AssemblyName = "SimplePang";
/// <summary>
/// Gravity velocity, in pixels per second
/// </summary>
public static Vector2 mGravityVel = new Vector2(0,500);
public static float mDt;
private static int mFPSCounter;
private static float mTimeCounter;
private static int mFPS;
public static int DefaultGameWidth
{
get { return 1920; }
}
public static int DefaultGameHeight
{
get { return 1080; }
}
public static Player mPlayer = new Player();
public static List<Level> mLevels = new List<Level>();
/// <summary>
///
/// </summary>
/// <returns></returns>
public static void ChangeLevel(int pLevelIdx)
{
mCurrentLevelIdx = pLevelIdx;
mPlayer.mPos = mLevels[mCurrentLevelIdx].mPlayerInitialPosition;
}
private static float CalcDt()
{
// A hi-resolution timer would be used in normal circumstances
mStopwatch.Stop();
System.TimeSpan span = mStopwatch.Elapsed;
mStopwatch.Reset();
mStopwatch.Start();
float dt = (float)span.TotalSeconds;
// Filter out negative or too big DTs to protect the code
dt = Math.Max(0.00001f, dt);
dt = Math.Min(0.15f, dt);
return dt;
}
/// <summary>
///
/// </summary>
public static void onFrameMove()
{
// Calc time
mDt = CalcDt();
// Calc FPS
mFPSCounter++;
mTimeCounter += mDt;
if (mTimeCounter >= 1)
{
mFPS = mFPSCounter;
mFPSCounter = 0;
mTimeCounter = 0;
}
// Actualizar lógica del juego
mLevels[mCurrentLevelIdx].onFrameMove();
mPlayer.onFrameMove();
}
public static void onFrameRender() {
// Dibujar juego
mLevels[mCurrentLevelIdx].onFrameRender();
mPlayer.onFrameRender();
#if(DEBUG)
mRenderer.DrawText("FPS: "+ mFPS, 18, 10, 10, Color4.White);
#endif
}
/// <summary>
///
/// </summary>
public static void LoadContents()
{
mRenderer = new RendererGDI();
mInput = new InputGDI();
mStopwatch.Reset();
// Ir a la carpeta dónde están los recursos. Enumerarlos y coger los png
System.IO.DirectoryInfo dinfo = new System.IO.DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + @"\Resources");
foreach(System.IO.FileInfo file in dinfo.GetFiles())
{
mRenderer.LoadTexture(file.FullName);
}
//Load texture for player
mPlayer.mTextureName = AppDomain.CurrentDomain.BaseDirectory + @"\Resources\Pang.png";
mRenderer.LoadTexture(mPlayer.mTextureName);
//Load texture for balloons
Ball.mTextureName = AppDomain.CurrentDomain.BaseDirectory + @"\Resources\Balloons.png";
mRenderer.LoadTexture(Ball.mTextureName);
// Cargar todos los niveles que estén presentes en la carpeta niveles
dinfo = new System.IO.DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + @"\Levels");
System.IO.FileInfo[] xmlFiles = dinfo.GetFiles("*.xml");
mLevels.Clear();
foreach (System.IO.FileInfo file in xmlFiles)
{
Level level = new Level();
level.mBackgroundTextureName = System.IO.Path.ChangeExtension(file.FullName, ".png");
mRenderer.LoadTexture(level.mBackgroundTextureName);
mLevels.Add(level);
//Cargar fichero xml del nivel
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.Load(file.FullName);
System.Xml.XmlNode levelNode = doc.SelectSingleNode("Level");
level.ConfigureFromXML(levelNode);
}
//Initialize game in level 0
ChangeLevel(0);
}
}
}
|
Python
|
UTF-8
| 121 | 3.875 | 4 |
[] |
no_license
|
print("hello World!!!")
x = 0
for index in range(10):
x += 10
print("The value of x is currently {0}".format(x))
|
C
|
UTF-8
| 881 | 3.046875 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
int main (int argc, char *argv[])
{
struct hostent *h;
if (argc != 2)
{
fprintf (stderr,"usage: getip address\n");
exit(1);
}
if((h=gethostbyname(argv[1])) == NULL)
{
perror("gethostbyname");
exit(1);
}
printf("Host name : %s\n", h->h_name);
int j;
for(j=0; j<4; j++)
printf("%d ", h->h_addr[j]);
printf("\n");
printf("IP Address : %s\n", inet_ntoa (*((struct in_addr *)h->h_addr)));
char ip[100];
//char ip1[100];
int ip1;
scanf("%s", ip);
// ip1 = printf("%d\n", inet_addr(ip));
ip1 = inet_addr(ip);
int i;
for(i=0; i<sizeof(ip1); i++)
printf("%d ", ((unsigned char*)&ip1)[i]);
printf("\n");
// struct in_addr ia;
// ia.s_addr = ip1;
printf("%s\n", inet_ntoa(ip1));
return 0;
}
|
Shell
|
UTF-8
| 22,173 | 3.4375 | 3 |
[
"Apache-2.0"
] |
permissive
|
#!/bin/bash
# itest bash script
# name : test-installer-creator.sh
# desc : Standalone installer test core script
# parameters which has to be exported from server:
# ITEST_BUILD_NAME
# ITEST_BUILD_VERSION
# ITEST_CREATOR_PATH
# ITEST_CREATOR_SUBDIRS
# ITEST_CREATOR_FILES
# ****************************
# PREPARING OF THE ENVIRONMENT
# ****************************
echo "System environment preparing ..."
cd ~
declare ITEST_DIR=$(pwd)/itest
declare ITEST_ARCHIVE=installer/test/qa-functional/itest.zip
declare ITEST_SLEEP=10000
declare SYSTEM_TEMP=/tmp
cd $ITEST_DIR
if [ "$(test -f config && echo "OK")" == "" ]; then
echo "config file is missing or it is corrupted"
exit 1
fi
# The path where the JDK which will be used is installed
declare TEMP_BUFFER=$(cat config | grep "itest.jdk")
declare ITEST_JDK=${TEMP_BUFFER:10}
# The version of the JDK on tha ITEST_JDK path -> it's important only for standalone and asbundle package
declare TEMP_BUFFER=$(cat config | grep "itest.reqjdkver")
declare ITEST_REQJDKVER=${TEMP_BUFFER:16}
# The path where all builds of nb/jdkbundles/asbundles are situated (on unix stations it is "/net/phoenix/space/builds/netbeans"
declare TEMP_BUFFER=$(cat config | grep "itest.nbsourcepath")
declare ITEST_NBSOURCEPATH=${TEMP_BUFFER:19}
# Path to the CVS command which is used for checkouting of the actual versions of the test's scripts
declare TEMP_BUFFER=$(cat config | grep "itest.cvs")
declare ITEST_CVS=${TEMP_BUFFER:10}
# Path to the SCP command which is used for copying of the test report to the beetle
declare TEMP_BUFFER=$(cat config | grep "itest.scp")
declare ITEST_SCP=${TEMP_BUFFER:10}
# checking the existence of the global variables
if [ "${ITEST_DIR}" == "" ]; then
echo "ITEST_DIR parameter missing"
exit 1
elif [ "${ITEST_JDK}" == "" ]; then
echo "ITEST_JDK parameter missing"
exit 1
elif [ "${ITEST_REQJDKVER}" == "" ]; then
echo "ITEST_REQJDKVER parameter missing"
exit 1
elif [ "${ITEST_NBSOURCEPATH}" == "" ]; then
echo "ITEST_NBSOURCEPATH parameter missing"
exit 1
elif [ "${ITEST_CVS}" == "" ]; then
echo "ITEST_CVS parameter missing"
exit 1
elif [ "${ITEST_SCP}" == "" ]; then
echo "ITEST_SCP parameter missing"
exit 1
fi
if [ "$(test -f config && echo "OK")" != "" ]; then
mv ./config $SYSTEM_TEMP/config
declare MOVE=yes
fi
rm -rf *
rm -rf ~/InstallShield
if [ "$MOVE" == "yes" ]; then
mv $SYSTEM_TEMP/config ./config
fi
$ITEST_CVS -d :pserver:qatester:user@server.domain:/cvs checkout $ITEST_ARCHIVE &>/dev/null
unzip -d ./ $ITEST_ARCHIVE &>/dev/null
rm -rf installer
if [ "$(test -f config && echo "OK")" == "" ]; then
mv ./config.new ./config
fi
if [ "$(test -f config && echo "OK")" == "" ]; then
echo "config file is missing or it is corrupted"
exit 1
fi
# ***********************
# UPDATING THE TEST FILES
# ***********************
echo "Updating the test files ..."
# Additional settings
export ITEST_TEMP=$ITEST_DIR/temp
export ITEST_LOGS=$ITEST_DIR/logs
export ITEST_BIN=$ITEST_DIR/bin
export ITEST_JTOOL=$ITEST_DIR/jtool
# Inicialization of the local variables
declare CVS_SCRIPTS=installer/test/qa-functional/scripts/actions
declare LOCAL_SCRIPTS=$ITEST_DIR/scripts
# Checkouting for the actual version
cd $ITEST_DIR
$ITEST_CVS -d :pserver:qatester:user@server.domain:/cvs checkout $CVS_SCRIPTS &>/dev/null
rm -rf $LOCAL_SCRIPTS
mv $ITEST_DIR/$CVS_SCRIPTS $LOCAL_SCRIPTS
rm -rf $ITEST_DIR/installer
chmod +x $LOCAL_SCRIPTS/*
# *********************************
# POST UPDATING ENVIRONMENT SETTING
# *********************************
echo "Post updating environment setting ..."
# Directories existence check
if [ "$(test -d $ITEST_TEMP && echo "OK")" == "" ]; then
mkdir $ITEST_TEMP
fi
if [ "$(test -d $ITEST_LOGS && echo "OK")" == "" ]; then
mkdir $ITEST_LOGS
fi
# Post-checkout configuration of the environment
cd ${LOCAL_SCRIPTS}
# testing of the parameters exported from server
if [ "${ITEST_BUILD_NAME}" == "" ]; then
echo "ITEST_BUILD_NAME parameter missing"
exit 1
elif [ "${ITEST_BUILD_VERSION}" == "" ]; then
echo "ITEST_BUILD_VERSION parameter missing"
exit 1
elif [ "${ITEST_CREATOR_PATH}" == "" ]; then
echo "ITEST_CREATOR_PATH parameter missing"
exit 1
elif [ "${ITEST_CREATOR_SUBDIRS}" == "" ]; then
echo "ITEST_CREATOR_SUBDIRS parameter missing"
exit 1
elif [ "${ITEST_CREATOR_FILES}" == "" ]; then
echo "ITEST_CREATOR_FILES parameter missing"
exit 1
fi
# finding out of the platform
case $(uname) in
CYGWIN_NT-5.1) declare ITEST_PLATFORM_IDENTIFIER=win
;;
CYGWIN_NT-5.0) declare ITEST_PLATFORM_IDENTIFIER=win
;;
Linux) declare ITEST_PLATFORM_IDENTIFIER=linux
;;
SunOS) if [ "$(uname -p | grep "i386")" != "" ]; then
declare ITEST_PLATFORM_IDENTIFIER=x86
else
declare ITEST_PLATFORM_IDENTIFIER=sparc
fi
;;
*) echo "UNKNOWN PLATFORM"
exit 1
;;
esac
# ********************
# STARTING OF THE TEST
# ********************
echo "Test started ..."
echo "***"
echo ""
declare ITEST_PLATFORM_DETAIL=$(uname -a)
declare ITEST_TESTED_FILE=${ITEST_NBSOURCEPATH}$ITEST_CREATOR_PATH$(ls ${ITEST_NBSOURCEPATH}$ITEST_CREATOR_PATH | grep "${ITEST_PLATFORM_IDENTIFIER}" | grep netbeans)
declare ITEST_TESTED_CREATOR_FILE=${ITEST_NBSOURCEPATH}$ITEST_CREATOR_PATH$(ls ${ITEST_NBSOURCEPATH}$ITEST_CREATOR_PATH | grep "${ITEST_PLATFORM_IDENTIFIER}" | grep CreatorPack)
declare ITEST_JAVA=${ITEST_JDK}/jre/bin/java
declare ITEST_JAR=${ITEST_JDK}/bin/jar
declare ITEST_TEST_NAME="NetBeans IDE Standalone + Creator Pack Installer Test"
declare ITEST_CORE_LIB=${ITEST_JTOOL}/itest-core.jar
declare ITEST_JEMMY_LIB=${ITEST_JTOOL}/lib/jemmy.jar
declare ITEST_CANCEL_LIB=${ITEST_JTOOL}/itest-action-cancel.jar
declare ITEST_INSTALLERCREATOR_LIB=${ITEST_JTOOL}/itest-action-installercreator.jar
declare ITEST_IDE_JARFILE=${ITEST_TEMP}/standalone.jar
declare ITEST_CREATOR_JARFILE=${ITEST_TEMP}/creator.jar
# report header
echo "Testname : "$ITEST_TEST_NAME
echo ""
echo "Platform : "$ITEST_PLATFORM_DETAIL
echo "Tested IDE file : "$ITEST_TESTED_FILE
echo "Tested Creator file : "$ITEST_TESTED_CREATOR_FILE
echo "Date : "$(date)
echo ""
echo "Results :"
# runing the action script "action-bintojar.sh"
# TESTSTEP 1
# **********
echo -n "Teststep 1 - Converting the IDE binary file to the JAR....."
sleep 1
export ACTION_BINTOJAR_BINSOURCE=${ITEST_TESTED_FILE}
export ACTION_BINTOJAR_JARTARGET=${ITEST_IDE_JARFILE}
export ACTION_BINTOJAR_JAR=${ITEST_JAR}
export ACTION_BINTOJAR_TEMPDIR=${ITEST_TEMP}
export ACTION_BINTOJAR_PLATFORM=${ITEST_PLATFORM_IDENTIFIER}
./action-fail.sh
./action-bintojar.sh &>/dev/null
if [ "$?" = "0" ]; then
echo PASS
else
echo FAIL
fi
# runing the action script "action-bintojar.sh"
# TESTSTEP 2
# **********
echo -n "Teststep 2 - Converting the Creator binary file to the JAR....."
sleep 1
export ACTION_BINTOJAR_BINSOURCE=${ITEST_TESTED_CREATOR_FILE}
export ACTION_BINTOJAR_JARTARGET=${ITEST_CREATOR_JARFILE}
./action-fail.sh
./action-bintojar.sh &>/dev/null
if [ "$?" = "0" ]; then
echo PASS
else
echo FAIL
fi
# install the IDE
# TESTSTEP 3
# **********
echo "Teststep 3 - IDE Installer test"
echo ""
echo "==>"
echo ""
sleep 1
declare INSTALLER_TEST_INSTALLDIR=${ITEST_TEMP}/nb-standalone-$RANDOM
if [ "${ITEST_PLATFORM_IDENTIFIER}" != "win" ]; then
declare INSTALLER_TEST_NWRITEDIR=${ITEST_TEMP}/nwritedir
rm -rf ${INSTALLER_TEST_NWRITEDIR}
mkdir ${INSTALLER_TEST_NWRITEDIR}
chmod 000 ${INSTALLER_TEST_NWRITEDIR}
else
declare INSTALLER_TEST_NWRITEDIR=${ITEST_NBSOURCEPATH}
fi
if [ "${ITEST_PLATFORM_IDENTIFIER}" == "win" ]; then
declare INSTALL_CLASSPATH=$(cygpath -wp ${ITEST_IDE_JARFILE}:${ITEST_CORE_LIB}:${ITEST_JEMMY_LIB})
declare INSTALL_DIR=$(cygpath -wp ${INSTALLER_TEST_INSTALLDIR})
declare INSTALL_JDKHOME=$(cygpath -wp ${ITEST_JDK})
declare INSTALL_NWRITEDIR=$(cygpath -wp ${INSTALLER_TEST_NWRITEDIR})
else
declare INSTALL_CLASSPATH=${ITEST_IDE_JARFILE}:${ITEST_CORE_LIB}:${ITEST_JEMMY_LIB}
declare INSTALL_DIR=${INSTALLER_TEST_INSTALLDIR}
declare INSTALL_JDKHOME=${ITEST_JDK}
declare INSTALL_NWRITEDIR=${INSTALLER_TEST_NWRITEDIR}
fi
$ITEST_JAVA -cp $INSTALL_CLASSPATH org.netbeans.itest.Run -action installersa -log console -sleep $ITEST_SLEEP -name "netbeans standalone installer test" -installersa.nbpath $INSTALL_DIR -installersa.jdkpath $INSTALL_JDKHOME -installersa.nwritedir $INSTALL_NWRITEDIR -installersa.buildname "$ITEST_BUILD_NAME" -installersa.buildversion "$ITEST_BUILD_VERSION"
if [ "${ITEST_PLATFORM_IDENTIFIER}" != "win" ]; then
chmod 777 ${INSTALLER_TEST_NWRITEDIR}
rm -rf ${INSTALLER_TEST_NWRITEDIR}
fi
echo ""
echo "==>"
echo ""
# packing installed netbeans into zip archive
# *******************************************
echo "Packing installed netbeans..."
declare INSTALLER_ARCHIVE=$ITEST_TEMP/nb.zip
zip -r $INSTALLER_ARCHIVE $INSTALLER_TEST_INSTALLDIR &>/dev/null
echo ""
# running the uninstaller test
# TESTSTEP 4
# **********
echo "Teststep 4 - NetBeans IDE Uninstaller test"
echo ""
echo "==>"
echo ""
sleep 1
declare UNINSTALLER_JAR=${INSTALLER_TEST_INSTALLDIR}/_uninst/uninstall.jar
if [ "${ITEST_PLATFORM_IDENTIFIER}" == "win" ]; then
declare UNINSTALL_CLASSPATH=$(cygpath -wp ${UNINSTALLER_JAR}:${ITEST_CORE_LIB}:${ITEST_JEMMY_LIB})
else
declare UNINSTALL_CLASSPATH=${UNINSTALLER_JAR}:${ITEST_CORE_LIB}:${ITEST_JEMMY_LIB}
fi
$ITEST_JAVA -cp $UNINSTALL_CLASSPATH org.netbeans.itest.Run -action uninstaller -log console -sleep $ITEST_SLEEP -name "netbeans uninstaller test" -uninstaller.buildname "$ITEST_BUILD_NAME" -uninstaller.buildversion "$INSTALL_BUILD_VERSION"
echo ""
echo "==>"
echo ""
# unpacking netbeans
# ******************
echo "Unpacking netbeans..."
unzip $INSTALLER_ARCHIVE -d / &>/dev/null
echo ""
# install the creator pack
# TESTSTEP 5
# **********
echo "Teststep 5 - Creator Installer test"
echo ""
echo "==>"
echo ""
sleep 1
if [ "${ITEST_PLATFORM_IDENTIFIER}" == "win" ]; then
declare INSTALL_CREATOR_CLASSPATH=$(cygpath -wp ${ITEST_CREATOR_JARFILE}:${ITEST_CORE_LIB}:${ITEST_JEMMY_LIB})
else
declare INSTALL_CREATOR_CLASSPATH=${ITEST_CREATOR_JARFILE}:${ITEST_CORE_LIB}:${ITEST_JEMMY_LIB}
fi
$ITEST_JAVA -cp $INSTALL_CREATOR_CLASSPATH org.netbeans.itest.Run -action installercreator -log console -sleep $ITEST_SLEEP -name "netbeans standalone+creator pack installer test" -Installercreator.NetBeansPath "$INSTALL_DIR" -Installercreator.NetBeansVersion "$ITEST_BUILD_VERSION" -Installercreator.CreatorPackDir "rave2.0" -Installercreator.CreatorPackSubdirList "$ITEST_CREATOR_SUBDIRS" -Installercreator.CreatorPackFileList "$ITEST_CREATOR_FILES"
echo ""
echo "==>"
echo ""
# ***************************
# CLEANING UP THE ENVIRONMENT
# ***************************
echo ""
echo "***"
echo "Test finished ..."
echo "System environment cleaning ..."
cd $ITEST_DIR
if [ "$(test -f config && echo "OK")" != "" ]; then
mv ./config $SYSTEM_TEMP/config
declare MOVE=yes
fi
rm -rf *
rm -rf ~/InstallShield
if [ "$MOVE" == "yes" ]; then
mv $SYSTEM_TEMP/config ./config
fi
# ****
# DONE
# ****
echo "Done"
pkill -u tester &>/dev/null
exit 0
|
Python
|
UTF-8
| 737 | 3.21875 | 3 |
[] |
no_license
|
def MinNoOnes(a,low,high):
if low>high:
return -1
else:
mid=int((low+high)/2)
if(a[low]==1):
return low
if a[mid]==0:
return MinNoOnes(a,mid+1,high)
else:
return MinNoOnes(a,low,mid)
#
# a=[0,1,1,1,1,1,1,1,1]
# n=len(a)-1
# val=MinNoOnes(a,0,n)
# num=n-val+1
# print(num)
list=[[0,0,1],[0,0,1,1,1,1,1],[0,0,1]]
minimum=[]
def findones(list):
for i in range(0,len(list)):
n=len(list[i])-1
index=MinNoOnes(list[i],0,n)
if(index!=-1):
num=n-index+1
minimum.append(num)
else:
minimum.append(-1)
findones(list)
val=minimum.index(min(minimum))
print(val)
# for i,ele in enumerate(min):
|
Java
|
UTF-8
| 1,510 | 2.34375 | 2 |
[] |
no_license
|
package com.ljx.chapter3_1.unit;
import com.ljx.chapter3_1.configuration.Chapter3_2Configuration;
import com.ljx.chapter3_1.model.User;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
public class Chapter32ApplicationTests {
AnnotationConfigApplicationContext applicationContext;
@Before
public void setUp() {
applicationContext = new AnnotationConfigApplicationContext(Chapter3_2Configuration.class);
}
@Test
public void contextLoads() {
Assert.assertTrue(applicationContext.containsBean("user"));
// spring will auto scan the user component and inject it
// with class name ,first Letter lowcase
Assert.assertFalse(applicationContext.containsBean("User"));
Assert.assertTrue(applicationContext.containsBean("employee"));
Assert.assertFalse(applicationContext.containsBean("indexController"));
}
@Test
public void valueTest() {
User user = applicationContext.getBean("user", User.class);
Assert.assertNotNull(user);
Assert.assertEquals(user.getId(),Long.valueOf(1L));
Assert.assertEquals(user.getUserName(),"Peggy");
Assert.assertEquals(user.getNote(),"HelloWorld Peggy");
}
}
|
TypeScript
|
UTF-8
| 484 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
export class Transformation {
name: string;
disabled?: boolean;
collections?: string[];
applyToAllDocuments?: boolean;
script?: string;
}
export function serializeTransformation(transformation: Transformation) {
return {
Name: transformation.name,
Disabled: transformation.disabled,
Collections: transformation.collections,
ApplyToAllDocuments: transformation.applyToAllDocuments,
Script: transformation.script
}
}
|
C++
|
UTF-8
| 3,603 | 2.515625 | 3 |
[] |
no_license
|
// ==============================================================
// This file is part of Glest (www.glest.org)
//
// Copyright (C) 2001-2008 Marti�o Figueroa
//
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version
// ==============================================================
#ifndef _MAPEDITOR_PROGRAM_H_
#define _MAPEDITOR_PROGRAM_H_
#include "map.h"
#include "renderer.h"
#include <stack>
using std::stack;
namespace MapEditor {
class MainWindow;
enum ChangeType {
ctNone = -1,
ctHeight,
ctSurface,
ctObject,
ctResource,
ctLocation,
ctGradient,
ctAll
};
// =============================================
// class Undo Point
// A linked list class that is more of an extension / modification on
// the already existing Cell struct in map.h
// Provides the ability to only specify a certain property of the map to change
// =============================================
class UndoPoint {
private:
// Only keep a certain number of undo points in memory otherwise
// Big projects could hog a lot of memory
const static int MAX_UNDO_LIST_SIZE = 100; // TODO get feedback on this value
static int undoCount;
ChangeType change;
// Pointers to arrays of each property
int *surface;
int *object;
int *resource;
float *height;
// Map width and height
static int w;
static int h;
public:
UndoPoint();
~UndoPoint();
void init(ChangeType change);
void revert();
inline ChangeType getChange() const { return change; }
};
class ChangeStack : public std::stack<UndoPoint> {
public:
static const int maxSize = 100;
void clear() { c.clear(); }
void push(UndoPoint p) {
if (c.size() >= maxSize) {
c.pop_front();
}
stack<UndoPoint>::push(p);
}
};
// ===============================================
// class Program
// ===============================================
class Program {
friend class UndoPoint;
private:
Renderer renderer;
int offsetX, offsetY;
int cellSize;
static Map *map;
ChangeStack undoStack, redoStack;
public:
Program(int w, int h);
~Program();
//map cell change
void glestChangeMapHeight(int x, int y, int Height, int radius);
void pirateChangeMapHeight(int x, int y, int Height, int radius);
void changeMapSurface(int x, int y, int surface, int radius);
void changeMapObject(int x, int y, int object, int radius);
void changeMapResource(int x, int y, int resource, int radius);
void changeStartLocation(int x, int y, int player);
void setUndoPoint(ChangeType change);
bool undo();
bool redo();
//map ops
void reset(int w, int h, int alt, int surf);
void resize(int w, int h, int alt, int surf);
void resetFactions(int maxFactions);
void setRefAlt(int x, int y);
void flipX();
void flipY();
void randomizeMapHeights();
void randomizeMap();
void switchMapSurfaces(int surf1, int surf2);
void loadMap(const string &path);
void saveMap(const string &path);
//map misc
bool setMapTitle(const string &title);
bool setMapDesc(const string &desc);
bool setMapAuthor(const string &author);
void setMapAdvanced(int altFactor, int waterLevel);
//misc
void renderMap(int w, int h);
void setOffset(int x, int y);
void incCellSize(int i);
int getCellSize() const { return cellSize; }
void setCellSize(int s) { cellSize = s; }
void resetOffset();
int getObject(int x, int y);
int getResource(int x, int y);
static const Map *getMap() {return map;}
Vec2i getCellCoords(int x, int y);
};
}// end namespace
#endif
|
Markdown
|
UTF-8
| 1,055 | 2.609375 | 3 |
[] |
no_license
|
# Pi Companion
A portable linux companion for my iPad Pro.
## Getting Started
Burn the latest raspbian lite image onto an SD Card. Balena etcher is a
reasonable tool on windows for this.
Create an empty file called `ssh` in the boot dir of the new SD.
Create a file called `wpa-supplicant.conf` in the boot dir of the new SD with
the WiFi connection details. It's possible to configure multiple networks to
try in order. Something like:
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=GB
network={
priority=30
ssid="Phone"
psk="???"
key_mgmt=WPA-PSK
id_str="phone"
}
network={
priority=50
ssid=“Home"
psk="???"
key_mgmt=WPA-PSK
id_str="home"
}
Boot the device, then reboot the device for all initial setup to take effect.
Run the following commands:
sudo apt update && sudo apt upgrade
sudo apt install ansible
Now run the following command to bootstrap the instance:
sudo ansible-playbook pi-companion.yml
|
Java
|
UTF-8
| 465 | 2.046875 | 2 |
[] |
no_license
|
package com.abaghel.examples.spring.springboot.security.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.abaghel.examples.spring.springboot.security.entity.RememberMeToken;
/**
*
* @author abaghel
*
*/
public interface RememberMeTokenRepository extends JpaRepository<RememberMeToken, String> {
List<RememberMeToken> findByUserName(String userName);
RememberMeToken findBySeries(String series);
}
|
C++
|
UTF-8
| 1,616 | 3.5 | 4 |
[] |
no_license
|
#pragma once
#include <mutex>
#include <shared_mutex>
#include <type_traits>
template <class Ty>
class Synchronized {
public:
using value_type = std::remove_const_t<std::remove_reference_t<Ty>>;
using mutex_t = std::mutex;
using guard_t = std::lock_guard<mutex_t>;
template <class Guard, class Value>
struct Reference {
template <class Mutex>
Reference(Mutex& mtx, Value& value) : guard(mtx), ref_to_value(value) {}
Guard guard;
Value& ref_to_value;
};
using reference = Reference<guard_t, value_type>;
using const_reference = Reference<guard_t, const value_type>;
public:
template <class U = Ty,
std::enable_if_t<std::is_default_constructible_v<U>, int> = 0>
Synchronized() noexcept(std::is_nothrow_default_constructible_v<Ty>) {}
Synchronized(const Synchronized&) = default;
Synchronized(Synchronized&&) = default;
template <class... Types>
Synchronized(std::in_place_t, Types&&... args) noexcept(
std::is_nothrow_constructible_v<Ty, Types...>)
: m_value(std::forward<Types>(args)...) {}
Synchronized& operator=(const Synchronized&) = default;
Synchronized& operator=(Synchronized&&) = default;
Synchronized& operator=(const Ty& new_value) {
GetAccess().ref_to_value = new_value;
return *this;
}
Synchronized& operator=(Ty&& new_value) {
GetAccess().ref_to_value = std::move(new_value);
return *this;
}
reference GetAccess() { return reference(m_mtx, m_value); }
const_reference GetAccess() const { return const_reference(m_mtx, m_value); }
private:
Ty m_value{};
mutable mutex_t m_mtx;
};
|
JavaScript
|
UTF-8
| 2,086 | 2.734375 | 3 |
[] |
no_license
|
const hamburgerBtn = document.querySelector(".hamburger-menu");
const hamburgerNavbar = document.querySelector(".hamburger-navbar");
//Mobile navigation
const mbInicio = document.querySelector('#mb-inicio');
const mbServicios = document.querySelector('#mb-servicios');
const mbProyectos = document.querySelector('#mb-proyectos');
const mbContacto = document.querySelector('#mb-contacto');
//desktop navigation
const dkInicio = document.querySelector('#dk-inicio');
const dkServicios = document.querySelector('#dk-servicios');
const dkProyectos = document.querySelector('#dk-proyectos');
const dkContacto = document.querySelector('#dk-contacto');
// const desktopNav = document.querySelector(".desktop-nav");
// const navbarTop = desktopNav.offsetTop;
let openedMenu = false;
hamburgerBtn.addEventListener("click", () => {
if (!openedMenu) {
hamburgerNavbar.classList.add("open");
// hamburgerNavbar.style.animation='open-hamburger 0.5 ease-in';
openedMenu = true;
} else {
hamburgerNavbar.classList.remove("open");
openedMenu = false;
}
});
// Navigation Listeners
dkInicio.addEventListener('click', inicioView )
dkServicios.addEventListener('click', serviciosView)
dkProyectos.addEventListener('click', proyectosView)
dkInicio.addEventListener('click', contactoView)
mbInicio.addEventListener('click', inicioView)
mbServicios.addEventListener('click', serviciosView)
mbProyectos.addEventListener('click', proyectosView)
mbContacto.addEventListener('click', contactoView)
function inicioView(e) {
e.preventDefault();
document.querySelector("#inicio").scrollIntoView({
behavior: "smooth",
});
}
function serviciosView(e) {
e.preventDefault();
document.querySelector("#servicios").scrollIntoView({
behavior: "smooth",
});
}
function proyectosView(e) {
e.preventDefault();
document.querySelector("#proyectos").scrollIntoView({
behavior: "smooth",
});
}
function contactoView(e) {
console.log('asd')
e.preventDefault();
document.querySelector("#contacto").scrollIntoView({
behavior: "smooth",
});
}
|
Shell
|
UTF-8
| 973 | 3.4375 | 3 |
[
"MIT"
] |
permissive
|
#!/bin/bash
set -e
mkdir -p $OUTPUT_BINARIES
mkdir -p $GOPACKAGES
echo ' '
echo '------------------'
echo "Adding user $DO_USER"
echo '------------------'
echo ' '
useradd $DO_USER -u $DO_UID
echo '------------------'
echo "Reading $GOREPOS and fetching with git"
echo '------------------'
echo ' '
# REMOVE OLD PACKAGES
set -x
cd $GOPACKAGES
rm -rf $GOPACKAGES/*
# Clone GIT REPOS TO GET PAKCAGES
cat $INPUT_REPOS | while read package
do
cd $GOPACKAGES
go get $package && \
cd $OUTPUT_BINARIES && \
GOOS=windows GOARCH=amd64 go build -o ${package}-windows.exe ${package} && mv ${package}-windows.exe ./$(basename ${package})-windows.exe
GOOS=linux GOARCH=amd64 go build -o ${package}-linux ${package} && mv ${package}-linux ./$(basename ${package})-linux
GOOS=darwin GOARCH=amd64 go build -o ${package}-darwin ${package} && mv ${package}-darwin ./$(basename ${package})-darwin
done
set +x
chown -R $DO_USER:$DO_USER /gowork
ls -alsht $OUTPUT_BINARIES
|
C#
|
UTF-8
| 1,532 | 2.78125 | 3 |
[] |
no_license
|
using UnityEngine;
namespace Environment {
[System.Serializable]
public class SerializableEnvironmentColor {
[SerializeField] public Color skyColor1;
[SerializeField] public Color skyColor2;
[SerializeField] public Color skyColor3;
[SerializeField] public Color skyColor4;
[SerializeField] public Color skyColor5;
[SerializeField] public float proportion;
public SerializableEnvironmentColor(EnvironmentColor currentColor) {
this.skyColor1 = currentColor.skyColor1;
this.skyColor2 = currentColor.skyColor2;
this.skyColor3 = currentColor.skyColor3;
this.skyColor4 = currentColor.skyColor4;
this.skyColor5 = currentColor.skyColor5;
this.proportion = currentColor.proportion;
}
public EnvironmentColor ToEnvironmentColor() {
return new EnvironmentColor(this.skyColor1, this.skyColor2, this.skyColor3, this.skyColor4, this.skyColor5,
this.proportion);
}
private string ColorToCodeString(Color c) {
return $"new Color({c.r:0.00}f, {c.g:0.00}f, {c.b:0.00}f)";
}
public string ToCodeString() {
return
$"new EnvironmentColor({this.ColorToCodeString(this.skyColor1)}, {this.ColorToCodeString(this.skyColor2)}, {this.ColorToCodeString(this.skyColor3)}, {this.ColorToCodeString(this.skyColor4)}, {this.ColorToCodeString(this.skyColor5)}, {this.proportion:0.00}f);";
}
}
}
|
JavaScript
|
UTF-8
| 4,064 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
'use strict'
/**
* @license
* Copyright Little Star Media Inc. and other contributors.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* 'Software'), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* The touch controls module.
*
* @module axis/controls/touch
* @type {Function}
*/
void module.exports
/**
* Module dependencies.
* @private
*/
import { Quaternion } from 'three'
import AxisController from './controller'
/**
* TouchController constructor
*
* @public
* @constructor
* @class TouchController
* @extends AxisController
* @see {@link module:axis/controls/controller~AxisController}
* @param {Axis} scope - The axis instance
*/
export default class TouchController extends AxisController {
constructor (scope) {
super(scope, document)
/**
* Predicate indicating if touching.
*
* @public
* @name state.isTouching
* @type {Boolean}
*/
this.state.isTouching = false
/**
* Drag state
*
* @public
* @name state.drag
* @type {Object}
*/
this.state.drag = {
/**
* X coordinate drag state
*
* @public
* @name state.drag.x
* @type {Number}
*/
x: 0,
/**
* Y coordinate drag state
*
* @public
* @name state.drag.y
* @type {Number}
*/
y: 0
}
/**
* Current touchs
*
* @public
* @name state.touches
* @type {Array}
*/
this.state.touches = []
/**
* Current touch quaternion
*
* @public
* @name state.quaternions.touch
* @type {THREE.Quaternion}
*/
this.state.quaternions.touch = new Quaternion()
// initialize event delegation
this.events.bind('touchstart')
this.events.bind('touchmove')
this.events.bind('touchend')
this.events.bind('touch')
}
/**
* Handle 'ontouchstart' event.
*
* @private
* @param {Event} e
*/
ontouchstart (e) {
const touch = e.touches[0]
this.state.isTouching = true
this.state.touches = e.touches
this.state.drag.x = touch.pageX
this.state.drag.y = touch.pageY
}
/**
* Handle 'ontouchmove' event.
*
* @private
* @param {Event} e
*/
ontouchmove (e) {
const touch = e.touches[0]
const x = touch.pageX - this.state.drag.x
const y = touch.pageY - this.state.drag.y
if (this.scope.domElement.contains(e.target)) {
this.state.drag.x = touch.pageX
this.state.drag.y = touch.pageY
this.rotate({ x, y })
}
}
/**
* Handle 'ontouchend' event.
*
* @private
* @param {Event} e
*/
ontouchend (e) {
this.state.isTouching = false
}
/**
* Update touch controller state.
*
* @public
*/
update () {
if (!this.state.isTouching) { return this }
super.update()
this.state.quaternions.touch.copy(this.state.target.quaternion)
return this
}
}
|
C++
|
UTF-8
| 733 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
#include<sequencer.hpp>
#include<selector.hpp>
#include<action.hpp>
#include<iostream>
bool doorOpen = true;
bool isDoorOpen() {
if (doorOpen) {
std::cout << "door is opened" << std::endl;
return true;
}
std::cout << "door is closed" << std::endl;
return false;
}
bool closeDoor() {
doorOpen = false;
std::cout << "closed door" << std::endl;
return true;
}
int main() {
std::cout << "BT" << std::endl;
Sequencer* rootDoor = new Sequencer();
Sequencer* checkDoor = new Sequencer();
Action* isDoorOpenNode = new Action(isDoorOpen);
Action* closeDoorNode = new Action(closeDoor);
rootDoor->addChild(checkDoor);
checkDoor->addChild(isDoorOpenNode);
checkDoor->addChild(closeDoorNode);
rootDoor->Invoke();
}
|
Ruby
|
UTF-8
| 433 | 3.765625 | 4 |
[
"MIT"
] |
permissive
|
class Question
attr_accessor :num1, :num2, :answer, :operator
def initialize
@num1 = 1 + rand(20)
@num2 = 1 + rand(20)
@operator = ["+", "-", "*"].sample
@answer = num1.method(operator).(num2)
end
def generate_question
puts "What is #{num1} #{operator} #{num2}?"
end
def verify_answer(user_answer)
if user_answer.to_i == @answer
return true
else
return false
end
end
end
|
Java
|
UTF-8
| 771 | 3.859375 | 4 |
[] |
no_license
|
package com.class33;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class HomeWork {
public static void main(String[] args) {
/*create an arraylist of cars and retrieve all the values using
* 3 diffrent ways
*/
List<String> car=new ArrayList<>();
car.add("Nissan");
car.add("Toyota");
car.add("Honda");
car.add("BMW");
System.out.println("*******first way*****");
for(String cars:car) {
System.out.println(cars);
}
System.out.println("********second way*******");
for(int i=0; i<car.size(); i++) {
System.out.println(car.get(i));
}
System.out.println("***********third way*********");
Iterator it=car.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
}
|
Java
|
UTF-8
| 4,968 | 2.265625 | 2 |
[] |
no_license
|
package com.hs3.lotts.n11x5.nx;
import com.hs3.lotts.LotteryUtils;
import com.hs3.lotts.NumberView;
import com.hs3.lotts.PermutateUtils;
import com.hs3.lotts.PlayerBase;
import com.hs3.utils.ListUtils;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public abstract class N11x5SinglePlayer extends PlayerBase {
private static final List<Integer> INDEXS = Arrays.asList(new Integer[]{Integer.valueOf(0), Integer.valueOf(1),
Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4)});
private String groupName = "任选";
private String title = "单式";
private List<String> nums = new ArrayList(
Arrays.asList(new String[]{"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11"}));
protected abstract int getSelectNum();
protected abstract int getWinNum();
protected List<Integer> getIndexs() {
return INDEXS;
}
public String getGroupName() {
return this.groupName;
}
public String getTitle() {
return this.title;
}
public NumberView[] getNumView() {
return null;
}
public Integer getCount(String bets) {
List<String> lines = ListUtils.toList(bets, "\\s+");
for (String line : lines) {
List<String> n = LotteryUtils.toListByLength(line, Integer.valueOf(2));
if (n.size() != getSelectNum()) {
return Integer.valueOf(0);
}
if (ListUtils.hasSame(n)) {
return Integer.valueOf(0);
}
if (n.retainAll(this.nums)) {
return Integer.valueOf(0);
}
}
return Integer.valueOf(lines.size());
}
public BigDecimal getWin(String bets, List<Integer> openNums) {
List<String> lines = ListUtils.toList(bets, "\\s+");
BigDecimal win = new BigDecimal("0");
for (String line : lines) {
List<Integer> n = LotteryUtils.toIntListByLength(line, 2);
int winNum = 0;
for (int i = 0; i < n.size(); i++) {
int num = ((Integer) n.get(i)).intValue();
if (openNums.contains(Integer.valueOf(num))) {
winNum++;
}
}
if (winNum == getWinNum()) {
win = win.add(getBonus());
}
}
return win;
}
private String getKey(List<Integer> ns) {
String format = "";
for (int i = 0; i < 5; i++) {
if (ns.contains(Integer.valueOf(i))) {
format = format + ",%s";
} else {
format = format + ",-";
}
}
return format.substring(1);
}
public Map<String, BigDecimal> ifOpenWin(String bets) {
Map<String, BigDecimal> result = new HashMap();
List<String> lines = ListUtils.toList(bets, "\\s+");
List<List<Integer>> allBuy = new ArrayList();
for (String line : lines) {
List<Integer> n = LotteryUtils.toIntListByLength(line, 2);
allBuy.add(n);
}
int allNum = getSelectNum();
/**
* jd-gui Object indexs = PermutateUtils.getCombinSelect(getIndexs(), allNum);
* Iterator localIterator3; for (Iterator localIterator2 = allBuy.iterator();
* localIterator2.hasNext(); localIterator3.hasNext()) { List<Integer> num =
* (List)localIterator2.next();
*
* Set<String> all = PermutateUtils.getPerms(num.toArray(new Object[allNum]),
* ",");
*
* localIterator3 = all.iterator(); continue;String a =
* (String)localIterator3.next(); Object[] nnn = ListUtils.toList(a).toArray(new
* Object[allNum]); for (String i : (Set)indexs) { String k =
* getKey(ListUtils.toIntList(i)); String key = String.format(k, nnn);
* addMap(result, key, getBonus()); } }
*/
Set indexs = PermutateUtils.getCombinSelect(getIndexs(), allNum);
for (Iterator iterator1 = allBuy.iterator(); iterator1.hasNext(); ) {
List<Integer> num = (List) iterator1.next();
Set<String> all = PermutateUtils.getPerms(num.toArray(new Object[allNum]), ",");
for (Iterator iterator2 = all.iterator(); iterator2.hasNext(); ) {
String a = (String) iterator2.next();
Object nnn[] = ListUtils.toList(a).toArray(new Object[allNum]);
String key;
for (Iterator iterator3 = indexs.iterator(); iterator3.hasNext(); addMap(result, key, getBonus())) {
String i = (String) iterator3.next();
String k = getKey(ListUtils.toIntList(i));
key = String.format(k, nnn);
}
}
}
return result;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.